feat(app): interactive Bubble Tea dashboard — grid, focus, zoom, polling
Phase 4 of the v0.1 MVP. Consolidates layout/fetch/render into internal/app and adds the interactive TUI; cmd/grot/run.go is now thin CLI wiring. - grid.go: Rect + GridLayout (auto-flow, absolute cells, reflow breakpoints <80/80-139/>=140) + focusMove (overlap-gated geometric hjkl). - fetch.go: FetchWidget/useRange/FetchAll moved out of run.go. - render.go: header, grid compositor, StaticFrame, and safeRender (never renders a widget below its MinSize). - model.go: Bubble Tea Model + RunTUI. tick -> batched per-widget fetch Cmds with an in-flight guard so slow queries never block Update or stack; keys for hjkl focus, Enter zoom, +/- range presets, r refresh, t theme, q quit; WindowSizeMsg reflow; vertical scroll; widget-local errors keep the grid intact. - run.go: default launches the TUI; --once renders one static frame. Fix: an aggressive resize could lay a widget out below its chrome, underflowing width math to a negative strings.Repeat count and panicking in TruncateVisual. TruncateVisual/Center/PadOrTruncate now clamp non-positive widths, and safeRender gates widget sizes — "live resize never breaks the grid". Verified: full interactive TUI against live Prometheus (real PTY) renders all widgets and handles all keys without panic; 12 model tests + grid/step tests; go test -race and golangci-lint clean.
This commit is contained in:
1 parent
4cfb29e515
commit
fbcb245d59
11 files changed
+1101
-198
No files matched your search
+23
-194
@@ -1,23 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/term"
|
||||
|
||||
"github.com/qf-studio/grot/internal/app"
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
"github.com/qf-studio/grot/internal/datasource"
|
||||
"github.com/qf-studio/grot/internal/datasource/prom"
|
||||
"github.com/qf-studio/grot/pkg/tui/render"
|
||||
"github.com/qf-studio/grot/pkg/tui/theme"
|
||||
"github.com/qf-studio/grot/pkg/tui/widget"
|
||||
)
|
||||
@@ -27,8 +20,8 @@ func runCmd() *cobra.Command {
|
||||
cfgPath string
|
||||
promAddr string
|
||||
themeName string
|
||||
watch bool
|
||||
ascii bool
|
||||
once bool
|
||||
)
|
||||
|
||||
cmd := &cobra.Command{
|
||||
@@ -43,7 +36,7 @@ func runCmd() *cobra.Command {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
th := theme.ByName(coalesce(themeName, dash.Theme))
|
||||
th := theme.ByName(firstNonEmpty(themeName, dash.Theme))
|
||||
|
||||
widgets := make([]widget.Widget, len(dash.Widgets))
|
||||
for i, spec := range dash.Widgets {
|
||||
@@ -59,210 +52,46 @@ func runCmd() *cobra.Command {
|
||||
widgets[i] = w
|
||||
}
|
||||
|
||||
refresh := dash.Refresh.Duration()
|
||||
renderFrame := func(ctx context.Context) string {
|
||||
// Lay out once per tick so fetch (range-query step sizing) and
|
||||
// draw share the same cell widths, and both track a resize.
|
||||
lay := planLayout(dash.Widgets, termWidth())
|
||||
fetchAll(ctx, ds, dash, widgets, lay, refresh)
|
||||
return frame(dash, widgets, th, lay)
|
||||
}
|
||||
|
||||
if !watch {
|
||||
fmt.Println(renderFrame(cmd.Context()))
|
||||
if once {
|
||||
w, h := termSize()
|
||||
rects := app.GridLayout(dash.Widgets, w, h)
|
||||
app.FetchAll(cmd.Context(), ds, dash, widgets, rects, fetchTimeout(dash))
|
||||
fmt.Println(app.StaticFrame(dash, widgets, th, w, h))
|
||||
return nil
|
||||
}
|
||||
return watchLoop(cmd.Context(), refresh, renderFrame)
|
||||
return app.RunTUI(cmd.Context(), dash, widgets, ds, th)
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVarP(&cfgPath, "config", "c", "", "dashboard YAML config (required)")
|
||||
cmd.Flags().StringVar(&promAddr, "prom", "http://localhost:9090", "Prometheus base URL")
|
||||
cmd.Flags().StringVar(&themeName, "theme", "", "override theme (default: config theme)")
|
||||
cmd.Flags().BoolVarP(&watch, "watch", "w", false, "refresh on the config interval until Ctrl-C")
|
||||
cmd.Flags().BoolVar(&ascii, "ascii", false, "block-character charts instead of braille")
|
||||
cmd.Flags().BoolVar(&once, "once", false, "render a single static frame and exit (no TUI)")
|
||||
_ = cmd.MarkFlagRequired("config")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// fetchAll runs each widget's queries and delivers results (or errors). A slow
|
||||
// or failing query only affects its own widget — the grid never breaks. The
|
||||
// layout supplies each widget's cell size so range queries can size their step
|
||||
// to the chart width.
|
||||
func fetchAll(ctx context.Context, ds datasource.Datasource, dash *config.Dashboard, widgets []widget.Widget, lay layout, refresh time.Duration) {
|
||||
timeout := 10 * time.Second
|
||||
if refresh > 0 && refresh < timeout {
|
||||
timeout = refresh
|
||||
}
|
||||
rng := dash.Range.Duration()
|
||||
for i, spec := range dash.Widgets {
|
||||
chartW, _ := render.InnerSize(lay.cells[i].W, lay.cells[i].H)
|
||||
cctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
res, err := fetchWidget(cctx, ds, spec, chartW, rng)
|
||||
cancel()
|
||||
if err != nil {
|
||||
widgets[i].SetError(err)
|
||||
continue
|
||||
}
|
||||
widgets[i].SetResult(res)
|
||||
// fetchTimeout bounds a single one-shot fetch: 10s, or the refresh interval if
|
||||
// it is shorter.
|
||||
func fetchTimeout(dash *config.Dashboard) time.Duration {
|
||||
t := 10 * time.Second
|
||||
if r := dash.Refresh.Duration(); r > 0 && r < t {
|
||||
t = r
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func fetchWidget(ctx context.Context, ds datasource.Datasource, spec config.WidgetSpec, chartW int, rng time.Duration) (widget.QueryResult, error) {
|
||||
var all []widget.Series
|
||||
for _, q := range spec.Queries {
|
||||
var (
|
||||
s []widget.Series
|
||||
err error
|
||||
)
|
||||
if useRange(spec, q) {
|
||||
end := time.Now()
|
||||
s, err = ds.QueryRange(ctx, datasource.Range{
|
||||
Expr: q.Expr,
|
||||
Legend: q.Legend,
|
||||
Start: end.Add(-rng),
|
||||
End: end,
|
||||
Step: app.StepFor(rng, chartW),
|
||||
})
|
||||
} else {
|
||||
s, err = ds.QueryInstant(ctx, datasource.Instant{Expr: q.Expr, Legend: q.Legend})
|
||||
}
|
||||
if err != nil {
|
||||
return widget.QueryResult{}, err
|
||||
}
|
||||
all = append(all, s...)
|
||||
// termSize reports the terminal size, falling back to a sane default when
|
||||
// stdout is not a TTY (e.g. piped output for --once).
|
||||
func termSize() (int, int) {
|
||||
if w, h, err := term.GetSize(int(os.Stdout.Fd())); err == nil && w > 40 {
|
||||
return w, h
|
||||
}
|
||||
return widget.QueryResult{Series: all, FetchedAt: time.Now()}, nil
|
||||
return 100, 40
|
||||
}
|
||||
|
||||
// useRange decides whether a query runs as query_range. Time-series panels need
|
||||
// a range to draw a line; single-value panels (stat/gauge/bargauge) reduce to
|
||||
// one point and stay instant. A query may opt back into instant via Instant.
|
||||
func useRange(spec config.WidgetSpec, q config.Query) bool {
|
||||
return spec.Type == config.TypeTimeSeries && !q.Instant
|
||||
}
|
||||
|
||||
// frame renders the header plus the packed grid described by lay.
|
||||
func frame(dash *config.Dashboard, widgets []widget.Widget, th theme.Theme, lay layout) string {
|
||||
header := th.AccentStyle().Bold(true).Render(" "+coalesce(dash.Title, "grot")) +
|
||||
th.DimStyle().Render(" · "+time.Now().Format("15:04:05")+" · "+th.Name)
|
||||
return header + "\n" + packRows(widgets, th, lay)
|
||||
}
|
||||
|
||||
// cellPlan is one widget's outer cell size within the packed grid.
|
||||
type cellPlan struct{ W, H int }
|
||||
|
||||
// layout is the resolved placement for a frame: per-widget cell sizes plus the
|
||||
// grouping of widget indices into rows. Computed once per tick so fetch and
|
||||
// draw agree on widths.
|
||||
type layout struct {
|
||||
cells []cellPlan
|
||||
rows [][]int
|
||||
}
|
||||
|
||||
// planLayout packs widgets left-to-right into rows, even-splitting each row's
|
||||
// width. Phase 3 uses this simple split; the 24-column grid engine arrives in
|
||||
// Phase 4.
|
||||
func planLayout(specs []config.WidgetSpec, termW int) layout {
|
||||
perRow := termW / 34
|
||||
if perRow < 1 {
|
||||
perRow = 1
|
||||
}
|
||||
if perRow > 4 {
|
||||
perRow = 4
|
||||
}
|
||||
|
||||
lay := layout{cells: make([]cellPlan, len(specs))}
|
||||
for start := 0; start < len(specs); start += perRow {
|
||||
end := start + perRow
|
||||
if end > len(specs) {
|
||||
end = len(specs)
|
||||
}
|
||||
n := end - start
|
||||
colW := termW / n
|
||||
rowH := 0
|
||||
for i := start; i < end; i++ {
|
||||
if h := typeHeight(specs[i].Type); h > rowH {
|
||||
rowH = h
|
||||
}
|
||||
}
|
||||
row := make([]int, 0, n)
|
||||
for i := start; i < end; i++ {
|
||||
cellW := colW
|
||||
if i == end-1 {
|
||||
cellW = termW - colW*(n-1) // last column absorbs the remainder
|
||||
}
|
||||
lay.cells[i] = cellPlan{W: cellW, H: rowH}
|
||||
row = append(row, i)
|
||||
}
|
||||
lay.rows = append(lay.rows, row)
|
||||
}
|
||||
return lay
|
||||
}
|
||||
|
||||
// packRows draws the widgets at the sizes fixed by lay.
|
||||
func packRows(widgets []widget.Widget, th theme.Theme, lay layout) string {
|
||||
rows := make([]string, 0, len(lay.rows))
|
||||
for _, idxs := range lay.rows {
|
||||
cols := make([]string, 0, len(idxs))
|
||||
for _, i := range idxs {
|
||||
c := lay.cells[i]
|
||||
cols = append(cols, widgets[i].Render(c.W, c.H, th, false))
|
||||
}
|
||||
rows = append(rows, lipgloss.JoinHorizontal(lipgloss.Top, cols...))
|
||||
}
|
||||
return strings.Join(rows, "\n")
|
||||
}
|
||||
|
||||
func typeHeight(t config.WidgetType) int {
|
||||
switch t {
|
||||
case config.TypeStat:
|
||||
return 6
|
||||
case config.TypeGauge:
|
||||
return 7
|
||||
case config.TypeBarGauge:
|
||||
return 8
|
||||
case config.TypeTimeSeries:
|
||||
return 10
|
||||
}
|
||||
return 6
|
||||
}
|
||||
|
||||
// watchLoop clears the screen and re-renders on the refresh interval until the
|
||||
// context is cancelled or an interrupt arrives.
|
||||
func watchLoop(ctx context.Context, refresh time.Duration, render func(context.Context) string) error {
|
||||
if refresh <= 0 {
|
||||
refresh = 30 * time.Second
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
draw := func() {
|
||||
fmt.Print("\033[H\033[2J") // cursor home + clear screen
|
||||
fmt.Println(render(ctx))
|
||||
}
|
||||
draw()
|
||||
|
||||
t := time.NewTicker(refresh)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-t.C:
|
||||
draw()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func termWidth() int {
|
||||
if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && w > 40 {
|
||||
return w
|
||||
}
|
||||
return 100
|
||||
}
|
||||
|
||||
func coalesce(vals ...string) string {
|
||||
func firstNonEmpty(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if v != "" {
|
||||
return v
|
||||
|
||||
@@ -3,6 +3,7 @@ module github.com/qf-studio/grot
|
||||
go 1.25.6
|
||||
|
||||
require (
|
||||
github.com/charmbracelet/bubbletea v1.3.10
|
||||
github.com/charmbracelet/lipgloss v1.1.0
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/prometheus/common v0.66.1
|
||||
@@ -14,17 +15,21 @@ require (
|
||||
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/ansi v0.10.1 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
|
||||
github.com/charmbracelet/x/term v0.2.1 // indirect
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/kr/text v0.2.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-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
|
||||
github.com/muesli/cancelreader v0.2.2 // indirect
|
||||
github.com/muesli/termenv v0.16.0 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/rivo/uniseg v0.4.7 // indirect
|
||||
@@ -32,5 +37,6 @@ require (
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.28.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
)
|
||||
@@ -4,12 +4,14 @@ github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
|
||||
github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
|
||||
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/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
|
||||
github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
|
||||
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=
|
||||
@@ -19,6 +21,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
|
||||
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
@@ -36,6 +40,8 @@ github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69
|
||||
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-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
|
||||
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
|
||||
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/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -43,6 +49,10 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
|
||||
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
|
||||
github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
|
||||
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
|
||||
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/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
@@ -84,6 +94,7 @@ golang.org/x/net v0.43.0 h1:lat02VYK2j4aLzMzecihNvTlJNQUq316m2Mr9rnM6YE=
|
||||
golang.org/x/net v0.43.0/go.mod h1:vhO1fvI4dGsIjh73sWfUVjj3N7CA9WkKJNQm2svM6Jg=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
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=
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
"github.com/qf-studio/grot/internal/datasource"
|
||||
"github.com/qf-studio/grot/pkg/tui/render"
|
||||
"github.com/qf-studio/grot/pkg/tui/widget"
|
||||
)
|
||||
|
||||
// FetchWidget runs every query in spec and returns the combined result.
|
||||
// Time-series queries go through query_range (windowed [now-rng, now] at a step
|
||||
// sized to chartW); everything else is an instant query. chartW is the widget's
|
||||
// inner chart width in cells — used only to size the range step.
|
||||
func FetchWidget(ctx context.Context, ds datasource.Datasource, spec config.WidgetSpec, chartW int, rng time.Duration) (widget.QueryResult, error) {
|
||||
var all []widget.Series
|
||||
for _, q := range spec.Queries {
|
||||
var (
|
||||
s []widget.Series
|
||||
err error
|
||||
)
|
||||
if useRange(spec, q) {
|
||||
end := time.Now()
|
||||
s, err = ds.QueryRange(ctx, datasource.Range{
|
||||
Expr: q.Expr,
|
||||
Legend: q.Legend,
|
||||
Start: end.Add(-rng),
|
||||
End: end,
|
||||
Step: StepFor(rng, chartW),
|
||||
})
|
||||
} else {
|
||||
s, err = ds.QueryInstant(ctx, datasource.Instant{Expr: q.Expr, Legend: q.Legend})
|
||||
}
|
||||
if err != nil {
|
||||
return widget.QueryResult{}, err
|
||||
}
|
||||
all = append(all, s...)
|
||||
}
|
||||
return widget.QueryResult{Series: all, FetchedAt: time.Now()}, nil
|
||||
}
|
||||
|
||||
// FetchAll fetches every widget synchronously, assigning each its result or
|
||||
// error. A failing query only marks its own widget — the grid stays intact.
|
||||
// Used by the one-shot (--once) path; the TUI fetches concurrently instead.
|
||||
func FetchAll(ctx context.Context, ds datasource.Datasource, dash *config.Dashboard, widgets []widget.Widget, rects []Rect, timeout time.Duration) {
|
||||
rng := dash.Range.Duration()
|
||||
for i, spec := range dash.Widgets {
|
||||
cctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
res, err := FetchWidget(cctx, ds, spec, chartWidth(rects[i]), rng)
|
||||
cancel()
|
||||
if err != nil {
|
||||
widgets[i].SetError(err)
|
||||
continue
|
||||
}
|
||||
widgets[i].SetResult(res)
|
||||
}
|
||||
}
|
||||
|
||||
// useRange decides whether a query runs as query_range. Time-series panels need
|
||||
// a range to draw a line; single-value panels (stat/gauge/bargauge) reduce to
|
||||
// one point and stay instant. A query may opt back into instant via Instant.
|
||||
func useRange(spec config.WidgetSpec, q config.Query) bool {
|
||||
return spec.Type == config.TypeTimeSeries && !q.Instant
|
||||
}
|
||||
|
||||
// chartWidth returns the inner chart width for a cell rect — the value
|
||||
// FetchWidget wants for range-step sizing.
|
||||
func chartWidth(r Rect) int {
|
||||
w, _ := render.InnerSize(r.W, r.H)
|
||||
return w
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package app
|
||||
|
||||
import "github.com/qf-studio/grot/internal/config"
|
||||
|
||||
// Rect is a widget's placement in terminal cells, top-left origin.
|
||||
type Rect struct{ X, Y, W, H int }
|
||||
|
||||
// minColW is the narrowest a widget cell is allowed to get before the packer
|
||||
// drops to fewer columns per row.
|
||||
const minColW = 34
|
||||
|
||||
// typeHeight is the row height (in terminal cells) a widget of the given type
|
||||
// wants. Charts are tallest; single-value panels are short.
|
||||
func typeHeight(t config.WidgetType) int {
|
||||
switch t {
|
||||
case config.TypeStat:
|
||||
return 6
|
||||
case config.TypeGauge:
|
||||
return 7
|
||||
case config.TypeBarGauge:
|
||||
return 8
|
||||
case config.TypeTimeSeries:
|
||||
return 10
|
||||
}
|
||||
return 6
|
||||
}
|
||||
|
||||
// maxPerRow caps how many widgets share a row at each width breakpoint:
|
||||
// <80 → single column, 80–139 → up to two, ≥140 → up to four.
|
||||
func maxPerRow(termW int) int {
|
||||
switch {
|
||||
case termW < 80:
|
||||
return 1
|
||||
case termW < 140:
|
||||
return 2
|
||||
default:
|
||||
return 4
|
||||
}
|
||||
}
|
||||
|
||||
// GridLayout arranges widgets into absolute terminal-cell rectangles for a
|
||||
// termW×termH viewport. It auto-flows left-to-right, wrapping into rows; each
|
||||
// row's height is the tallest widget in it, and the last cell absorbs any
|
||||
// rounding remainder so rows always span the full width. Reflow is driven by
|
||||
// width breakpoints (see maxPerRow). termH is currently advisory — vertical
|
||||
// overflow is handled by the caller's scroll, not by squeezing rows.
|
||||
//
|
||||
// The 24-column gridPos honoring path (Grafana import) lands in Phase 5; this
|
||||
// packer serves native configs, which typically omit explicit placement.
|
||||
func GridLayout(specs []config.WidgetSpec, termW, termH int) []Rect {
|
||||
_ = termH
|
||||
rects := make([]Rect, len(specs))
|
||||
if len(specs) == 0 {
|
||||
return rects
|
||||
}
|
||||
|
||||
per := maxPerRow(termW)
|
||||
if fit := termW / minColW; fit < per {
|
||||
per = fit
|
||||
}
|
||||
if per < 1 {
|
||||
per = 1
|
||||
}
|
||||
|
||||
y := 0
|
||||
for start := 0; start < len(specs); start += per {
|
||||
end := start + per
|
||||
if end > len(specs) {
|
||||
end = len(specs)
|
||||
}
|
||||
n := end - start
|
||||
colW := termW / n
|
||||
rowH := 0
|
||||
for i := start; i < end; i++ {
|
||||
if h := typeHeight(specs[i].Type); h > rowH {
|
||||
rowH = h
|
||||
}
|
||||
}
|
||||
x := 0
|
||||
for i := start; i < end; i++ {
|
||||
w := colW
|
||||
if i == end-1 {
|
||||
w = termW - colW*(n-1) // last column absorbs the remainder
|
||||
}
|
||||
rects[i] = Rect{X: x, Y: y, W: w, H: rowH}
|
||||
x += colW
|
||||
}
|
||||
y += rowH
|
||||
}
|
||||
return rects
|
||||
}
|
||||
|
||||
// GridHeight is the total cell height the laid-out grid occupies.
|
||||
func GridHeight(rects []Rect) int {
|
||||
max := 0
|
||||
for _, r := range rects {
|
||||
if b := r.Y + r.H; b > max {
|
||||
max = b
|
||||
}
|
||||
}
|
||||
return max
|
||||
}
|
||||
|
||||
// focusMove returns the index of the widget nearest to cur in direction dir
|
||||
// ('h' left, 'j' down, 'k' up, 'l' right), or cur when nothing lies that way.
|
||||
// Horizontal moves only consider widgets whose rows overlap the current one
|
||||
// (and vertical moves, columns), then pick the nearest by edge distance — so
|
||||
// focus tracks the visual row/column rather than drifting diagonally.
|
||||
func focusMove(rects []Rect, cur int, dir byte) int {
|
||||
if cur < 0 || cur >= len(rects) {
|
||||
return cur
|
||||
}
|
||||
c := rects[cur]
|
||||
best, bestDist, found := cur, 0, false
|
||||
for i, r := range rects {
|
||||
if i == cur {
|
||||
continue
|
||||
}
|
||||
var dist int
|
||||
switch dir {
|
||||
case 'h':
|
||||
if r.X >= c.X || !overlaps(c.Y, c.H, r.Y, r.H) {
|
||||
continue
|
||||
}
|
||||
dist = c.X - r.X
|
||||
case 'l':
|
||||
if r.X <= c.X || !overlaps(c.Y, c.H, r.Y, r.H) {
|
||||
continue
|
||||
}
|
||||
dist = r.X - c.X
|
||||
case 'k':
|
||||
if r.Y >= c.Y || !overlaps(c.X, c.W, r.X, r.W) {
|
||||
continue
|
||||
}
|
||||
dist = c.Y - r.Y
|
||||
case 'j':
|
||||
if r.Y <= c.Y || !overlaps(c.X, c.W, r.X, r.W) {
|
||||
continue
|
||||
}
|
||||
dist = r.Y - c.Y
|
||||
default:
|
||||
return cur
|
||||
}
|
||||
if !found || dist < bestDist {
|
||||
bestDist, best, found = dist, i, true
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// overlaps reports whether the spans [a, a+al) and [b, b+bl) intersect.
|
||||
func overlaps(a, al, b, bl int) bool {
|
||||
return a < b+bl && b < a+al
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
)
|
||||
|
||||
func specs(types ...config.WidgetType) []config.WidgetSpec {
|
||||
out := make([]config.WidgetSpec, len(types))
|
||||
for i, t := range types {
|
||||
out[i] = config.WidgetSpec{Type: t}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestGridLayoutBreakpoints(t *testing.T) {
|
||||
four := specs(config.TypeStat, config.TypeStat, config.TypeStat, config.TypeStat)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
termW int
|
||||
wantPerRow int // widgets sharing the first row
|
||||
}{
|
||||
{"narrow stacks single column", 70, 1},
|
||||
{"medium packs two", 100, 2},
|
||||
{"wide packs four", 200, 4},
|
||||
{"width caps at ~34-col min", 80, 2}, // 80/34 = 2
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
rects := GridLayout(four, tt.termW, 50)
|
||||
firstRowY := rects[0].Y
|
||||
got := 0
|
||||
for _, r := range rects {
|
||||
if r.Y == firstRowY {
|
||||
got++
|
||||
}
|
||||
}
|
||||
if got != tt.wantPerRow {
|
||||
t.Errorf("termW=%d: first row has %d widgets, want %d", tt.termW, got, tt.wantPerRow)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGridLayoutSpansFullWidth(t *testing.T) {
|
||||
// Every row must span exactly termW with no gaps or overhang.
|
||||
rects := GridLayout(specs(config.TypeStat, config.TypeStat, config.TypeStat), 141, 50)
|
||||
byRow := map[int][]Rect{}
|
||||
for _, r := range rects {
|
||||
byRow[r.Y] = append(byRow[r.Y], r)
|
||||
}
|
||||
for y, row := range byRow {
|
||||
right := 0
|
||||
x := 0
|
||||
for _, r := range row {
|
||||
if r.X != x {
|
||||
t.Errorf("row y=%d: gap — rect X=%d, expected %d", y, r.X, x)
|
||||
}
|
||||
x += r.W
|
||||
right = r.X + r.W
|
||||
}
|
||||
if right != 141 {
|
||||
t.Errorf("row y=%d spans %d cells, want 141", y, right)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGridLayoutRowHeightIsTallest(t *testing.T) {
|
||||
// A stat (6) beside a timeseries (10) share the timeseries height.
|
||||
rects := GridLayout(specs(config.TypeStat, config.TypeTimeSeries), 200, 50)
|
||||
if rects[0].H != rects[1].H {
|
||||
t.Fatalf("cells in a row differ in height: %d vs %d", rects[0].H, rects[1].H)
|
||||
}
|
||||
if rects[0].H != typeHeight(config.TypeTimeSeries) {
|
||||
t.Errorf("row height = %d, want tallest %d", rects[0].H, typeHeight(config.TypeTimeSeries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGridLayoutEmpty(t *testing.T) {
|
||||
if got := GridLayout(nil, 100, 50); len(got) != 0 {
|
||||
t.Errorf("empty specs → %d rects, want 0", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFocusMove(t *testing.T) {
|
||||
// 2×2 grid of equal cells:
|
||||
// 0 1
|
||||
// 2 3
|
||||
rects := []Rect{
|
||||
{X: 0, Y: 0, W: 10, H: 5},
|
||||
{X: 10, Y: 0, W: 10, H: 5},
|
||||
{X: 0, Y: 5, W: 10, H: 5},
|
||||
{X: 10, Y: 5, W: 10, H: 5},
|
||||
}
|
||||
tests := []struct {
|
||||
cur int
|
||||
dir byte
|
||||
want int
|
||||
}{
|
||||
{0, 'l', 1},
|
||||
{0, 'j', 2},
|
||||
{1, 'h', 0},
|
||||
{3, 'k', 1},
|
||||
{3, 'h', 2},
|
||||
{0, 'h', 0}, // nothing to the left → stays
|
||||
{0, 'k', 0}, // nothing above → stays
|
||||
{2, 'j', 2}, // nothing below → stays
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := focusMove(rects, tt.cur, tt.dir); got != tt.want {
|
||||
t.Errorf("focusMove(cur=%d, dir=%c) = %d, want %d", tt.cur, tt.dir, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGridHeight(t *testing.T) {
|
||||
rects := GridLayout(specs(config.TypeStat, config.TypeStat, config.TypeTimeSeries), 70, 50)
|
||||
// Narrow → single column stack: 6 + 6 + 10 = 22.
|
||||
if got := GridHeight(rects); got != 22 {
|
||||
t.Errorf("GridHeight = %d, want 22", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
"github.com/qf-studio/grot/internal/datasource"
|
||||
"github.com/qf-studio/grot/pkg/tui/theme"
|
||||
"github.com/qf-studio/grot/pkg/tui/widget"
|
||||
)
|
||||
|
||||
// rangePresets are the windows the +/- keys step through.
|
||||
var rangePresets = []time.Duration{
|
||||
5 * time.Minute, 15 * time.Minute, 30 * time.Minute,
|
||||
1 * time.Hour, 3 * time.Hour, 6 * time.Hour, 12 * time.Hour, 24 * time.Hour,
|
||||
}
|
||||
|
||||
// tickMsg fires on the refresh interval; fetchedMsg delivers one widget's data.
|
||||
type (
|
||||
tickMsg time.Time
|
||||
fetchedMsg struct {
|
||||
idx int
|
||||
res widget.QueryResult
|
||||
err error
|
||||
}
|
||||
)
|
||||
|
||||
// Model is grot's Bubble Tea application: a focusable, zoomable grid of widgets
|
||||
// backed by a polling datasource. Fetches run as concurrent Cmds guarded so a
|
||||
// slow query never blocks Update or stacks up behind itself.
|
||||
type Model struct {
|
||||
dash *config.Dashboard
|
||||
specs []config.WidgetSpec
|
||||
widgets []widget.Widget
|
||||
ds datasource.Datasource
|
||||
|
||||
th theme.Theme
|
||||
themeIdx int
|
||||
|
||||
width, height int
|
||||
rects []Rect
|
||||
focus int
|
||||
zoomed bool
|
||||
scroll int
|
||||
ready bool
|
||||
|
||||
rng time.Duration
|
||||
rangeIdx int
|
||||
refresh time.Duration
|
||||
|
||||
inflight []bool
|
||||
fetchedAt []time.Time
|
||||
}
|
||||
|
||||
// NewModel builds the application model. Widgets must already be constructed
|
||||
// (see BuildWidget); data is fetched by the running program.
|
||||
func NewModel(dash *config.Dashboard, widgets []widget.Widget, ds datasource.Datasource, th theme.Theme) Model {
|
||||
return Model{
|
||||
dash: dash,
|
||||
specs: dash.Widgets,
|
||||
widgets: widgets,
|
||||
ds: ds,
|
||||
th: th,
|
||||
themeIdx: themeIndex(th.Name),
|
||||
rng: dash.Range.Duration(),
|
||||
rangeIdx: nearestRange(dash.Range.Duration()),
|
||||
refresh: dash.Refresh.Duration(),
|
||||
inflight: make([]bool, len(widgets)),
|
||||
fetchedAt: make([]time.Time, len(widgets)),
|
||||
}
|
||||
}
|
||||
|
||||
// RunTUI runs the interactive dashboard until quit, Ctrl-C, or ctx cancel.
|
||||
func RunTUI(ctx context.Context, dash *config.Dashboard, widgets []widget.Widget, ds datasource.Datasource, th theme.Theme) error {
|
||||
ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
p := tea.NewProgram(
|
||||
NewModel(dash, widgets, ds, th),
|
||||
tea.WithAltScreen(),
|
||||
tea.WithContext(ctx),
|
||||
)
|
||||
_, err := p.Run()
|
||||
return err
|
||||
}
|
||||
|
||||
func (m Model) Init() tea.Cmd { return m.tickCmd() }
|
||||
|
||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||
switch msg := msg.(type) {
|
||||
case tea.WindowSizeMsg:
|
||||
m.width, m.height = msg.Width, msg.Height
|
||||
m.rects = GridLayout(m.specs, m.width, m.contentHeight())
|
||||
m.clampFocus()
|
||||
m.ensureVisible()
|
||||
if !m.ready {
|
||||
m.ready = true
|
||||
return m, m.fetchDueCmd() // first paint has dimensions → fetch now
|
||||
}
|
||||
return m, nil
|
||||
|
||||
case tea.KeyMsg:
|
||||
return m.handleKey(msg)
|
||||
|
||||
case tickMsg:
|
||||
return m, tea.Batch(m.fetchDueCmd(), m.tickCmd())
|
||||
|
||||
case fetchedMsg:
|
||||
if msg.idx >= 0 && msg.idx < len(m.widgets) {
|
||||
m.inflight[msg.idx] = false
|
||||
m.fetchedAt[msg.idx] = time.Now()
|
||||
if msg.err != nil {
|
||||
m.widgets[msg.idx].SetError(msg.err)
|
||||
} else {
|
||||
m.widgets[msg.idx].SetResult(msg.res)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (m Model) View() string {
|
||||
if !m.ready {
|
||||
return ""
|
||||
}
|
||||
header := headerLine(coalesce(m.dash.Title, "grot"), m.th, formatRange(m.rng), m.zoomed, m.staleNames())
|
||||
if m.zoomed && len(m.widgets) > 0 {
|
||||
r := m.fetchRect(m.focus)
|
||||
return header + "\n" + safeRender(m.widgets[m.focus], r.W, r.H, m.th, true)
|
||||
}
|
||||
grid := composeGrid(m.widgets, m.rects, m.th, m.focus)
|
||||
return header + "\n" + cropVertical(grid, m.scroll, m.contentHeight())
|
||||
}
|
||||
|
||||
func (m Model) handleKey(k tea.KeyMsg) (tea.Model, tea.Cmd) {
|
||||
switch k.String() {
|
||||
case "q", "ctrl+c":
|
||||
return m, tea.Quit
|
||||
case "h", "left":
|
||||
m.focus = focusMove(m.rects, m.focus, 'h')
|
||||
m.ensureVisible()
|
||||
case "j", "down":
|
||||
m.focus = focusMove(m.rects, m.focus, 'j')
|
||||
m.ensureVisible()
|
||||
case "k", "up":
|
||||
m.focus = focusMove(m.rects, m.focus, 'k')
|
||||
m.ensureVisible()
|
||||
case "l", "right":
|
||||
m.focus = focusMove(m.rects, m.focus, 'l')
|
||||
m.ensureVisible()
|
||||
case "enter":
|
||||
m.zoomed = !m.zoomed
|
||||
case "+", "=":
|
||||
if m.rangeIdx < len(rangePresets)-1 {
|
||||
m.rangeIdx++
|
||||
m.rng = rangePresets[m.rangeIdx]
|
||||
return m, m.fetchDueCmd()
|
||||
}
|
||||
case "-", "_":
|
||||
if m.rangeIdx > 0 {
|
||||
m.rangeIdx--
|
||||
m.rng = rangePresets[m.rangeIdx]
|
||||
return m, m.fetchDueCmd()
|
||||
}
|
||||
case "r":
|
||||
return m, m.fetchDueCmd()
|
||||
case "t":
|
||||
m.themeIdx = (m.themeIdx + 1) % len(theme.All)
|
||||
m.th = theme.All[m.themeIdx]
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// fetchDueCmd dispatches a fetch for every widget not already in flight,
|
||||
// marking them so they don't stack. Returns nil when all are busy.
|
||||
func (m *Model) fetchDueCmd() tea.Cmd {
|
||||
var cmds []tea.Cmd
|
||||
for i := range m.widgets {
|
||||
if m.inflight[i] {
|
||||
continue
|
||||
}
|
||||
m.inflight[i] = true
|
||||
cmds = append(cmds, m.fetchCmd(i))
|
||||
}
|
||||
if len(cmds) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tea.Batch(cmds...)
|
||||
}
|
||||
|
||||
// fetchCmd captures the current step/range/width for widget i and fetches off
|
||||
// the Update goroutine.
|
||||
func (m Model) fetchCmd(i int) tea.Cmd {
|
||||
spec := m.specs[i]
|
||||
cw := chartWidth(m.fetchRect(i))
|
||||
rng := m.rng
|
||||
ds := m.ds
|
||||
timeout := m.timeout()
|
||||
return func() tea.Msg {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
res, err := FetchWidget(ctx, ds, spec, cw, rng)
|
||||
return fetchedMsg{idx: i, res: res, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
// fetchRect is the rectangle a widget currently occupies — the full content
|
||||
// area when it is the zoomed widget, otherwise its grid cell.
|
||||
func (m Model) fetchRect(i int) Rect {
|
||||
if m.zoomed && i == m.focus {
|
||||
return Rect{W: m.width, H: m.contentHeight()}
|
||||
}
|
||||
if i >= 0 && i < len(m.rects) {
|
||||
return m.rects[i]
|
||||
}
|
||||
return Rect{}
|
||||
}
|
||||
|
||||
// staleNames lists widgets whose freshest data is older than twice the refresh
|
||||
// interval — surfaced as an amber hint in the header.
|
||||
func (m Model) staleNames() []string {
|
||||
if m.refresh <= 0 {
|
||||
return nil
|
||||
}
|
||||
var names []string
|
||||
for i, at := range m.fetchedAt {
|
||||
if at.IsZero() {
|
||||
continue
|
||||
}
|
||||
if time.Since(at) > 2*m.refresh {
|
||||
names = append(names, m.widgets[i].Title())
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func (m *Model) ensureVisible() {
|
||||
if m.zoomed || m.focus < 0 || m.focus >= len(m.rects) {
|
||||
return
|
||||
}
|
||||
r := m.rects[m.focus]
|
||||
ch := m.contentHeight()
|
||||
if r.Y < m.scroll {
|
||||
m.scroll = r.Y
|
||||
}
|
||||
if r.Y+r.H > m.scroll+ch {
|
||||
m.scroll = r.Y + r.H - ch
|
||||
}
|
||||
if m.scroll < 0 {
|
||||
m.scroll = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) clampFocus() {
|
||||
if m.focus >= len(m.widgets) {
|
||||
m.focus = len(m.widgets) - 1
|
||||
}
|
||||
if m.focus < 0 {
|
||||
m.focus = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (m Model) contentHeight() int {
|
||||
h := m.height - 1 // header row
|
||||
if h < 1 {
|
||||
return 1
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func (m Model) timeout() time.Duration {
|
||||
t := 10 * time.Second
|
||||
if m.refresh > 0 && m.refresh < t {
|
||||
t = m.refresh
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func (m Model) tickCmd() tea.Cmd {
|
||||
d := m.refresh
|
||||
if d <= 0 {
|
||||
d = 30 * time.Second
|
||||
}
|
||||
return tea.Tick(d, func(t time.Time) tea.Msg { return tickMsg(t) })
|
||||
}
|
||||
|
||||
// cropVertical returns the height lines of s starting at offset, for scroll.
|
||||
func cropVertical(s string, offset, height int) string {
|
||||
lines := strings.Split(s, "\n")
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
if offset > len(lines) {
|
||||
offset = len(lines)
|
||||
}
|
||||
end := offset + height
|
||||
if end > len(lines) {
|
||||
end = len(lines)
|
||||
}
|
||||
return strings.Join(lines[offset:end], "\n")
|
||||
}
|
||||
|
||||
func nearestRange(d time.Duration) int {
|
||||
best, bestDiff := 0, absDur(rangePresets[0]-d)
|
||||
for i, p := range rangePresets {
|
||||
if diff := absDur(p - d); diff < bestDiff {
|
||||
best, bestDiff = i, diff
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func absDur(d time.Duration) time.Duration {
|
||||
if d < 0 {
|
||||
return -d
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func themeIndex(name string) int {
|
||||
for i, t := range theme.All {
|
||||
if t.Name == name {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
tea "github.com/charmbracelet/bubbletea"
|
||||
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
"github.com/qf-studio/grot/internal/datasource"
|
||||
"github.com/qf-studio/grot/pkg/tui/theme"
|
||||
"github.com/qf-studio/grot/pkg/tui/widget"
|
||||
)
|
||||
|
||||
// fakeDS returns canned data and counts calls.
|
||||
type fakeDS struct{ instant, rng int }
|
||||
|
||||
func (f *fakeDS) QueryInstant(context.Context, datasource.Instant) ([]widget.Series, error) {
|
||||
f.instant++
|
||||
return []widget.Series{{Legend: "v", Points: []widget.Point{{V: 42}}}}, nil
|
||||
}
|
||||
|
||||
func (f *fakeDS) QueryRange(context.Context, datasource.Range) ([]widget.Series, error) {
|
||||
f.rng++
|
||||
return []widget.Series{{Legend: "s", Points: []widget.Point{{V: 1}, {V: 2}, {V: 3}}}}, nil
|
||||
}
|
||||
|
||||
func runeKey(r rune) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{r}} }
|
||||
|
||||
func drive(m Model, msg tea.Msg) Model {
|
||||
nm, _ := m.Update(msg)
|
||||
return nm.(Model)
|
||||
}
|
||||
|
||||
func newModel(t *testing.T) (Model, *fakeDS) {
|
||||
t.Helper()
|
||||
ds := &fakeDS{}
|
||||
dash := &config.Dashboard{
|
||||
Title: "test",
|
||||
Theme: "pilot",
|
||||
Refresh: config.Duration(30 * time.Second),
|
||||
Range: config.Duration(15 * time.Minute),
|
||||
Widgets: []config.WidgetSpec{
|
||||
{Type: config.TypeStat, Title: "a", Queries: []config.Query{{Expr: "x"}}},
|
||||
{Type: config.TypeStat, Title: "b", Queries: []config.Query{{Expr: "y"}}},
|
||||
{Type: config.TypeTimeSeries, Title: "c", Queries: []config.Query{{Expr: "z"}}},
|
||||
},
|
||||
}
|
||||
widgets := make([]widget.Widget, len(dash.Widgets))
|
||||
for i, spec := range dash.Widgets {
|
||||
w, err := BuildWidget(spec)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildWidget: %v", err)
|
||||
}
|
||||
widgets[i] = w
|
||||
}
|
||||
return NewModel(dash, widgets, ds, theme.Pilot), ds
|
||||
}
|
||||
|
||||
func TestModelReadyAndView(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
if m.View() != "" {
|
||||
t.Error("View before sizing should be empty")
|
||||
}
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
if !m.ready {
|
||||
t.Fatal("WindowSizeMsg should mark model ready")
|
||||
}
|
||||
if len(m.rects) != 3 {
|
||||
t.Fatalf("expected 3 rects, got %d", len(m.rects))
|
||||
}
|
||||
if v := m.View(); !strings.Contains(v, "test") {
|
||||
t.Errorf("View missing title; got:\n%s", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelFocusMovement(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40}) // 2 per row
|
||||
if m.focus != 0 {
|
||||
t.Fatalf("initial focus = %d, want 0", m.focus)
|
||||
}
|
||||
m = drive(m, runeKey('l'))
|
||||
if m.focus != 1 {
|
||||
t.Errorf("after 'l', focus = %d, want 1", m.focus)
|
||||
}
|
||||
m = drive(m, runeKey('h'))
|
||||
if m.focus != 0 {
|
||||
t.Errorf("after 'h', focus = %d, want 0", m.focus)
|
||||
}
|
||||
m = drive(m, runeKey('j'))
|
||||
if m.focus == 0 {
|
||||
t.Errorf("after 'j', focus should leave row 0, still %d", m.focus)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelZoomToggle(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
m = drive(m, tea.KeyMsg{Type: tea.KeyEnter})
|
||||
if !m.zoomed {
|
||||
t.Error("Enter should zoom")
|
||||
}
|
||||
m = drive(m, tea.KeyMsg{Type: tea.KeyEnter})
|
||||
if m.zoomed {
|
||||
t.Error("Enter again should unzoom")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelRangePresets(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
if m.rng != 15*time.Minute {
|
||||
t.Fatalf("initial range = %s, want 15m", m.rng)
|
||||
}
|
||||
m = drive(m, runeKey('+'))
|
||||
if m.rng != 30*time.Minute {
|
||||
t.Errorf("after '+', range = %s, want 30m", m.rng)
|
||||
}
|
||||
m = drive(m, runeKey('-'))
|
||||
m = drive(m, runeKey('-'))
|
||||
if m.rng != 5*time.Minute {
|
||||
t.Errorf("after '--', range = %s, want 5m", m.rng)
|
||||
}
|
||||
// Clamp at the low end.
|
||||
m = drive(m, runeKey('-'))
|
||||
if m.rng != 5*time.Minute {
|
||||
t.Errorf("range should clamp at 5m, got %s", m.rng)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelThemeCycle(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
start := m.th.Name
|
||||
m = drive(m, runeKey('t'))
|
||||
if m.th.Name == start {
|
||||
t.Errorf("'t' should change theme from %s", start)
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelQuit(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
_, cmd := m.Update(runeKey('q'))
|
||||
if cmd == nil {
|
||||
t.Fatal("'q' should return a command")
|
||||
}
|
||||
if _, ok := cmd().(tea.QuitMsg); !ok {
|
||||
t.Error("'q' should return tea.Quit")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelFetchCmdAndResult(t *testing.T) {
|
||||
m, ds := newModel(t)
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
|
||||
// Stat widget 0 → instant; timeseries widget 2 → range.
|
||||
if msg, ok := m.fetchCmd(0)().(fetchedMsg); !ok || msg.idx != 0 || msg.err != nil {
|
||||
t.Errorf("fetchCmd(0) bad msg: %#v", msg)
|
||||
}
|
||||
if msg, ok := m.fetchCmd(2)().(fetchedMsg); !ok || msg.idx != 2 || msg.err != nil {
|
||||
t.Errorf("fetchCmd(2) bad msg: %#v", msg)
|
||||
}
|
||||
if ds.instant == 0 || ds.rng == 0 {
|
||||
t.Errorf("expected both instant and range queries; got instant=%d range=%d", ds.instant, ds.rng)
|
||||
}
|
||||
|
||||
// Delivering a result clears in-flight and stamps fetchedAt.
|
||||
m.inflight[0] = true
|
||||
m = drive(m, fetchedMsg{idx: 0, res: widget.QueryResult{FetchedAt: time.Now()}})
|
||||
if m.inflight[0] {
|
||||
t.Error("fetchedMsg should clear in-flight")
|
||||
}
|
||||
if m.fetchedAt[0].IsZero() {
|
||||
t.Error("fetchedMsg should stamp fetchedAt")
|
||||
}
|
||||
}
|
||||
|
||||
func TestModelInFlightGuard(t *testing.T) {
|
||||
m, _ := newModel(t)
|
||||
// Becoming ready dispatches the initial fetch, marking every widget in flight.
|
||||
m = drive(m, tea.WindowSizeMsg{Width: 100, Height: 40})
|
||||
for i, f := range m.inflight {
|
||||
if !f {
|
||||
t.Errorf("widget %d should be in-flight after initial dispatch", i)
|
||||
}
|
||||
}
|
||||
// A dispatch while all are busy is a no-op — slow queries can't stack.
|
||||
if cmd := m.fetchDueCmd(); cmd != nil {
|
||||
t.Error("fetchDueCmd should be a no-op while all in flight")
|
||||
}
|
||||
// Completing the fetches frees them...
|
||||
for i := range m.widgets {
|
||||
m = drive(m, fetchedMsg{idx: i, res: widget.QueryResult{FetchedAt: time.Now()}})
|
||||
}
|
||||
for i, f := range m.inflight {
|
||||
if f {
|
||||
t.Errorf("widget %d still in-flight after result", i)
|
||||
}
|
||||
}
|
||||
// ...so the next dispatch runs again.
|
||||
if cmd := m.fetchDueCmd(); cmd == nil {
|
||||
t.Fatal("fetchDueCmd should dispatch once widgets are idle")
|
||||
}
|
||||
}
|
||||
|
||||
// TestSafeRenderTiny ensures a widget squeezed below its MinSize yields a blank
|
||||
// box of the exact size instead of panicking on underflowed width math.
|
||||
func TestSafeRenderTiny(t *testing.T) {
|
||||
w, err := BuildWidget(config.WidgetSpec{Type: config.TypeTimeSeries, Title: "c", Queries: []config.Query{{Expr: "z"}}})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildWidget: %v", err)
|
||||
}
|
||||
for _, sz := range []struct{ w, h int }{{0, 0}, {1, 1}, {3, 2}, {10, 3}} {
|
||||
out := safeRender(w, sz.w, sz.h, theme.Pilot, false) // must not panic
|
||||
lines := 0
|
||||
if out != "" {
|
||||
lines = strings.Count(out, "\n") + 1
|
||||
}
|
||||
if sz.h > 0 && sz.w >= 0 && lines > sz.h {
|
||||
t.Errorf("safeRender(%dx%d) produced %d lines, want <= %d", sz.w, sz.h, lines, sz.h)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
|
||||
"github.com/qf-studio/grot/internal/config"
|
||||
"github.com/qf-studio/grot/pkg/tui/theme"
|
||||
"github.com/qf-studio/grot/pkg/tui/widget"
|
||||
)
|
||||
|
||||
// StaticFrame renders a one-shot header + grid at the given viewport, with no
|
||||
// focus. Widgets must already hold their fetched results.
|
||||
func StaticFrame(dash *config.Dashboard, widgets []widget.Widget, th theme.Theme, termW, termH int) string {
|
||||
rects := GridLayout(dash.Widgets, termW, termH)
|
||||
title := coalesce(dash.Title, "grot")
|
||||
header := headerLine(title, th, formatRange(dash.Range.Duration()), false, nil)
|
||||
return header + "\n" + composeGrid(widgets, rects, th, -1)
|
||||
}
|
||||
|
||||
// headerLine is the quiet top strip: bold title, then dim clock · theme · range,
|
||||
// plus an amber stale hint when any widget's data has aged out.
|
||||
func headerLine(title string, th theme.Theme, rangeLabel string, zoomed bool, stale []string) string {
|
||||
b := new(strings.Builder)
|
||||
b.WriteString(th.AccentStyle().Bold(true).Render(" " + title))
|
||||
meta := " · " + time.Now().Format("15:04:05") + " · " + th.Name + " · " + rangeLabel
|
||||
if zoomed {
|
||||
meta += " · zoom"
|
||||
}
|
||||
b.WriteString(th.DimStyle().Render(meta))
|
||||
if len(stale) > 0 {
|
||||
b.WriteString(th.WarningStyle().Render(" · stale: " + strings.Join(stale, ", ")))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// composeGrid draws widgets into their row-ordered rects. Rects sharing a Y
|
||||
// form one row joined horizontally; rows stack vertically. focus is the index
|
||||
// drawn focused (-1 for none).
|
||||
func composeGrid(widgets []widget.Widget, rects []Rect, th theme.Theme, focus int) string {
|
||||
if len(widgets) == 0 {
|
||||
return ""
|
||||
}
|
||||
var rows []string
|
||||
i := 0
|
||||
for i < len(rects) {
|
||||
y := rects[i].Y
|
||||
var cols []string
|
||||
for i < len(rects) && rects[i].Y == y {
|
||||
cols = append(cols, safeRender(widgets[i], rects[i].W, rects[i].H, th, i == focus))
|
||||
i++
|
||||
}
|
||||
rows = append(rows, lipgloss.JoinHorizontal(lipgloss.Top, cols...))
|
||||
}
|
||||
return strings.Join(rows, "\n")
|
||||
}
|
||||
|
||||
// safeRender renders a widget, but never below its declared MinSize — a cell
|
||||
// squeezed smaller than that (e.g. mid-resize, or in a very narrow terminal)
|
||||
// gets a blank box of the exact requested size instead. Widgets assume at least
|
||||
// MinSize; handing them less underflows their internal width math and panics.
|
||||
func safeRender(wd widget.Widget, width, height int, th theme.Theme, focused bool) string {
|
||||
mw, mh := wd.MinSize()
|
||||
if width < mw || height < mh {
|
||||
return blankCell(width, height)
|
||||
}
|
||||
return wd.Render(width, height, th, focused)
|
||||
}
|
||||
|
||||
// blankCell is a width×height block of spaces (dimensions clamped to zero).
|
||||
func blankCell(width, height int) string {
|
||||
if width < 0 {
|
||||
width = 0
|
||||
}
|
||||
if height < 0 {
|
||||
height = 0
|
||||
}
|
||||
if height == 0 {
|
||||
return ""
|
||||
}
|
||||
line := strings.Repeat(" ", width)
|
||||
lines := make([]string, height)
|
||||
for i := range lines {
|
||||
lines[i] = line
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// formatRange renders a window duration compactly for the header (90s → "90s",
|
||||
// 15m → "15m", 3h → "3h").
|
||||
func formatRange(d time.Duration) string {
|
||||
switch {
|
||||
case d <= 0:
|
||||
return "—"
|
||||
case d < time.Minute:
|
||||
return fmt.Sprintf("%ds", int(d.Seconds()))
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("%dm", int(d.Minutes()))
|
||||
default:
|
||||
if d%time.Hour == 0 {
|
||||
return fmt.Sprintf("%dh", int(d.Hours()))
|
||||
}
|
||||
return fmt.Sprintf("%.1fh", d.Hours())
|
||||
}
|
||||
}
|
||||
|
||||
// coalesce returns the first non-empty string.
|
||||
func coalesce(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -130,3 +130,19 @@ func TestFormatCompact(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestTextHelpersNonPositiveWidth guards against the negative-Repeat panic that
|
||||
// surfaced when a widget was laid out smaller than its chrome during a resize.
|
||||
func TestTextHelpersNonPositiveWidth(t *testing.T) {
|
||||
for _, w := range []int{0, -1, -4, -100} {
|
||||
if got := TruncateVisual("no data", w); got != "" {
|
||||
t.Errorf("TruncateVisual(_, %d) = %q, want empty", w, got)
|
||||
}
|
||||
if got := Center("no data", w); got != "" {
|
||||
t.Errorf("Center(_, %d) = %q, want empty", w, got)
|
||||
}
|
||||
if got := PadOrTruncate("no data", w); got != "" {
|
||||
t.Errorf("PadOrTruncate(_, %d) = %q, want empty", w, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -7,8 +7,13 @@ import (
|
||||
"github.com/charmbracelet/lipgloss"
|
||||
)
|
||||
|
||||
// PadOrTruncate ensures s is exactly targetWidth visual cells, ANSI-aware.
|
||||
// PadOrTruncate ensures s is exactly targetWidth visual cells, ANSI-aware. A
|
||||
// non-positive width yields the empty string (widgets may be laid out smaller
|
||||
// than their chrome during an aggressive resize).
|
||||
func PadOrTruncate(s string, targetWidth int) string {
|
||||
if targetWidth <= 0 {
|
||||
return ""
|
||||
}
|
||||
visualWidth := lipgloss.Width(s)
|
||||
if visualWidth == targetWidth {
|
||||
return s
|
||||
@@ -24,6 +29,9 @@ func PadOrTruncate(s string, targetWidth int) string {
|
||||
// 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 {
|
||||
if targetWidth <= 0 {
|
||||
return ""
|
||||
}
|
||||
visualWidth := lipgloss.Width(s)
|
||||
if visualWidth <= targetWidth {
|
||||
return s
|
||||
@@ -66,6 +74,9 @@ func TruncateVisual(s string, targetWidth int) string {
|
||||
// Center centers s within width visual cells (ANSI-aware). Strings wider than
|
||||
// width are truncated.
|
||||
func Center(s string, width int) string {
|
||||
if width <= 0 {
|
||||
return ""
|
||||
}
|
||||
w := lipgloss.Width(s)
|
||||
if w >= width {
|
||||
return TruncateVisual(s, width)
|
||||
|
||||
Reference in new issue
Block a user