From 9239e54eebfb284499fba0165e73a291f9336c77 Mon Sep 17 00:00:00 2001 From: Muhammad Nauman Raza Date: Sat, 30 Mar 2024 12:45:22 +0000 Subject: [PATCH] feat: nicer help --- go.mod | 1 + go.sum | 2 ++ main.go | 33 +++++++++++++++++++++++++++++---- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 90c124f..4792259 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/devraza/sage go 1.21.7 require ( + github.com/charmbracelet/bubbles v0.18.0 github.com/charmbracelet/bubbletea v0.25.0 github.com/charmbracelet/lipgloss v0.10.0 github.com/prometheus-community/pro-bing v0.4.0 diff --git a/go.sum b/go.sum index e720038..803f247 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ 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/bubbles v0.18.0 h1:PYv1A036luoBGroX6VWjQIE9Syf2Wby2oOl/39KLfy0= +github.com/charmbracelet/bubbles v0.18.0/go.mod h1:08qhZhtIwzgrtBjAcJnij1t1H0ZRjwHyGsy6AL11PSw= github.com/charmbracelet/bubbletea v0.25.0 h1:bAfwk7jRz7FKFl9RzlIULPkStffg5k6pNt5dywy4TcM= github.com/charmbracelet/bubbletea v0.25.0/go.mod h1:EN3QDR1T5ZdWmdfDzYcqOCAps45+QIJbLOBxmVNWNNg= github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s= diff --git a/main.go b/main.go index cfe5f48..75ea39f 100644 --- a/main.go +++ b/main.go @@ -6,6 +6,8 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/bubbles/key" + "github.com/charmbracelet/bubbles/help" "github.com/prometheus-community/pro-bing" ) @@ -14,12 +16,34 @@ var ( checkMark = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).SetString("✓") ) +type keyMap struct { + Quit key.Binding +} +func (k keyMap) ShortHelp() []key.Binding { + return []key.Binding{k.Quit} +} +func (k keyMap) FullHelp() [][]key.Binding { + return [][]key.Binding{ + {k.Quit}, + } +} +var keys = keyMap{ + Quit: key.NewBinding( + key.WithKeys("q", "esc", "ctrl+c"), + key.WithHelp("q", "quit"), + ), +} + type model struct { + keys keyMap + help help.Model addresses []string } func initialModel() model { return model{ + keys: keys, + help: help.New(), addresses: []string{"100.64.0.1", "100.64.0.2"}, } } @@ -31,8 +55,8 @@ func (m model) Init() tea.Cmd { func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch msg := msg.(type) { case tea.KeyMsg: - switch msg.String() { - case "ctrl+c", "q": + switch { + case key.Matches(msg, m.keys.Quit): return m, tea.Quit } } @@ -49,8 +73,9 @@ func (m model) View() string { s += fmt.Sprintf("%s %s\n", checkMark, address) } } - s += "\nPress q to quit.\n" - return s + + helpView := m.help.View(m.keys) + return s + "\n" + helpView } func main() {