Skip to content

Instantly share code, notes, and snippets.

@remogatto
Last active January 12, 2024 21:19
Show Gist options
  • Save remogatto/22a4a25e86e07823d20b50b0f5367632 to your computer and use it in GitHub Desktop.
Save remogatto/22a4a25e86e07823d20b50b0f5367632 to your computer and use it in GitHub Desktop.
Basic BubbleTea lipgloss-styled application
package main
import (
"fmt"
"os"
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/bubbles/textinput"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
var (
textInputStyle = lipgloss.NewStyle().BorderStyle(lipgloss.RoundedBorder())
)
type keyBindings struct {
Quit key.Binding
}
// ShortHelp returns keybindings to be shown in the mini help view. It's part
// of the key.Map interface.
func (k keyBindings) ShortHelp() []key.Binding {
return []key.Binding{k.Quit}
}
// FullHelp returns keybindings for the expanded help view. It's part of the
// key.Map interface.
func (k keyBindings) FullHelp() [][]key.Binding {
return [][]key.Binding{
{k.Quit},
}
}
func newBindings() keyBindings {
return keyBindings{
Quit: key.NewBinding(key.WithKeys("ctrl+c"), key.WithHelp("ctrl+c", "Quit app")),
}
}
type model struct {
input textinput.Model
help help.Model
b keyBindings
wSize tea.WindowSizeMsg
}
func initialModel() model {
ti := textinput.New()
ti.Focus()
return model{
input: ti,
help: help.New(),
b: newBindings(),
}
}
func (m model) Init() tea.Cmd {
return textinput.Blink
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.wSize = msg
case tea.KeyMsg:
switch {
case key.Matches(msg, m.b.Quit):
return m, tea.Quit
}
}
m.input, cmd = m.input.Update(msg)
return m, cmd
}
func (m model) View() string {
textInputStyle = textInputStyle.Width(m.wSize.Width - textInputStyle.GetHorizontalFrameSize() - len(m.input.Prompt))
return fmt.Sprintf("%s\n%s", textInputStyle.Render(m.input.View()), m.help.View(m.b))
}
func main() {
if _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run(); err != nil {
fmt.Println("Error running program:", err)
os.Exit(1)
}
}
@remogatto
Copy link
Author

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment