gitstack

grindlemire/go-tui code browser

1.7 KB 78 lines 2026-03-15 · e5befc1 raw
 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
package main

import tui "github.com/grindlemire/go-tui"

type myApp struct {
	app          *tui.App
	showSettings *tui.State[bool]
	textarea     *tui.TextArea
}

func InlineApp() *myApp {
	a := &myApp{
		showSettings: tui.NewState(false),
	}
	a.textarea = tui.NewTextArea(
		tui.WithTextAreaWidth(60),
		tui.WithTextAreaBorder(tui.BorderRounded),
		tui.WithTextAreaPlaceholder("Type here..."),
		tui.WithTextAreaOnSubmit(a.send),
	)
	return a
}

func (a *myApp) BindApp(app *tui.App) {
	a.app = app
	a.showSettings.BindApp(app)
	a.textarea.BindApp(app)
}

func (a *myApp) send(text string) {
	if text == "" {
		return
	}
	a.textarea.Clear()
	a.app.PrintAboveln("You: %s", text)
}

func (a *myApp) toggleSettings() {
	if a.showSettings.Get() {
		_ = a.app.ExitAlternateScreen()
		a.showSettings.Set(false)
		return
	}
	a.showSettings.Set(true)
	_ = a.app.EnterAlternateScreen()
}

func (a *myApp) KeyMap() tui.KeyMap {
	if a.showSettings.Get() {
		return tui.KeyMap{
			tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { a.toggleSettings() }),
			tui.On(tui.Rune('c').Ctrl(), func(ke tui.KeyEvent) { ke.App().Stop() }),
		}
	}

	km := a.textarea.KeyMap()
	km = append(km,
		tui.OnStop(tui.Rune('s').Ctrl(), func(ke tui.KeyEvent) { a.toggleSettings() }),
		tui.On(tui.KeyEscape, func(ke tui.KeyEvent) { ke.App().Stop() }),
		tui.On(tui.Rune('c').Ctrl(), func(ke tui.KeyEvent) { ke.App().Stop() }),
	)
	return km
}

func (a *myApp) Watchers() []tui.Watcher {
	return a.textarea.Watchers()
}

templ (a *myApp) Render() {
	if a.showSettings.Get() {
		<div class="flex-col h-full p-1 border-rounded border-cyan">
			<span class="font-bold text-cyan">Settings</span>
			<span class="font-dim">Press Escape to</span>
		</div>
	} else {
		@a.textarea
	}
}