Add the TUI.
A table with one row per URL, a level-colored log pane and a status bar. New alerts flash their row and ring the bell. Keys pause, force checks, open the product page or cart link, and reload the config, which is validated first and applied in place, keeping each URL's timing. Headless mode and the TUI now share one watcher. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f0eda5d4d
commit
a19e6fa711
14 files changed
+1359
-105
No files matched your search
@@ -0,0 +1,121 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// LogLine is one log record, formatted for the log pane.
|
||||
type LogLine struct {
|
||||
Time time.Time
|
||||
Level slog.Level
|
||||
Msg string
|
||||
// Attrs are the record's attributes as key=value pairs.
|
||||
Attrs string
|
||||
}
|
||||
|
||||
// LogHandler is a slog.Handler that feeds the log pane.
|
||||
type LogHandler struct {
|
||||
level slog.Level
|
||||
sink *sink
|
||||
attrs string
|
||||
prefix string
|
||||
}
|
||||
|
||||
// sink is shared by a handler and the handlers derived from it.
|
||||
type sink struct {
|
||||
lines chan LogLine
|
||||
|
||||
mu sync.Mutex
|
||||
out io.Writer // set once the TUI is gone
|
||||
}
|
||||
|
||||
// NewLogHandler returns a handler for records at level or above.
|
||||
func NewLogHandler(level slog.Level) *LogHandler {
|
||||
return &LogHandler{level: level, sink: &sink{lines: make(chan LogLine, 1024)}}
|
||||
}
|
||||
|
||||
// Redirect sends all further lines to w, for after the TUI exits.
|
||||
func (h *LogHandler) Redirect(w io.Writer) {
|
||||
h.sink.mu.Lock()
|
||||
defer h.sink.mu.Unlock()
|
||||
|
||||
h.sink.out = w
|
||||
}
|
||||
|
||||
func (h *LogHandler) Enabled(_ context.Context, l slog.Level) bool { return l >= h.level }
|
||||
|
||||
// Handle never blocks. When the TUI falls 1024 lines behind, new lines are
|
||||
// dropped.
|
||||
func (h *LogHandler) Handle(_ context.Context, r slog.Record) error {
|
||||
var b strings.Builder
|
||||
b.WriteString(h.attrs)
|
||||
r.Attrs(func(a slog.Attr) bool {
|
||||
writeAttr(&b, h.prefix, a)
|
||||
return true
|
||||
})
|
||||
|
||||
l := LogLine{Time: r.Time, Level: r.Level, Msg: r.Message, Attrs: b.String()}
|
||||
|
||||
h.sink.mu.Lock()
|
||||
defer h.sink.mu.Unlock()
|
||||
|
||||
if h.sink.out != nil {
|
||||
_, err := io.WriteString(h.sink.out, l.Time.Format(time.TimeOnly)+" "+l.Level.String()+" "+l.Msg+" "+l.Attrs+"\n")
|
||||
return err
|
||||
}
|
||||
|
||||
select {
|
||||
case h.sink.lines <- l:
|
||||
default:
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *LogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||
var b strings.Builder
|
||||
b.WriteString(h.attrs)
|
||||
for _, a := range attrs { writeAttr(&b, h.prefix, a) }
|
||||
|
||||
c := *h
|
||||
c.attrs = b.String()
|
||||
return &c
|
||||
}
|
||||
|
||||
func (h *LogHandler) WithGroup(name string) slog.Handler {
|
||||
c := *h
|
||||
c.prefix = h.prefix + name + "."
|
||||
return &c
|
||||
}
|
||||
|
||||
func writeAttr(b *strings.Builder, prefix string, a slog.Attr) {
|
||||
v := a.Value.Resolve()
|
||||
|
||||
if v.Kind() == slog.KindGroup {
|
||||
for _, g := range v.Group() { writeAttr(b, prefix+a.Key+".", g) }
|
||||
return
|
||||
}
|
||||
|
||||
if a.Key == "" { return }
|
||||
|
||||
s := v.String()
|
||||
switch v.Kind() {
|
||||
case slog.KindTime:
|
||||
s = v.Time().Local().Format(time.TimeOnly)
|
||||
case slog.KindDuration:
|
||||
s = v.Duration().Round(time.Second).String()
|
||||
default:
|
||||
// Strings, numbers and errors print as they are.
|
||||
}
|
||||
|
||||
if s == "" || strings.ContainsAny(s, " =\"\n") { s = strconv.Quote(s) }
|
||||
|
||||
if b.Len() > 0 { b.WriteByte(' ') }
|
||||
b.WriteString(prefix + a.Key + "=" + s)
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
// Package tui is the interactive view of dibs: a table with one row per
|
||||
// URL, a log pane and a status bar.
|
||||
package tui
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"charm.land/bubbles/v2/viewport"
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"github.com/pkg/browser"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/alert"
|
||||
"git.security-command.org/Overlord/dibs/internal/config"
|
||||
"git.security-command.org/Overlord/dibs/internal/fetch"
|
||||
"git.security-command.org/Overlord/dibs/internal/plugin"
|
||||
"git.security-command.org/Overlord/dibs/internal/watch"
|
||||
)
|
||||
|
||||
const (
|
||||
// tick is how often the table refreshes. It is also the flash rate.
|
||||
tick = 500 * time.Millisecond
|
||||
flashFor = 30 * time.Second
|
||||
noteFor = 10 * time.Second
|
||||
)
|
||||
|
||||
// maxLines is how many lines the log pane keeps.
|
||||
const maxLines = 2000
|
||||
|
||||
// Controller is the running watcher.
|
||||
type Controller interface {
|
||||
Statuses() []watch.Status
|
||||
Pause(item string, paused bool) bool
|
||||
PauseAll(paused bool)
|
||||
CheckNow(item string) bool
|
||||
Reload() ([]string, error)
|
||||
}
|
||||
|
||||
// CheckMsg is one finished check and what the alert engine made of it.
|
||||
type CheckMsg struct {
|
||||
Result watch.Result
|
||||
Decision alert.Decision
|
||||
PriceErr error
|
||||
}
|
||||
|
||||
type (
|
||||
tickMsg time.Time
|
||||
logMsg LogLine
|
||||
reloadMsg struct {
|
||||
summary []string
|
||||
err error
|
||||
}
|
||||
openMsg struct {
|
||||
url string
|
||||
err error
|
||||
}
|
||||
)
|
||||
|
||||
// Status texts, as the STATUS column shows them.
|
||||
const (
|
||||
statusWatching = "watching"
|
||||
statusAvailable = "AVAILABLE"
|
||||
statusBlocked = "blocked"
|
||||
statusError = "error"
|
||||
statusPaused = "paused"
|
||||
)
|
||||
|
||||
// result is what the last check of a URL found.
|
||||
type result struct {
|
||||
status string
|
||||
price string
|
||||
seller string
|
||||
cartLink string
|
||||
flash time.Time // the row flashes until then
|
||||
}
|
||||
|
||||
type Model struct {
|
||||
ctl Controller
|
||||
path string
|
||||
lines <-chan LogLine
|
||||
|
||||
now time.Time
|
||||
rows []watch.Status
|
||||
results map[string]*result // by configured URL
|
||||
cursor int
|
||||
offset int // the first table row on screen
|
||||
|
||||
logs []LogLine
|
||||
log viewport.Model
|
||||
logFocus bool
|
||||
|
||||
width, height int
|
||||
|
||||
note string
|
||||
noteError bool
|
||||
noteTime time.Time
|
||||
reloading bool
|
||||
}
|
||||
|
||||
// New returns the TUI for ctl. path is the config file, and logs is the
|
||||
// handler the watcher logs to.
|
||||
func New(ctl Controller, path string, logs *LogHandler) *Model {
|
||||
// The browser's own output would draw over the TUI.
|
||||
browser.Stdout, browser.Stderr = io.Discard, io.Discard
|
||||
|
||||
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(path, home+string(os.PathSeparator)) { path = "~" + path[len(home):] }
|
||||
|
||||
m := &Model{
|
||||
ctl: ctl,
|
||||
path: path,
|
||||
lines: logs.sink.lines,
|
||||
now: time.Now(),
|
||||
results: map[string]*result{},
|
||||
log: viewport.New(),
|
||||
}
|
||||
m.rows = ctl.Statuses()
|
||||
|
||||
return m
|
||||
}
|
||||
|
||||
func (m *Model) Init() tea.Cmd {
|
||||
return tea.Batch(m.tick(), m.nextLine())
|
||||
}
|
||||
|
||||
func (m *Model) tick() tea.Cmd {
|
||||
return tea.Tick(tick, func(t time.Time) tea.Msg { return tickMsg(t) })
|
||||
}
|
||||
|
||||
func (m *Model) nextLine() tea.Cmd {
|
||||
return func() tea.Msg { return logMsg(<-m.lines) }
|
||||
}
|
||||
|
||||
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.layout()
|
||||
case tickMsg:
|
||||
m.now = time.Time(msg)
|
||||
m.rows = m.ctl.Statuses()
|
||||
m.clampCursor()
|
||||
return m, m.tick()
|
||||
case logMsg:
|
||||
m.addLog(LogLine(msg))
|
||||
return m, m.nextLine()
|
||||
case CheckMsg:
|
||||
return m, m.checked(msg)
|
||||
case reloadMsg:
|
||||
m.reloading = false
|
||||
m.rows = m.ctl.Statuses()
|
||||
m.clampCursor()
|
||||
if msg.err != nil { m.setNote(reloadError(msg.err), true) } else { m.setNote(reloadNote(msg.summary), false) }
|
||||
case openMsg:
|
||||
if msg.err != nil { m.setNote("cannot open the browser: "+msg.err.Error(), true) } else { m.setNote("opened "+msg.url, false) }
|
||||
case tea.KeyPressMsg:
|
||||
return m, m.key(msg)
|
||||
}
|
||||
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// checked records a check. A new alert flashes its row and rings the bell.
|
||||
func (m *Model) checked(c CheckMsg) tea.Cmd {
|
||||
r := m.results[c.Result.URL]
|
||||
if r == nil {
|
||||
r = &result{}
|
||||
m.results[c.Result.URL] = r
|
||||
}
|
||||
|
||||
r.status = statusOf(c)
|
||||
|
||||
if rep := c.Result.Report; rep != nil {
|
||||
r.price, r.seller = "", ""
|
||||
if res := rep.Result; res != nil {
|
||||
if res.Price != nil { r.price = alert.Money(*res.Price, res.Currency) }
|
||||
r.seller = sellerText(res.Seller)
|
||||
}
|
||||
|
||||
if rep.CartLink != "" { r.cartLink = rep.CartLink }
|
||||
}
|
||||
|
||||
m.rows = m.ctl.Statuses()
|
||||
|
||||
if c.Decision.Alert == nil { return nil }
|
||||
|
||||
r.flash = m.now.Add(flashFor)
|
||||
return tea.Raw("\a")
|
||||
}
|
||||
|
||||
func statusOf(c CheckMsg) string {
|
||||
rep := c.Result.Report
|
||||
|
||||
switch {
|
||||
case rep == nil:
|
||||
return statusError
|
||||
case rep.Verdict == fetch.Challenge.String() || rep.Verdict == fetch.Blocked.String():
|
||||
return statusBlocked
|
||||
case c.Result.Err != nil || rep.Verdict == fetch.HTTPError.String():
|
||||
return statusError
|
||||
case c.Decision.Qualifies:
|
||||
return statusAvailable
|
||||
default:
|
||||
return statusWatching
|
||||
}
|
||||
}
|
||||
|
||||
func sellerText(seller string) string {
|
||||
switch seller {
|
||||
case plugin.SellerFirstParty:
|
||||
return "first party"
|
||||
case plugin.SellerFulfilled:
|
||||
return "fulfilled"
|
||||
case plugin.SellerThirdParty:
|
||||
return "third party"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) key(msg tea.KeyPressMsg) tea.Cmd {
|
||||
k := msg.String()
|
||||
|
||||
switch k {
|
||||
case "q", "ctrl+c":
|
||||
return tea.Quit
|
||||
case "l", "tab":
|
||||
m.logFocus = !m.logFocus
|
||||
return nil
|
||||
case "r":
|
||||
return m.reload()
|
||||
}
|
||||
|
||||
if m.logFocus {
|
||||
if k == "esc" {
|
||||
m.logFocus = false
|
||||
return nil
|
||||
}
|
||||
|
||||
var cmd tea.Cmd
|
||||
m.log, cmd = m.log.Update(msg)
|
||||
return cmd
|
||||
}
|
||||
|
||||
switch k {
|
||||
case "up", "k":
|
||||
m.cursor--
|
||||
case "down", "j":
|
||||
m.cursor++
|
||||
case "home", "g":
|
||||
m.cursor = 0
|
||||
case "end", "G":
|
||||
m.cursor = len(m.rows) - 1
|
||||
case "P":
|
||||
m.pauseAll()
|
||||
default:
|
||||
return m.rowKey(k)
|
||||
}
|
||||
|
||||
m.clampCursor()
|
||||
return nil
|
||||
}
|
||||
|
||||
// rowKey handles the keys that act on the selected row.
|
||||
func (m *Model) rowKey(k string) tea.Cmd {
|
||||
if m.cursor >= len(m.rows) { return nil }
|
||||
|
||||
row := m.rows[m.cursor]
|
||||
|
||||
switch k {
|
||||
case "p":
|
||||
m.ctl.Pause(row.Item, !row.Paused)
|
||||
if row.Paused { m.setNote("resumed "+row.Item, false) } else { m.setNote("paused "+row.Item, false) }
|
||||
m.rows = m.ctl.Statuses()
|
||||
case "c":
|
||||
m.ctl.CheckNow(row.Item)
|
||||
m.setNote("checking "+row.Item+" as soon as the rate limits allow", false)
|
||||
m.rows = m.ctl.Statuses()
|
||||
case "o":
|
||||
return open(row.FetchURL)
|
||||
case "enter":
|
||||
if r := m.results[row.URL]; r != nil && r.cartLink != "" { return open(r.cartLink) }
|
||||
|
||||
m.setNote("no cart link yet, opening the product page", false)
|
||||
return open(row.FetchURL)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// pauseAll pauses every URL, or resumes them all if all are paused.
|
||||
func (m *Model) pauseAll() {
|
||||
pause := false
|
||||
for _, row := range m.rows {
|
||||
if !row.Paused { pause = true }
|
||||
}
|
||||
|
||||
m.ctl.PauseAll(pause)
|
||||
m.rows = m.ctl.Statuses()
|
||||
|
||||
if pause { m.setNote("paused everything", false) } else { m.setNote("resumed everything", false) }
|
||||
}
|
||||
|
||||
func (m *Model) reload() tea.Cmd {
|
||||
if m.reloading { return nil }
|
||||
|
||||
m.reloading = true
|
||||
m.setNote("reloading "+m.path, false)
|
||||
|
||||
return func() tea.Msg {
|
||||
summary, err := m.ctl.Reload()
|
||||
return reloadMsg{summary: summary, err: err}
|
||||
}
|
||||
}
|
||||
|
||||
func reloadNote(summary []string) string {
|
||||
if len(summary) == 1 { return "reloaded: " + summary[0] }
|
||||
|
||||
return fmt.Sprintf("reloaded: %d changes (see log)", len(summary))
|
||||
}
|
||||
|
||||
// reloadError shows the first problem in the config. The log has them all.
|
||||
func reloadError(err error) string {
|
||||
var errs config.Errors
|
||||
if errors.As(err, &errs) && len(errs) > 0 {
|
||||
msg := "reload failed, config unchanged: line " + errs[0].Brief()
|
||||
if len(errs) > 1 { msg += fmt.Sprintf(" (+%d more)", len(errs)-1) }
|
||||
|
||||
return msg
|
||||
}
|
||||
|
||||
return "reload failed, config unchanged: " + err.Error()
|
||||
}
|
||||
|
||||
func open(url string) tea.Cmd {
|
||||
return func() tea.Msg { return openMsg{url: url, err: browser.OpenURL(url)} }
|
||||
}
|
||||
|
||||
func (m *Model) setNote(note string, isError bool) {
|
||||
m.note, m.noteError, m.noteTime = note, isError, time.Now()
|
||||
}
|
||||
|
||||
func (m *Model) addLog(l LogLine) {
|
||||
follow := m.log.AtBottom()
|
||||
|
||||
m.logs = append(m.logs, l)
|
||||
if len(m.logs) > maxLines { m.logs = m.logs[len(m.logs)-maxLines:] }
|
||||
|
||||
m.log.SetContentLines(m.logLines())
|
||||
if follow { m.log.GotoBottom() }
|
||||
}
|
||||
|
||||
func (m *Model) clampCursor() {
|
||||
m.cursor = max(0, min(m.cursor, len(m.rows)-1))
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
package tui
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
tea "charm.land/bubbletea/v2"
|
||||
"charm.land/lipgloss/v2"
|
||||
"github.com/charmbracelet/x/ansi"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
|
||||
"git.security-command.org/Overlord/dibs/internal/watch"
|
||||
)
|
||||
|
||||
// The colors are ANSI palette entries, so they follow the terminal's theme.
|
||||
var (
|
||||
bold = lipgloss.NewStyle().Bold(true)
|
||||
faint = lipgloss.NewStyle().Faint(true)
|
||||
green = lipgloss.NewStyle().Foreground(lipgloss.Color("10")).Bold(true)
|
||||
yellow = lipgloss.NewStyle().Foreground(lipgloss.Color("11"))
|
||||
red = lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
|
||||
blue = lipgloss.NewStyle().Foreground(lipgloss.Color("12"))
|
||||
selected = lipgloss.NewStyle().Reverse(true)
|
||||
flashing = lipgloss.NewStyle().Background(lipgloss.Color("10")).Foreground(lipgloss.Color("0")).Bold(true)
|
||||
)
|
||||
|
||||
// fixedLines are the lines around the table body and the log: the header,
|
||||
// the column titles, the log title, the status bar and the key help.
|
||||
const fixedLines = 5
|
||||
|
||||
var columns = []struct {
|
||||
title string
|
||||
min, max int
|
||||
} {
|
||||
{"ITEM", 8, 32},
|
||||
{"SHOP", 4, 12},
|
||||
{"TLD", 3, 6},
|
||||
{"STATUS", 9, 9},
|
||||
{"PRICE", 5, 16},
|
||||
{"SELLER", 6, 11},
|
||||
{"LAST", 4, 9},
|
||||
{"NEXT", 4, 10},
|
||||
}
|
||||
|
||||
// layout sizes the table and the log pane to the window.
|
||||
func (m *Model) layout() {
|
||||
avail := max(m.height-fixedLines, 2)
|
||||
body := min(len(m.rows), max(3, avail*55/100), avail-1)
|
||||
body = max(body, 1)
|
||||
|
||||
m.log.SetWidth(m.width)
|
||||
m.log.SetHeight(max(avail-body, 1))
|
||||
|
||||
if m.cursor < m.offset { m.offset = m.cursor }
|
||||
if m.cursor >= m.offset+body { m.offset = m.cursor - body + 1 }
|
||||
m.offset = max(0, min(m.offset, len(m.rows)-body))
|
||||
}
|
||||
|
||||
func (m *Model) bodyHeight() int {
|
||||
return max(m.height-fixedLines, 2) - m.log.Height()
|
||||
}
|
||||
|
||||
func (m *Model) View() tea.View {
|
||||
v := tea.NewView("")
|
||||
v.AltScreen = true
|
||||
v.WindowTitle = "dibs"
|
||||
|
||||
if n := m.count(statusAvailable); n > 0 { v.WindowTitle = fmt.Sprintf("dibs · %d AVAILABLE", n) }
|
||||
|
||||
if m.width == 0 { return v }
|
||||
|
||||
m.layout()
|
||||
|
||||
var b strings.Builder
|
||||
b.WriteString(fit(bold.Render("dibs")+" "+faint.Render(m.path), m.width) + "\n")
|
||||
b.WriteString(m.table())
|
||||
b.WriteString(m.logTitle() + "\n")
|
||||
b.WriteString(m.log.View() + "\n")
|
||||
b.WriteString(m.statusBar() + "\n")
|
||||
b.WriteString(fit(faint.Render(m.help()), m.width))
|
||||
|
||||
v.SetContent(b.String())
|
||||
return v
|
||||
}
|
||||
|
||||
func (m *Model) table() string {
|
||||
cells := make([][]string, len(m.rows))
|
||||
widths := make([]int, len(columns))
|
||||
|
||||
for i, c := range columns { widths[i] = max(c.min, len(c.title)) }
|
||||
|
||||
for i, row := range m.rows {
|
||||
cells[i] = m.cells(row)
|
||||
for j, c := range cells[i] { widths[j] = max(widths[j], min(ansi.StringWidth(c), columns[j].max)) }
|
||||
}
|
||||
|
||||
// The ITEM column gives way first when the window is narrow.
|
||||
total := 2
|
||||
for _, w := range widths { total += w + 2 }
|
||||
if over := total - m.width; over > 0 { widths[0] = max(columns[0].min, widths[0]-over) }
|
||||
|
||||
var b strings.Builder
|
||||
|
||||
titles := make([]string, len(columns))
|
||||
for i, c := range columns { titles[i] = c.title }
|
||||
b.WriteString(fit(faint.Render(" "+joinCells(titles, widths)), m.width) + "\n")
|
||||
|
||||
body := m.bodyHeight()
|
||||
for i := m.offset; i < m.offset+body; i++ {
|
||||
if i >= len(m.rows) {
|
||||
b.WriteString("\n")
|
||||
continue
|
||||
}
|
||||
|
||||
b.WriteString(m.rowLine(i, cells[i], widths) + "\n")
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (m *Model) rowLine(i int, cells []string, widths []int) string {
|
||||
r := m.results[m.rows[i].URL]
|
||||
|
||||
switch {
|
||||
case r != nil && m.now.Before(r.flash) && m.now.UnixMilli()/tick.Milliseconds()%2 == 0:
|
||||
return flashing.Render(padRight(" "+joinCells(cells, widths), m.width))
|
||||
case i == m.cursor && !m.logFocus:
|
||||
return selected.Render(padRight("> "+joinCells(cells, widths), m.width))
|
||||
}
|
||||
|
||||
// Only the status cell is colored.
|
||||
status := statusStyle(cells[3]).Render(padRight(cells[3], widths[3]))
|
||||
line := " " + joinCells(cells[:3], widths[:3]) + " " + status + " " + joinCells(cells[4:], widths[4:])
|
||||
|
||||
return fit(line, m.width)
|
||||
}
|
||||
|
||||
func (m *Model) cells(row watch.Status) []string {
|
||||
r := m.results[row.URL]
|
||||
if r == nil { r = &result{status: statusWatching} }
|
||||
|
||||
status := r.status
|
||||
if row.Paused { status = statusPaused }
|
||||
|
||||
return []string{row.Item, row.Shop, tld(row.Host), status, orDash(r.price), orDash(r.seller), m.ago(row.Last), m.until(row)}
|
||||
}
|
||||
|
||||
func statusStyle(status string) lipgloss.Style {
|
||||
switch status {
|
||||
case statusAvailable:
|
||||
return green
|
||||
case statusBlocked:
|
||||
return yellow
|
||||
case statusError:
|
||||
return red
|
||||
case statusPaused:
|
||||
return faint
|
||||
default:
|
||||
return lipgloss.NewStyle()
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Model) logTitle() string {
|
||||
title := "── log "
|
||||
if m.logFocus { return fit(bold.Render(title+"(scrolling) "+strings.Repeat("─", m.width)), m.width) }
|
||||
|
||||
return fit(faint.Render(title+strings.Repeat("─", m.width)), m.width)
|
||||
}
|
||||
|
||||
func (m *Model) logLines() []string {
|
||||
out := make([]string, len(m.logs))
|
||||
|
||||
for i, l := range m.logs {
|
||||
level := fmt.Sprintf("%-5s", l.Level)
|
||||
switch {
|
||||
case l.Level >= slog.LevelError:
|
||||
level = red.Render(level)
|
||||
case l.Level >= slog.LevelWarn:
|
||||
level = yellow.Render(level)
|
||||
case l.Level >= slog.LevelInfo:
|
||||
level = blue.Render(level)
|
||||
default:
|
||||
level = faint.Render(level)
|
||||
}
|
||||
|
||||
msg := l.Msg
|
||||
if msg == "ALERT" { msg = green.Render(msg) }
|
||||
|
||||
out[i] = faint.Render(l.Time.Format(time.TimeOnly)) + " " + level + " " + msg + " " + faint.Render(l.Attrs)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (m *Model) statusBar() string {
|
||||
parts := []string{fmt.Sprintf("%d URLs", len(m.rows))}
|
||||
|
||||
for _, s := range []struct {
|
||||
status string
|
||||
style lipgloss.Style
|
||||
} {
|
||||
{statusAvailable, green},
|
||||
{statusBlocked, yellow},
|
||||
{statusError, red},
|
||||
{statusPaused, faint},
|
||||
} {
|
||||
if n := m.count(s.status); n > 0 { parts = append(parts, s.style.Render(fmt.Sprintf("%d %s", n, s.status))) }
|
||||
}
|
||||
|
||||
left := strings.Join(parts, faint.Render(" · "))
|
||||
|
||||
note := ""
|
||||
if m.note != "" && time.Since(m.noteTime) < noteFor {
|
||||
note = m.note
|
||||
if m.noteError { note = red.Render(note) }
|
||||
}
|
||||
|
||||
gap := m.width - ansi.StringWidth(left) - ansi.StringWidth(note)
|
||||
if gap < 2 { return fit(left+" "+note, m.width) }
|
||||
|
||||
return left + strings.Repeat(" ", gap) + note
|
||||
}
|
||||
|
||||
func (m *Model) help() string {
|
||||
if m.logFocus { return "↑↓ pgup pgdn scroll · l/esc back to the table · r reload · q quit" }
|
||||
|
||||
return "↑↓ select · p pause · P pause all · c check now · o open page · enter cart · l log · r reload · q quit"
|
||||
}
|
||||
|
||||
// count is the number of rows showing status.
|
||||
func (m *Model) count(status string) int {
|
||||
n := 0
|
||||
for _, row := range m.rows {
|
||||
if m.cells(row)[3] == status { n++ }
|
||||
}
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
func (m *Model) ago(t time.Time) string {
|
||||
if t.IsZero() { return "—" }
|
||||
|
||||
return short(m.now.Sub(t)) + " ago"
|
||||
}
|
||||
|
||||
func (m *Model) until(row watch.Status) string {
|
||||
switch {
|
||||
case row.Paused:
|
||||
return "—"
|
||||
case row.Checking:
|
||||
return "checking"
|
||||
}
|
||||
|
||||
d := row.Next.Sub(m.now)
|
||||
if d <= 0 { return "due" }
|
||||
|
||||
return "in " + short(d)
|
||||
}
|
||||
|
||||
// short formats d as "45s", "3m05s" or "1h20m".
|
||||
func short(d time.Duration) string {
|
||||
d = max(d, 0).Round(time.Second)
|
||||
|
||||
switch {
|
||||
case d < time.Minute:
|
||||
return fmt.Sprintf("%ds", int(d.Seconds()))
|
||||
case d < time.Hour:
|
||||
return fmt.Sprintf("%dm%02ds", int(d.Minutes()), int(d.Seconds())%60)
|
||||
default:
|
||||
return fmt.Sprintf("%dh%02dm", int(d.Hours()), int(d.Minutes())%60)
|
||||
}
|
||||
}
|
||||
|
||||
func tld(host string) string {
|
||||
suffix, _ := publicsuffix.PublicSuffix(host)
|
||||
return suffix
|
||||
}
|
||||
|
||||
func orDash(s string) string {
|
||||
if s == "" { return "—" }
|
||||
|
||||
return s
|
||||
}
|
||||
|
||||
func joinCells(cells []string, widths []int) string {
|
||||
var b strings.Builder
|
||||
for i, c := range cells {
|
||||
if i > 0 { b.WriteString(" ") }
|
||||
b.WriteString(padRight(ansi.Truncate(c, widths[i], "…"), widths[i]))
|
||||
}
|
||||
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func padRight(s string, w int) string {
|
||||
return s + strings.Repeat(" ", max(0, w-ansi.StringWidth(s)))
|
||||
}
|
||||
|
||||
// fit cuts s to the window width.
|
||||
func fit(s string, w int) string {
|
||||
return ansi.Truncate(s, w, "")
|
||||
}
|
||||
Reference in new issue
Block a user