bubbletea/examples/spinner/main.go

80 lines
1.4 KiB
Go
Raw Normal View History

2020-02-10 12:46:12 -05:00
package main
// A simple program demonstrating the spinner component from the Bubbles
// component library.
2020-02-10 12:46:12 -05:00
import (
"fmt"
"os"
2020-02-10 12:46:12 -05:00
"github.com/charmbracelet/bubbles/spinner"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
2020-02-10 12:46:12 -05:00
"github.com/muesli/termenv"
)
2020-11-12 11:30:03 -05:00
var color = termenv.ColorProfile().Color
type errMsg error
2020-02-10 12:46:12 -05:00
type model struct {
spinner spinner.Model
quitting bool
err error
2020-02-10 12:46:12 -05:00
}
func initialModel() model {
s := spinner.NewModel()
2020-11-12 11:30:03 -05:00
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
return model{spinner: s}
2020-02-10 12:46:12 -05:00
}
func (m model) Init() tea.Cmd {
2020-10-31 20:58:24 -04:00
return spinner.Tick
}
2020-02-10 12:46:12 -05:00
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
2020-02-10 12:46:12 -05:00
switch msg := msg.(type) {
case tea.KeyMsg:
2020-02-10 12:46:12 -05:00
switch msg.String() {
2021-05-01 09:28:58 -04:00
case "q", "esc", "ctrl+c":
m.quitting = true
return m, tea.Quit
2020-02-10 12:46:12 -05:00
default:
return m, nil
}
2020-05-04 18:33:17 -04:00
case errMsg:
m.err = msg
return m, nil
2020-02-10 12:46:12 -05:00
default:
var cmd tea.Cmd
2020-10-31 20:58:24 -04:00
m.spinner, cmd = m.spinner.Update(msg)
return m, cmd
2020-02-10 12:46:12 -05:00
}
}
func (m model) View() string {
2020-05-04 18:33:17 -04:00
if m.err != nil {
return m.err.Error()
2020-02-10 12:46:12 -05:00
}
2020-11-12 11:30:03 -05:00
s := termenv.String(m.spinner.View()).Foreground(color("205")).String()
str := fmt.Sprintf("\n\n %s Loading forever...press q to quit\n\n", s)
if m.quitting {
return str + "\n"
}
return str
2020-02-10 12:46:12 -05:00
}
2021-05-01 09:28:58 -04:00
func main() {
p := tea.NewProgram(initialModel())
if err := p.Start(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}