feat: scaffold grot — render primitives, themes, widgets, demo gallery

Phase 1 of the btop-style Prometheus/Grafana TUI:
- pkg/tui/render: exact-cell panel borders, ANSI-aware pad/truncate,
  block sparklines + multi-row area charts, gradient meters (ported
  from Pilot's dashboard, generalized to take theme styles)
- pkg/tui/theme: pilot, tokyo-night, catppuccin-mocha palettes
- pkg/tui/widget: Stat, Gauge, BarGauge, TimeSeries with threshold
  coloring, Grafana-style units, error/no-data states
- cmd/grot: cobra CLI with 'demo' gallery command
- Makefile, golangci config, MIT license
This commit is contained in:
Aleks Petrov committed 2026-07-07 13:10:01 +02:00
commit 6141ff1f2a
21 files changed
+1823

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
bin/
dist/
coverage.out
coverage.html
*.log
.DS_Store
# built binary
/grot
+18
View File
@@ -0,0 +1,18 @@
version: "2"
run:
timeout: 5m
linters:
enable:
- errcheck
- govet
- ineffassign
- staticcheck
- unused
settings:
staticcheck:
checks:
- "all"
- "-ST1000" # package comment
- "-ST1003" # variable naming
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 QF Studio
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+83
View File
@@ -0,0 +1,83 @@
.PHONY: build build-all run demo test test-coverage lint fmt clean install deps release help
BINARY_NAME=grot
VERSION?=$(shell git describe --tags --always --dirty 2>/dev/null || echo "dev")
BUILD_TIME=$(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
LDFLAGS=-ldflags "-X main.version=$(VERSION) -X main.buildTime=$(BUILD_TIME)"
all: build
build:
@echo "Building $(BINARY_NAME)..."
go build $(LDFLAGS) -o bin/$(BINARY_NAME) ./cmd/grot
build-all:
@echo "Building for all platforms..."
GOOS=darwin GOARCH=amd64 CGO_ENABLED=0 go build $(LDFLAGS) -o bin/$(BINARY_NAME)-darwin-amd64 ./cmd/grot
GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build $(LDFLAGS) -o bin/$(BINARY_NAME)-darwin-arm64 ./cmd/grot
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build $(LDFLAGS) -o bin/$(BINARY_NAME)-linux-amd64 ./cmd/grot
GOOS=linux GOARCH=arm64 CGO_ENABLED=0 go build $(LDFLAGS) -o bin/$(BINARY_NAME)-linux-arm64 ./cmd/grot
run: build
./bin/$(BINARY_NAME)
demo: build
./bin/$(BINARY_NAME) demo
deps:
go mod download
go mod tidy
test:
go test -race ./...
test-coverage:
go test -race -coverprofile=coverage.out ./...
go tool cover -html=coverage.out -o coverage.html
lint:
@if command -v golangci-lint >/dev/null 2>&1; then \
golangci-lint run; \
else \
echo "golangci-lint not installed, skipping..."; \
fi
fmt:
go fmt ./...
@if command -v goimports >/dev/null 2>&1; then \
goimports -w .; \
fi
clean:
rm -rf bin/ dist/
rm -f coverage.out coverage.html
install:
go install $(LDFLAGS) ./cmd/grot
# Release — tag-only; CI (goreleaser) is the sole publisher.
# Usage: make release V=0.1.0
release:
ifndef V
$(error V is required. Usage: make release V=0.1.0)
endif
@if [ -n "$$(git status --porcelain)" ]; then \
echo "❌ Working directory not clean."; exit 1; \
fi
@if [ "$$(git branch --show-current)" != "main" ]; then \
echo "❌ Must be on main branch."; exit 1; \
fi
git tag v$(V)
git push origin v$(V)
@echo "✅ Tag v$(V) pushed. CI publishes the release."
help:
@echo "grot Makefile:"
@echo " make build Build the binary"
@echo " make build-all Build for all platforms"
@echo " make demo Build and render the demo gallery"
@echo " make test Run tests (-race)"
@echo " make lint Run golangci-lint"
@echo " make fmt Format code"
@echo " make install Install to GOPATH/bin"
@echo " make release V=x.y.z Tag and push a release"
+50
View File
@@ -0,0 +1,50 @@
# grot
**btop-style terminal dashboards for Prometheus & Grafana.**
grot renders Prometheus metrics as polished terminal dashboards — braille
charts, gradient gauges, threshold-colored stats. Point it at your existing
Grafana dashboard JSON and get the same layout in your terminal.
> Status: pre-release, under active development.
## Quick start
```bash
# Widget gallery with fake data
grot demo --theme tokyo-night
# Coming soon:
# grot --prom http://localhost:9090 --config dashboard.yaml
# grot --prom http://localhost:9090 --grafana-json my-dashboard.json
```
## Why
- [grafterm](https://github.com/slok/grafterm) is abandoned (2019) and limited
to termdash's fixed widgets.
- [btop](https://github.com/aristocratos/btop) proves terminal dashboards can
be beautiful — but it only shows system metrics.
- Nothing renders *your* Grafana dashboards in the terminal. grot does.
## Features
- **Grafana import** — parse dashboard JSON (stat, gauge, bargauge,
timeseries panels) into a terminal layout
- **Native YAML config** — simple dashboard definitions without Grafana
- **Themes** — pilot, tokyo-night, catppuccin-mocha
- **btop-like keys** — hjkl focus, zoom, live time-range switching
- Widget-local errors: a broken query never breaks the grid
## Development
```bash
make build # build ./bin/grot
make demo # render the widget gallery
make test # go test -race
make lint # golangci-lint
```
## License
MIT
+155
View File
@@ -0,0 +1,155 @@
package main
import (
"fmt"
"math"
"os"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/spf13/cobra"
"golang.org/x/term"
"github.com/qf-studio/grot/pkg/tui/theme"
"github.com/qf-studio/grot/pkg/tui/widget"
)
func demoCmd() *cobra.Command {
var themeName string
var width int
cmd := &cobra.Command{
Use: "demo",
Short: "Render a static widget gallery with fake data",
Run: func(cmd *cobra.Command, args []string) {
if width == 0 {
if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && w > 40 {
width = w
} else {
width = 100
}
}
th := theme.ByName(themeName)
fmt.Println(renderDemo(th, width))
},
}
cmd.Flags().StringVar(&themeName, "theme", "pilot", "theme: pilot | tokyo-night | catppuccin-mocha")
cmd.Flags().IntVar(&width, "width", 0, "render width (default: terminal width)")
return cmd
}
func renderDemo(th theme.Theme, width int) string {
now := time.Now()
instant := func(legend string, v float64) widget.QueryResult {
return widget.QueryResult{
Series: []widget.Series{{Legend: legend, Points: []widget.Point{{T: now, V: v}}}},
FetchedAt: now,
}
}
rangeSeries := func(legend string, gen func(i int) float64, n int) widget.Series {
pts := make([]widget.Point, n)
for i := 0; i < n; i++ {
pts[i] = widget.Point{T: now.Add(time.Duration(i-n) * time.Minute), V: gen(i)}
}
return widget.Series{Legend: legend, Points: pts}
}
fv := func(v float64) *float64 { return &v }
// --- Row 1: four stats ---
statW := width / 4
lastW := width - statW*3 // absorb remainder
statH := 6
success := widget.NewStat("Success Rate", "percent")
success.Thresholds = []widget.Threshold{
{Color: "red"}, {Value: fv(70), Color: "yellow"}, {Value: fv(90), Color: "green"},
}
success.SetResult(instant("rate", 66.0))
queue := widget.NewStat("Queue Depth", "short")
queue.Thresholds = []widget.Threshold{
{Color: "green"}, {Value: fv(5), Color: "yellow"}, {Value: fv(15), Color: "red"},
}
queue.SetResult(widget.QueryResult{Series: []widget.Series{
rangeSeries("queue", func(i int) float64 { return math.Abs(3*math.Sin(float64(i)/5)) + float64(i%3) }, 40),
}, FetchedAt: now})
prs := widget.NewStat("Active PRs", "short")
prs.SetResult(instant("prs", 4))
cost := widget.NewStat("Cumulative Cost", "currencyUSD")
cost.SetResult(instant("cost", 154.23))
row1 := lipgloss.JoinHorizontal(lipgloss.Top,
success.Render(statW, statH, th, false),
queue.Render(statW, statH, th, false),
prs.Render(statW, statH, th, false),
cost.Render(lastW, statH, th, true), // focused example
)
// --- Row 2: gauge + bargauge ---
halfW := width / 2
otherW := width - halfW
row2H := 7
gauge := widget.NewGauge("CI Pass Rate", "percent", 0, 100)
gauge.Thresholds = []widget.Threshold{
{Color: "red"}, {Value: fv(70), Color: "yellow"}, {Value: fv(90), Color: "green"},
}
gauge.SetResult(instant("ci", 87.5))
bars := widget.NewBarGauge("Tokens by Model", "short")
bars.SetResult(widget.QueryResult{Series: []widget.Series{
{Legend: "opus/input", Points: []widget.Point{{T: now, V: 57_300}}},
{Legend: "opus/output", Points: []widget.Point{{T: now, V: 31_000}}},
{Legend: "haiku/input", Points: []widget.Point{{T: now, V: 12_400}}},
{Legend: "haiku/output", Points: []widget.Point{{T: now, V: 4_100}}},
}, FetchedAt: now})
row2 := lipgloss.JoinHorizontal(lipgloss.Top,
gauge.Render(halfW, row2H, th, false),
bars.Render(otherW, row2H, th, false),
)
// --- Row 3: two timeseries ---
row3H := 12
p95 := widget.NewTimeSeries("Execution Duration P95", "s")
p95.SetResult(widget.QueryResult{Series: []widget.Series{
rangeSeries("p95", func(i int) float64 {
return 300 + 150*math.Sin(float64(i)/8) + 30*math.Sin(float64(i)/2)
}, 120),
}, FetchedAt: now})
tokens := widget.NewTimeSeries("Tokens / 5m", "short")
tokens.SetResult(widget.QueryResult{Series: []widget.Series{
rangeSeries("opus", func(i int) float64 {
v := 2000 + 1800*math.Sin(float64(i)/10) + 400*math.Cos(float64(i)/3)
return math.Max(v, 0)
}, 120),
rangeSeries("haiku", func(i int) float64 { return 800 + 300*math.Sin(float64(i)/6) }, 120),
}, FetchedAt: now})
row3 := lipgloss.JoinHorizontal(lipgloss.Top,
p95.Render(halfW, row3H, th, false),
tokens.Render(otherW, row3H, th, false),
)
// --- Error/no-data states ---
row4H := 5
errW := widget.NewStat("Broken Query", "short")
errW.SetError(fmt.Errorf(`parse error: unexpected "}"`))
empty := widget.NewTimeSeries("No Data Example", "short")
empty.SetResult(widget.QueryResult{FetchedAt: now})
row4 := lipgloss.JoinHorizontal(lipgloss.Top,
errW.Render(halfW, row4H, th, false),
empty.Render(otherW, row4H, th, false),
)
header := th.AccentStyle().Bold(true).Render(" grot") +
th.DimStyle().Render(" · demo gallery · theme: "+th.Name)
return header + "\n" + row1 + "\n" + row2 + "\n" + row3 + "\n" + row4
}
+37
View File
@@ -0,0 +1,37 @@
// grot — a btop-style terminal dashboard for Prometheus & Grafana.
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
var (
version = "dev"
buildTime = "unknown"
)
func main() {
root := &cobra.Command{
Use: "grot",
Short: "grot — btop-style terminal dashboards for Prometheus & Grafana",
Long: `grot renders Prometheus metrics as polished terminal dashboards.
Import your existing Grafana dashboard JSON or write a simple YAML config.`,
SilenceUsage: true,
}
root.AddCommand(demoCmd())
root.AddCommand(&cobra.Command{
Use: "version",
Short: "Print version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("grot %s (built %s)\n", version, buildTime)
},
})
if err := root.Execute(); err != nil {
os.Exit(1)
}
}
+26
View File
@@ -0,0 +1,26 @@
module github.com/qf-studio/grot
go 1.25.6
require (
github.com/charmbracelet/lipgloss v1.1.0
github.com/spf13/cobra v1.10.2
golang.org/x/term v0.44.0
)
require (
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
github.com/charmbracelet/x/ansi v0.8.0 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/muesli/termenv v0.16.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sys v0.46.0 // indirect
)
+42
View File
@@ -0,0 +1,42 @@
github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc=
golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+83
View File
@@ -0,0 +1,83 @@
package render
import (
"strings"
"github.com/charmbracelet/lipgloss"
)
// PanelStyle carries the styles used to draw a panel frame.
type PanelStyle struct {
Border lipgloss.Style // frame characters
Title lipgloss.Style // title text in the top border
}
// Panel draws a bordered panel of exactly w×h cells:
//
// ╭─ TITLE ────────╮
// │ content │
// ╰────────────────╯
//
// Content lines beyond h-2 are dropped; missing lines are padded blank.
// Each content line is padded/truncated to the inner width (w-4).
func Panel(title, content string, w, h int, ps PanelStyle) string {
if w < 6 || h < 2 {
return ""
}
lines := make([]string, 0, h)
lines = append(lines, topBorder(title, w, ps))
contentLines := strings.Split(content, "\n")
innerRows := h - 2
for i := 0; i < innerRows; i++ {
if i < len(contentLines) {
lines = append(lines, contentLine(contentLines[i], w, ps))
} else {
lines = append(lines, emptyLine(w, ps))
}
}
lines = append(lines, bottomBorder(w, ps))
return strings.Join(lines, "\n")
}
// InnerSize returns the content area dimensions for a Panel of w×h.
func InnerSize(w, h int) (int, int) {
return w - 4, h - 2
}
// topBorder creates: ╭─ TITLE ─────...─────╮ with exact w width.
func topBorder(title string, w int, ps PanelStyle) string {
if title == "" {
return ps.Border.Render("╭" + strings.Repeat("─", w-2) + "╮")
}
titleUpper := strings.ToUpper(title)
prefix := "╭─ "
// Truncate over-long titles so the frame never breaks.
maxTitle := w - lipgloss.Width(prefix) - 3 // trailing " ─╮" minimum
if lipgloss.Width(titleUpper) > maxTitle {
titleUpper = TruncateVisual(titleUpper, maxTitle)
}
prefixWidth := lipgloss.Width(prefix + titleUpper + " ")
dashCount := w - prefixWidth - 1
if dashCount < 0 {
dashCount = 0
}
return ps.Border.Render(prefix) + ps.Title.Render(titleUpper) +
ps.Border.Render(" "+strings.Repeat("─", dashCount)+"╮")
}
func bottomBorder(w int, ps PanelStyle) string {
return ps.Border.Render("╰" + strings.Repeat("─", w-2) + "╯")
}
func emptyLine(w int, ps PanelStyle) string {
b := ps.Border.Render("│")
return b + strings.Repeat(" ", w-2) + b
}
func contentLine(content string, w int, ps PanelStyle) string {
adjusted := PadOrTruncate(content, w-4)
b := ps.Border.Render("│")
return b + " " + adjusted + " " + b
}
+67
View File
@@ -0,0 +1,67 @@
package render
import (
"strings"
"github.com/charmbracelet/lipgloss"
)
// Meter renders a horizontal gauge of exactly width cells:
//
// ████████▓░░░░░░░
//
// frac is clamped to [0,1]. fill styles the solid portion, empty the rest.
// A ▓ shade cell marks the boundary for a gradient feel (only when partially
// filled).
func Meter(frac float64, width int, fill, empty lipgloss.Style) string {
if width <= 0 {
return ""
}
if frac < 0 {
frac = 0
}
if frac > 1 {
frac = 1
}
filled := int(frac * float64(width))
if filled > width {
filled = width
}
var b strings.Builder
if filled > 0 {
solid := filled
edge := false
if filled < width && filled > 1 {
solid = filled - 1
edge = true
}
b.WriteString(fill.Render(strings.Repeat("█", solid)))
if edge {
b.WriteString(fill.Render("▓"))
}
}
if width-filled > 0 {
b.WriteString(empty.Render(strings.Repeat("░", width-filled)))
}
return b.String()
}
// HBar renders a horizontal bar (no empty track) of up to width cells with a
// half-block cap for sub-cell resolution.
func HBar(frac float64, width int, fill lipgloss.Style) string {
if frac < 0 {
frac = 0
}
if frac > 1 {
frac = 1
}
cells := frac * float64(width)
full := int(cells)
half := cells-float64(full) >= 0.5 && full < width
s := strings.Repeat("█", full)
if half {
s += "▌"
}
return fill.Render(s)
}
+132
View File
@@ -0,0 +1,132 @@
package render
import (
"strings"
"testing"
"github.com/charmbracelet/lipgloss"
)
func TestPanelExactDimensions(t *testing.T) {
tests := []struct {
name string
title string
content string
w, h int
}{
{"basic", "Title", "hello", 30, 5},
{"empty content", "T", "", 20, 4},
{"overflow content", "Long", strings.Repeat("line\n", 20), 25, 6},
{"long title", strings.Repeat("VERYLONGTITLE", 5), "x", 20, 4},
{"styled content", "S", lipgloss.NewStyle().Foreground(lipgloss.Color("#ff0000")).Render("red text"), 30, 4},
}
ps := PanelStyle{Border: lipgloss.NewStyle(), Title: lipgloss.NewStyle()}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out := Panel(tt.title, tt.content, tt.w, tt.h, ps)
lines := strings.Split(out, "\n")
if len(lines) != tt.h {
t.Fatalf("got %d lines, want %d", len(lines), tt.h)
}
for i, line := range lines {
if got := lipgloss.Width(line); got != tt.w {
t.Errorf("line %d: width %d, want %d: %q", i, got, tt.w, line)
}
}
})
}
}
func TestPadOrTruncate(t *testing.T) {
tests := []struct {
in string
width int
}{
{"short", 20},
{"exactly-ten", 11},
{"this is a much longer string than allowed", 15},
{"", 5},
}
for _, tt := range tests {
out := PadOrTruncate(tt.in, tt.width)
if got := lipgloss.Width(out); got != tt.width {
t.Errorf("PadOrTruncate(%q, %d): width %d", tt.in, tt.width, got)
}
}
}
func TestTruncateVisualStyled(t *testing.T) {
styled := lipgloss.NewStyle().Foreground(lipgloss.Color("#7eb8da")).Render("styled long content here")
out := TruncateVisual(styled, 12)
if got := lipgloss.Width(out); got != 12 {
t.Errorf("styled truncate: width %d, want 12", got)
}
}
func TestNormalizeSparkline(t *testing.T) {
// Levels are 1-8, right-aligned, zeros pad left.
levels := NormalizeSparkline([]float64{0, 5, 10}, 5)
if len(levels) != 5 {
t.Fatalf("len %d", len(levels))
}
if levels[0] != 0 || levels[1] != 0 {
t.Errorf("left padding not zero: %v", levels)
}
if levels[2] != 1 {
t.Errorf("zero value should be baseline 1: %v", levels)
}
if levels[4] != 8 {
t.Errorf("max value should be 8: %v", levels)
}
}
func TestSparklineWidth(t *testing.T) {
for _, w := range []int{5, 20, 60} {
out := Sparkline(NormalizeSparkline([]float64{1, 2, 3}, w), w)
if got := lipgloss.Width(out); got != w {
t.Errorf("width %d: got %d", w, got)
}
}
}
func TestBlockChartDimensions(t *testing.T) {
vals := []float64{1, 5, 3, 8, 2, 9, 4}
rows := BlockChart(vals, 20, 4)
if len(rows) != 4 {
t.Fatalf("got %d rows, want 4", len(rows))
}
for i, r := range rows {
if got := lipgloss.Width(r); got != 20 {
t.Errorf("row %d: width %d, want 20", i, got)
}
}
// Max value column must reach the top row with a filled block.
if !strings.ContainsAny(rows[0], "▁▂▃▄▅▆▇█") {
t.Errorf("top row empty for max value: %q", rows[0])
}
}
func TestMeterWidth(t *testing.T) {
fill := lipgloss.NewStyle()
empty := lipgloss.NewStyle()
for _, frac := range []float64{-0.5, 0, 0.33, 0.5, 0.875, 1, 1.5} {
out := Meter(frac, 16, fill, empty)
if got := lipgloss.Width(out); got != 16 {
t.Errorf("frac %v: width %d, want 16", frac, got)
}
}
}
func TestFormatCompact(t *testing.T) {
tests := []struct {
in float64
want string
}{
{0, "0"}, {999, "999"}, {1000, "1.0K"}, {57300, "57.3K"}, {1_200_000, "1.2M"},
}
for _, tt := range tests {
if got := FormatCompact(tt.in); got != tt.want {
t.Errorf("FormatCompact(%v) = %q, want %q", tt.in, got, tt.want)
}
}
}
+159
View File
@@ -0,0 +1,159 @@
package render
import "math"
// SparkBlocks maps normalized levels (0-8) to Unicode block elements.
// Index 0 is a space, reserved for padding.
var SparkBlocks = []rune{' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'}
// NormalizeSparkline scales values to 1-8 levels for sparkline rendering,
// right-aligned within width (left-padded with 0 = blank). More values than
// width keeps the most recent.
func NormalizeSparkline(values []float64, width int) []int {
result := make([]int, width)
if len(values) == 0 || width <= 0 {
return result
}
offset := width - len(values)
if offset < 0 {
values = values[len(values)-width:]
offset = 0
}
minVal, maxVal := values[0], values[0]
for _, v := range values[1:] {
if v < minVal {
minVal = v
}
if v > maxVal {
maxVal = v
}
}
span := maxVal - minVal
if span == 0 {
level := 1
if values[0] > 0 {
level = 4
}
for i := range values {
result[offset+i] = level
}
return result
}
for i, v := range values {
normalized := (v - minVal) / span * 7
level := int(math.Round(normalized)) + 1
if v == 0 {
level = 1
}
if level < 1 {
level = 1
}
if level > 8 {
level = 8
}
result[offset+i] = level
}
return result
}
// Sparkline renders levels (0-8) as block characters, exactly width cells.
func Sparkline(levels []int, width int) string {
out := make([]rune, width)
start := 0
if len(levels) > width {
start = len(levels) - width
}
pad := width - (len(levels) - start)
for i := 0; i < pad; i++ {
out[i] = SparkBlocks[0]
}
for i := start; i < len(levels); i++ {
idx := levels[i]
if idx < 0 {
idx = 0
}
if idx >= len(SparkBlocks) {
idx = len(SparkBlocks) - 1
}
out[pad+i-start] = SparkBlocks[idx]
}
return string(out)
}
// BlockChart renders values as a multi-row block area chart of exactly
// width×rows cells, one string per row (top first). Each column is scaled to
// rows*8 sub-levels; partial tops use ▁▂▃▄▅▆▇, filled cells use █.
func BlockChart(values []float64, width, rows int) []string {
if rows < 1 {
rows = 1
}
levels := normalizeTo(values, width, rows*8)
out := make([]string, rows)
for r := 0; r < rows; r++ {
rowRunes := make([]rune, width)
// Sub-level threshold below this row (rows are top-first).
base := (rows - 1 - r) * 8
for c := 0; c < width; c++ {
fill := levels[c] - base
if fill < 0 {
fill = 0
}
if fill > 8 {
fill = 8
}
rowRunes[c] = SparkBlocks[fill]
}
out[r] = string(rowRunes)
}
return out
}
// normalizeTo scales values to 0..maxLevel, right-aligned within width.
func normalizeTo(values []float64, width, maxLevel int) []int {
result := make([]int, width)
if len(values) == 0 || width <= 0 {
return result
}
offset := width - len(values)
if offset < 0 {
values = values[len(values)-width:]
offset = 0
}
minVal, maxVal := values[0], values[0]
for _, v := range values[1:] {
if v < minVal {
minVal = v
}
if v > maxVal {
maxVal = v
}
}
span := maxVal - minVal
for i, v := range values {
var level int
if span == 0 {
if v > 0 {
level = maxLevel / 2
} else {
level = 1
}
} else {
level = int(math.Round((v-minVal)/span*float64(maxLevel-1))) + 1
if v == 0 && minVal == 0 {
level = 1
}
}
if level < 0 {
level = 0
}
if level > maxLevel {
level = maxLevel
}
result[offset+i] = level
}
return result
}
+102
View File
@@ -0,0 +1,102 @@
package render
import (
"fmt"
"strings"
"github.com/charmbracelet/lipgloss"
)
// PadOrTruncate ensures s is exactly targetWidth visual cells, ANSI-aware.
func PadOrTruncate(s string, targetWidth int) string {
visualWidth := lipgloss.Width(s)
if visualWidth == targetWidth {
return s
}
if visualWidth > targetWidth {
return TruncateVisual(s, targetWidth)
}
return s + strings.Repeat(" ", targetWidth-visualWidth)
}
// TruncateVisual truncates s to targetWidth visual cells, appending "..." when
// truncation occurs. ANSI escape sequences (lipgloss color codes) are copied
// through with zero visible width; a CSI sequence starts at ESC (0x1b) and
// ends at a byte in 0x40–0x7e.
func TruncateVisual(s string, targetWidth int) string {
visualWidth := lipgloss.Width(s)
if visualWidth <= targetWidth {
return s
}
if targetWidth <= 3 {
return strings.Repeat(".", targetWidth)
}
result := ""
width := 0
inEsc := false
for _, r := range s {
if inEsc {
result += string(r)
if r >= 0x40 && r <= 0x7e {
inEsc = false
}
continue
}
if r == 0x1b {
inEsc = true
result += string(r)
continue
}
runeWidth := lipgloss.Width(string(r))
if width+runeWidth > targetWidth-3 {
break
}
result += string(r)
width += runeWidth
}
for width < targetWidth-3 {
result += " "
width++
}
return result + "..."
}
// Center centers s within width visual cells (ANSI-aware). Strings wider than
// width are truncated.
func Center(s string, width int) string {
w := lipgloss.Width(s)
if w >= width {
return TruncateVisual(s, width)
}
left := (width - w) / 2
right := width - w - left
return strings.Repeat(" ", left) + s + strings.Repeat(" ", right)
}
// FormatCompact formats a number in compact SI form: 0, 999, 1.0K, 57.3K, 1.2M, 3.4B.
func FormatCompact(v float64) string {
abs := v
if abs < 0 {
abs = -abs
}
switch {
case abs < 1000:
if v == float64(int64(v)) {
return fmt.Sprintf("%d", int64(v))
}
return trimZeros(fmt.Sprintf("%.2f", v))
case abs < 1_000_000:
return fmt.Sprintf("%.1fK", v/1000)
case abs < 1_000_000_000:
return fmt.Sprintf("%.1fM", v/1_000_000)
default:
return fmt.Sprintf("%.1fB", v/1_000_000_000)
}
}
func trimZeros(s string) string {
s = strings.TrimRight(s, "0")
return strings.TrimRight(s, ".")
}
+150
View File
@@ -0,0 +1,150 @@
// Package theme defines grot's color themes. A Theme is a small set of
// semantic color tokens; render primitives derive lipgloss styles from it.
package theme
import "github.com/charmbracelet/lipgloss"
// Theme is a semantic color palette. All values are hex colors.
type Theme struct {
Name string
Accent string // titles, focused borders, primary data
Success string // good values, success thresholds
Error string // errors, critical thresholds
Warning string // warnings, amber thresholds
Border string // panel borders
Label string // widget titles, legends
Dim string // secondary text, axis labels
DimMore string // faintest text (padding glyphs, hints)
Series []string
}
// Style helpers — precomputed on demand; lipgloss styles are cheap values.
func (t Theme) TitleStyle() lipgloss.Style {
return lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(t.Label))
}
func (t Theme) BorderStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Border))
}
func (t Theme) FocusBorderStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Accent))
}
func (t Theme) AccentStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Accent))
}
func (t Theme) SuccessStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Success))
}
func (t Theme) ErrorStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Error))
}
func (t Theme) WarningStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Warning))
}
func (t Theme) LabelStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Label))
}
func (t Theme) DimStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.Dim))
}
func (t Theme) DimMoreStyle() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color(t.DimMore))
}
// SeriesStyle returns the style for the i-th chart series, cycling the palette.
func (t Theme) SeriesStyle(i int) lipgloss.Style {
c := t.Series[i%len(t.Series)]
return lipgloss.NewStyle().Foreground(lipgloss.Color(c))
}
// SeriesColor returns the hex color for the i-th series, cycling the palette.
func (t Theme) SeriesColor(i int) string {
return t.Series[i%len(t.Series)]
}
// ResolveColor maps a semantic or Grafana color name to a theme hex color.
// Unknown names pass through unchanged (assumed to be hex already).
func (t Theme) ResolveColor(name string) string {
switch name {
case "green", "success", "ok":
return t.Success
case "red", "critical", "error":
return t.Error
case "yellow", "orange", "amber", "warning":
return t.Warning
case "blue", "accent":
return t.Accent
case "text":
return t.Label
case "gray", "grey", "dim":
return t.Dim
}
return name
}
// Built-in themes.
var (
// Pilot is the muted terminal aesthetic from the Pilot dashboard.
Pilot = Theme{
Name: "pilot",
Accent: "#7eb8da", // steel blue
Success: "#7ec699", // sage green
Error: "#d48a8a", // dusty rose
Warning: "#d4a054", // amber
Border: "#3d4450", // slate
Label: "#c9d1d9",
Dim: "#8b949e",
DimMore: "#6e7681",
Series: []string{"#7eb8da", "#7ec699", "#d4a054", "#bb9af7", "#d48a8a", "#7dcfff"},
}
// TokyoNight matches the popular tokyonight palette.
TokyoNight = Theme{
Name: "tokyo-night",
Accent: "#7aa2f7",
Success: "#9ece6a",
Error: "#f7768e",
Warning: "#e0af68",
Border: "#3b4261",
Label: "#c0caf5",
Dim: "#565f89",
DimMore: "#414868",
Series: []string{"#7aa2f7", "#9ece6a", "#e0af68", "#bb9af7", "#f7768e", "#7dcfff"},
}
// CatppuccinMocha matches catppuccin-mocha.
CatppuccinMocha = Theme{
Name: "catppuccin-mocha",
Accent: "#89b4fa",
Success: "#a6e3a1",
Error: "#f38ba8",
Warning: "#f9e2af",
Border: "#45475a",
Label: "#cdd6f4",
Dim: "#6c7086",
DimMore: "#585b70",
Series: []string{"#89b4fa", "#a6e3a1", "#f9e2af", "#cba6f7", "#f38ba8", "#94e2d5"},
}
)
// All lists the built-in themes.
var All = []Theme{Pilot, TokyoNight, CatppuccinMocha}
// ByName returns the named theme, falling back to Pilot.
func ByName(name string) Theme {
for _, t := range All {
if t.Name == name {
return t
}
}
return Pilot
}
+105
View File
@@ -0,0 +1,105 @@
package widget
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
)
// BarGauge shows one horizontal bar per series, scaled to the max value:
//
// opus/in ██████████▌ 57.3K
// sonnet/in ██████ 31.0K
type BarGauge struct {
data
title string
Unit string
Decimals *int
Max *float64 // explicit scale; nil → max across series
Thresholds []Threshold
}
// NewBarGauge creates a bar-row widget.
func NewBarGauge(title, unit string) *BarGauge {
return &BarGauge{title: title, Unit: unit}
}
func (b *BarGauge) Title() string { return b.title }
func (b *BarGauge) MinSize() (int, int) { return 20, 4 }
func (b *BarGauge) Render(w, h int, th theme.Theme, focused bool) string {
iw, ih := render.InnerSize(w, h)
ps := b.panelStyle(th, focused)
var body string
switch {
case b.err != nil:
body = errorBody(b.err, iw, ih, th)
case len(b.res.Series) == 0:
body = noDataBody(iw, ih, th)
default:
body = b.body(iw, ih, th)
}
return render.Panel(b.title, body, w, h, ps)
}
func (b *BarGauge) body(iw, ih int, th theme.Theme) string {
series := b.res.Series
if len(series) > ih {
series = series[:ih]
}
// Column layout: legend | bar | value
legendW := 0
values := make([]float64, len(series))
labels := make([]string, len(series))
valueTexts := make([]string, len(series))
maxV := 0.0
for i, s := range series {
v, _ := s.Last()
values[i] = v
labels[i] = s.Legend
valueTexts[i] = FormatValue(v, b.Unit, b.Decimals)
if lw := lipgloss.Width(s.Legend); lw > legendW {
legendW = lw
}
if v > maxV {
maxV = v
}
}
if b.Max != nil {
maxV = *b.Max
}
if legendW > iw/3 {
legendW = iw / 3
}
valueW := 0
for _, vt := range valueTexts {
if len(vt) > valueW {
valueW = len(vt)
}
}
barW := iw - legendW - valueW - 4 // 2 gaps of 2 spaces
if barW < 3 {
barW = 3
}
rows := make([]string, len(series))
for i := range series {
frac := 0.0
if maxV > 0 {
frac = values[i] / maxV
}
color := thresholdColor(values[i], b.Thresholds, th, th.SeriesColor(i))
fill := lipgloss.NewStyle().Foreground(lipgloss.Color(color))
legend := th.LabelStyle().Render(render.PadOrTruncate(labels[i], legendW))
bar := render.PadOrTruncate(render.HBar(frac, barW, fill), barW)
val := th.DimStyle().Render(render.PadOrTruncate(valueTexts[i], valueW))
rows[i] = legend + " " + bar + " " + val
}
return vCenter(strings.Join(rows, "\n"), iw, ih)
}
+84
View File
@@ -0,0 +1,84 @@
package widget
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
)
// Gauge shows a value as a horizontal meter with threshold coloring:
//
// 66.0%
// ████████▓░░░░░░░
// 0 100
type Gauge struct {
data
title string
Unit string
Decimals *int
Min, Max float64
Thresholds []Threshold
}
// NewGauge creates a gauge widget with the given range (max 0 → 100).
func NewGauge(title, unit string, min, max float64) *Gauge {
if max == 0 && min == 0 {
max = 100
}
return &Gauge{title: title, Unit: unit, Min: min, Max: max}
}
func (g *Gauge) Title() string { return g.title }
func (g *Gauge) MinSize() (int, int) { return 16, 5 }
func (g *Gauge) Render(w, h int, th theme.Theme, focused bool) string {
iw, ih := render.InnerSize(w, h)
ps := g.panelStyle(th, focused)
var body string
switch {
case g.err != nil:
body = errorBody(g.err, iw, ih, th)
case len(g.res.Series) == 0:
body = noDataBody(iw, ih, th)
default:
body = g.body(iw, ih, th)
}
return render.Panel(g.title, body, w, h, ps)
}
func (g *Gauge) body(iw, ih int, th theme.Theme) string {
v, ok := g.res.Series[0].Last()
if !ok {
return noDataBody(iw, ih, th)
}
span := g.Max - g.Min
frac := 0.0
if span > 0 {
frac = (v - g.Min) / span
}
color := thresholdColor(v, g.Thresholds, th, th.Accent)
fill := lipgloss.NewStyle().Foreground(lipgloss.Color(color))
valueStyle := fill.Bold(true)
lines := []string{
render.Center(valueStyle.Render(FormatValue(v, g.Unit, g.Decimals)), iw),
render.Meter(frac, iw, fill, th.DimMoreStyle()),
}
// Min/max scale line when there's room.
if ih >= 4 {
lo := FormatValue(g.Min, g.Unit, g.Decimals)
hi := FormatValue(g.Max, g.Unit, g.Decimals)
gap := iw - len(lo) - len(hi)
if gap > 0 {
lines = append(lines, th.DimStyle().Render(lo+strings.Repeat(" ", gap)+hi))
}
}
return vCenter(strings.Join(lines, "\n"), iw, ih)
}
+69
View File
@@ -0,0 +1,69 @@
package widget
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
)
// Stat shows a single large value with threshold coloring and an optional
// history sparkline underneath (populated when the result carries a range).
type Stat struct {
data
title string
Unit string
Decimals *int
Thresholds []Threshold
}
// NewStat creates a stat widget.
func NewStat(title, unit string) *Stat {
return &Stat{title: title, Unit: unit}
}
func (s *Stat) Title() string { return s.title }
func (s *Stat) MinSize() (int, int) { return 14, 4 }
func (s *Stat) Render(w, h int, th theme.Theme, focused bool) string {
iw, ih := render.InnerSize(w, h)
ps := s.panelStyle(th, focused)
var body string
switch {
case s.err != nil:
body = errorBody(s.err, iw, ih, th)
case len(s.res.Series) == 0:
body = noDataBody(iw, ih, th)
default:
body = s.body(iw, ih, th)
}
return render.Panel(s.title, body, w, h, ps)
}
func (s *Stat) body(iw, ih int, th theme.Theme) string {
ser := s.res.Series[0]
v, ok := ser.Last()
if !ok {
return noDataBody(iw, ih, th)
}
color := thresholdColor(v, s.Thresholds, th, th.Label)
valueStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(color))
value := valueStyle.Render(FormatValue(v, s.Unit, s.Decimals))
lines := []string{render.Center(value, iw)}
// History sparkline when the series has a range and there's room.
if len(ser.Points) > 1 && ih >= 3 {
vals := make([]float64, len(ser.Points))
for i, p := range ser.Points {
vals[i] = p.V
}
spark := render.Sparkline(render.NormalizeSparkline(vals, iw), iw)
lines = append(lines, th.DimStyle().Render(spark))
}
return vCenter(strings.Join(lines, "\n"), iw, ih)
}
+133
View File
@@ -0,0 +1,133 @@
package widget
import (
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
)
// TimeSeries renders series as a block area chart with y-axis labels and a
// legend row. (Braille rendering lands in Phase 3; the block chart is the
// --ascii fallback and the Phase 1/2 default.)
type TimeSeries struct {
data
title string
Unit string
Decimals *int
Stacked bool
}
// NewTimeSeries creates a time-series chart widget.
func NewTimeSeries(title, unit string) *TimeSeries {
return &TimeSeries{title: title, Unit: unit}
}
func (t *TimeSeries) Title() string { return t.title }
func (t *TimeSeries) MinSize() (int, int) { return 24, 6 }
func (t *TimeSeries) Render(w, h int, th theme.Theme, focused bool) string {
iw, ih := render.InnerSize(w, h)
ps := t.panelStyle(th, focused)
var body string
switch {
case t.err != nil:
body = errorBody(t.err, iw, ih, th)
case len(t.res.Series) == 0 || len(t.res.Series[0].Points) == 0:
body = noDataBody(iw, ih, th)
default:
body = t.body(iw, ih, th)
}
return render.Panel(t.title, body, w, h, ps)
}
func (t *TimeSeries) body(iw, ih int, th theme.Theme) string {
// Layout: chart rows + legend row (if ≥2 series or room permits).
legendRows := 0
if ih >= 4 {
legendRows = 1
}
chartRows := ih - legendRows
if chartRows < 1 {
chartRows = 1
legendRows = 0
}
// Primary series drives the chart (multi-series overlay lands with
// braille in Phase 3; block chart shows series[0], legend shows all).
primary := t.res.Series[0]
vals := make([]float64, len(primary.Points))
minV, maxV := primary.Points[0].V, primary.Points[0].V
for i, p := range primary.Points {
vals[i] = p.V
if p.V < minV {
minV = p.V
}
if p.V > maxV {
maxV = p.V
}
}
// Y-axis label gutter.
hiLabel := FormatValue(maxV, t.Unit, t.Decimals)
loLabel := FormatValue(minV, t.Unit, t.Decimals)
gutter := len(hiLabel)
if len(loLabel) > gutter {
gutter = len(loLabel)
}
if gutter > iw/3 {
gutter = iw / 3
}
chartW := iw - gutter - 1
if chartW < 4 {
chartW = iw
gutter = 0
}
rows := render.BlockChart(vals, chartW, chartRows)
seriesStyle := th.SeriesStyle(0)
lines := make([]string, 0, ih)
for i, row := range rows {
label := strings.Repeat(" ", gutter)
if gutter > 0 {
switch i {
case 0:
label = render.PadOrTruncate(hiLabel, gutter)
case len(rows) - 1:
label = render.PadOrTruncate(loLabel, gutter)
}
}
sep := ""
if gutter > 0 {
sep = " "
}
lines = append(lines, th.DimStyle().Render(label)+sep+seriesStyle.Render(row))
}
if legendRows > 0 {
lines = append(lines, t.legend(iw, th))
}
return strings.Join(lines, "\n")
}
// legend renders "● legend1 ● legend2 ..." with per-series colors.
func (t *TimeSeries) legend(iw int, th theme.Theme) string {
parts := make([]string, 0, len(t.res.Series))
for i, s := range t.res.Series {
name := s.Legend
if name == "" {
name = "series"
}
dot := th.SeriesStyle(i).Render("●")
parts = append(parts, dot+" "+th.DimStyle().Render(name))
}
line := strings.Join(parts, " ")
if lipgloss.Width(line) > iw {
line = render.TruncateVisual(line, iw)
}
return line
}
+196
View File
@@ -0,0 +1,196 @@
// Package widget provides grot's renderable dashboard widgets: Stat, Gauge,
// BarGauge, and TimeSeries. Widgets receive query results and render
// themselves into an exact w×h cell rectangle.
package widget
import (
"fmt"
"strings"
"time"
"github.com/qf-studio/grot/pkg/tui/render"
"github.com/qf-studio/grot/pkg/tui/theme"
)
// Point is a single sample.
type Point struct {
T time.Time
V float64
}
// Series is a named sequence of points. Instant queries produce one point.
type Series struct {
Legend string
Points []Point
}
// Last returns the most recent value, or 0 with false when empty.
func (s Series) Last() (float64, bool) {
if len(s.Points) == 0 {
return 0, false
}
return s.Points[len(s.Points)-1].V, true
}
// QueryResult is the data delivered to a widget.
type QueryResult struct {
Series []Series
FetchedAt time.Time
}
// Threshold colors a value range. Value nil = base color.
type Threshold struct {
Value *float64
Color string // semantic name (green/red/...) or hex; resolved via theme
}
// Widget renders into an exact w×h cell rectangle.
type Widget interface {
Title() string
SetResult(QueryResult)
SetError(err error)
Render(w, h int, th theme.Theme, focused bool) string
MinSize() (w, h int)
}
// data is the shared state/data-plumbing for all widgets.
type data struct {
res QueryResult
err error
}
func (d *data) SetResult(r QueryResult) { d.res = r; d.err = nil }
func (d *data) SetError(err error) { d.err = err }
// panelStyle picks the frame styles for the current state: focused → accent,
// error → rose, otherwise theme border.
func (d *data) panelStyle(th theme.Theme, focused bool) render.PanelStyle {
ps := render.PanelStyle{Border: th.BorderStyle(), Title: th.TitleStyle()}
if d.err != nil {
ps.Border = th.ErrorStyle()
ps.Title = th.ErrorStyle().Bold(true)
}
if focused {
ps.Border = th.FocusBorderStyle()
}
return ps
}
// errorBody renders an in-panel error message centered in iw×ih.
func errorBody(err error, iw, ih int, th theme.Theme) string {
msg := render.TruncateVisual(err.Error(), iw)
return vCenter(th.ErrorStyle().Render(render.Center(msg, iw)), iw, ih)
}
// noDataBody renders the dim "no data" placeholder.
func noDataBody(iw, ih int, th theme.Theme) string {
return vCenter(th.DimStyle().Render(render.Center("no data", iw)), iw, ih)
}
// vCenter pads content (already ≤ ih lines) with blank lines to vertically
// center it within ih rows.
func vCenter(content string, iw, ih int) string {
lines := strings.Split(content, "\n")
if len(lines) >= ih {
return strings.Join(lines[:ih], "\n")
}
top := (ih - len(lines)) / 2
blank := strings.Repeat(" ", iw)
out := make([]string, 0, ih)
for i := 0; i < top; i++ {
out = append(out, blank)
}
out = append(out, lines...)
for len(out) < ih {
out = append(out, blank)
}
return strings.Join(out, "\n")
}
// thresholdColor resolves the color for value v given thresholds: the color
// of the highest threshold whose Value <= v. Falls back to fallback.
func thresholdColor(v float64, thresholds []Threshold, th theme.Theme, fallback string) string {
color := fallback
base := true
for _, t := range thresholds {
if t.Value == nil {
if base {
color = th.ResolveColor(t.Color)
}
continue
}
if v >= *t.Value {
color = th.ResolveColor(t.Color)
base = false
}
}
return color
}
// FormatValue formats v per a Grafana-style unit string.
func FormatValue(v float64, unit string, decimals *int) string {
dec := -1
if decimals != nil {
dec = *decimals
}
f := func(def int) string {
d := def
if dec >= 0 {
d = dec
}
return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.*f", d, v), "0"), ".")
}
switch unit {
case "percent":
return f(1) + "%"
case "percentunit":
return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.*f", pick(dec, 1), v*100), "0"), ".") + "%"
case "currencyUSD":
return "$" + f(2)
case "s":
return formatDuration(v)
case "ms":
return formatDuration(v / 1000)
case "bytes":
return formatBytes(v)
case "short", "", "none":
if dec >= 0 {
return fmt.Sprintf("%.*f", dec, v)
}
return render.FormatCompact(v)
default:
return f(2) + " " + unit
}
}
func pick(dec, def int) int {
if dec >= 0 {
return dec
}
return def
}
func formatDuration(sec float64) string {
switch {
case sec < 0.001:
return fmt.Sprintf("%.0fµs", sec*1_000_000)
case sec < 1:
return fmt.Sprintf("%.0fms", sec*1000)
case sec < 60:
return fmt.Sprintf("%.1fs", sec)
case sec < 3600:
return fmt.Sprintf("%.1fm", sec/60)
default:
return fmt.Sprintf("%.1fh", sec/3600)
}
}
func formatBytes(b float64) string {
units := []string{"B", "KiB", "MiB", "GiB", "TiB"}
i := 0
for b >= 1024 && i < len(units)-1 {
b /= 1024
i++
}
return fmt.Sprintf("%.1f%s", b, units[i])
}
+102
View File
@@ -0,0 +1,102 @@
package widget
import (
"errors"
"strings"
"testing"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/qf-studio/grot/pkg/tui/theme"
)
func result(vals ...float64) QueryResult {
now := time.Now()
pts := make([]Point, len(vals))
for i, v := range vals {
pts[i] = Point{T: now.Add(time.Duration(i) * time.Minute), V: v}
}
return QueryResult{Series: []Series{{Legend: "test", Points: pts}}, FetchedAt: now}
}
// Every widget must render exactly w×h cells in every state.
func TestWidgetsExactDimensions(t *testing.T) {
th := theme.Pilot
widgets := []Widget{
NewStat("Stat", "short"),
NewGauge("Gauge", "percent", 0, 100),
NewBarGauge("Bars", "short"),
NewTimeSeries("Chart", "s"),
}
states := []struct {
name string
apply func(w Widget)
}{
{"no data", func(w Widget) { w.SetResult(QueryResult{}) }},
{"single point", func(w Widget) { w.SetResult(result(42)) }},
{"range", func(w Widget) { w.SetResult(result(1, 5, 3, 8, 2)) }},
{"error", func(w Widget) { w.SetError(errors.New("connection refused: very long error message that should truncate")) }},
}
sizes := []struct{ w, h int }{{20, 4}, {30, 6}, {50, 12}, {80, 8}}
for _, wg := range widgets {
for _, st := range states {
st.apply(wg)
for _, sz := range sizes {
for _, focused := range []bool{false, true} {
out := wg.Render(sz.w, sz.h, th, focused)
lines := strings.Split(out, "\n")
if len(lines) != sz.h {
t.Errorf("%s/%s %dx%d: %d lines", wg.Title(), st.name, sz.w, sz.h, len(lines))
continue
}
for i, line := range lines {
if got := lipgloss.Width(line); got != sz.w {
t.Errorf("%s/%s %dx%d line %d: width %d", wg.Title(), st.name, sz.w, sz.h, i, got)
}
}
}
}
}
}
}
func TestThresholdColor(t *testing.T) {
th := theme.Pilot
fv := func(v float64) *float64 { return &v }
thresholds := []Threshold{
{Color: "red"}, {Value: fv(70), Color: "yellow"}, {Value: fv(90), Color: "green"},
}
tests := []struct {
v float64
want string
}{
{50, th.Error}, {66, th.Error}, {75, th.Warning}, {95, th.Success},
}
for _, tt := range tests {
if got := thresholdColor(tt.v, thresholds, th, th.Label); got != tt.want {
t.Errorf("thresholdColor(%v) = %q, want %q", tt.v, got, tt.want)
}
}
}
func TestFormatValue(t *testing.T) {
tests := []struct {
v float64
unit string
want string
}{
{66, "percent", "66%"},
{0.665, "percentunit", "66.5%"},
{154.234, "currencyUSD", "$154.23"},
{465.24, "s", "7.8m"},
{0.5, "s", "500ms"},
{57300, "short", "57.3K"},
{3, "", "3"},
}
for _, tt := range tests {
if got := FormatValue(tt.v, tt.unit, nil); got != tt.want {
t.Errorf("FormatValue(%v, %q) = %q, want %q", tt.v, tt.unit, got, tt.want)
}
}
}