gitstack

grindlemire/go-tui code browser

2.4 KB 98 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main

import (
	"fmt"
	"time"
	tui "github.com/grindlemire/go-tui"
)

type counterApp struct {
	count   *tui.State[int]
	elapsed *tui.State[int]
	peak    *tui.State[int]
}

func Counter() *counterApp {
	return &counterApp{
		count:   tui.NewState(0),
		elapsed: tui.NewState(0),
		peak:    tui.NewState(0),
	}
}

func (c *counterApp) KeyMap() tui.KeyMap {
	return tui.KeyMap{
		tui.On(tui.Rune('+'), func(ke tui.KeyEvent) {
			c.count.Update(func(v int) int { return v + 1 })
		}),
		tui.On(tui.Rune('-'), func(ke tui.KeyEvent) {
			c.count.Update(func(v int) int { return v - 1 })
		}),
		tui.On(tui.Rune('0'), func(ke tui.KeyEvent) { c.count.Set(0) }),
		tui.On(tui.Rune('q'), func(ke tui.KeyEvent) { ke.App().Stop() }),
	}
}

func (c *counterApp) Watchers() []tui.Watcher {
	return []tui.Watcher{
		tui.OnTimer(time.Second, func() {
			c.elapsed.Update(func(v int) int { return v + 1 })
		}),
		tui.OnChange(c.count, func(v int) {
			if v > c.peak.Get() {
				c.peak.Set(v)
			}
		}),
	}
}

func formatTime(seconds int) string {
	return fmt.Sprintf("%d:%02d", seconds/60, seconds%60)
}

templ Badge(label string, value string, color string) {
	<div class="flex gap-1">
		<span class="font-dim">{label}</span>
		<span class={"font-bold " + color}>{value}</span>
	</div>
}

templ Card(title string) {
	<div class="flex-col border-rounded border-cyan p-1 gap-1" flexGrow={1.0}>
		<span class="font-bold text-gradient-cyan-blue">{title}</span>
		<hr />
		{children...}
	</div>
}

templ (c *counterApp) Render() {
	<div class="flex-col border-double border-gradient-cyan-magenta p-1 gap-1">
		<div class="flex justify-between items-center">
			<span class="text-gradient-cyan-magenta font-bold">Counter</span>
			<div class="flex gap-2">
				@Badge("peak:", fmt.Sprintf("%d", c.peak.Get()), "text-magenta")
				@Badge("uptime:", formatTime(c.elapsed.Get()), "text-yellow")
			</div>
		</div>
		<hr />
		<div class="flex gap-2">
			@Card("Count") {
				<span class="text-cyan font-bold">
					{fmt.Sprintf("%d", c.count.Get())}
				</span>
			}
			@Card("Status") {
				if c.count.Get() > 0 {
					<span class="text-green font-bold">Positive</span>
				} else if c.count.Get() < 0 {
					<span class="text-red font-bold">Negative</span>
				} else {
					<span class="text-blue font-bold">Zero</span>
				}
			}
		</div>
		<div class="flex gap-1 justify-center">
			<span class="font-dim">+/-count·0 reset·q quit</span>
		</div>
	</div>
}