main.go
This file
Path
examples/progress-static/main.go
97 lines · 2.1 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23// A simple example that shows how to render a progress bar in a "pure"4// fashion. In this example we bump the progress by 25% every second,5// maintaining the progress state on our top level model using the progress bar6// model's ViewAs method only for rendering.7//8// The signature for ViewAs is:9//10// func (m Model) ViewAs(percent float64) string11//12// So it takes a float between 0 and 1, and renders the progress bar13// accordingly. When using the progress bar in this "pure" fashion and there's14// no need to call an Update method.15//16// The progress bar is also able to animate itself, however. For details see17// the progress-animated example.1819import (20 "fmt"21 "os"22 "strings"23 "time"2425 "charm.land/bubbles/v2/progress"26 tea "charm.land/bubbletea/v2"27 "charm.land/lipgloss/v2"28)2930const (31 padding = 232 maxWidth = 8033)3435var (36 helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render37 yellow = lipgloss.Color("#FDFF8C")38 pink = lipgloss.Color("#FF7CCB")39)4041func main() {42 prog := progress.New(progress.WithScaled(true), progress.WithColors(pink, yellow))4344 if _, err := tea.NewProgram(model{progress: prog}).Run(); err != nil {45 fmt.Println("Oh no!", err)46 os.Exit(1)47 }48}4950type tickMsg time.Time5152type model struct {53 percent float6454 progress progress.Model55}5657func (m model) Init() tea.Cmd {58 return tickCmd()59}6061func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {62 switch msg := msg.(type) {63 case tea.KeyPressMsg:64 return m, tea.Quit6566 case tea.WindowSizeMsg:67 m.progress.SetWidth(msg.Width - padding*2 - 4)68 if m.progress.Width() > maxWidth {69 m.progress.SetWidth(maxWidth)70 }71 return m, nil7273 case tickMsg:74 m.percent += 0.2575 if m.percent > 1.0 {76 m.percent = 1.077 return m, tea.Quit78 }79 return m, tickCmd()8081 default:82 return m, nil83 }84}8586func (m model) View() tea.View {87 pad := strings.Repeat(" ", padding)88 return tea.NewView("\n" +89 pad + m.progress.ViewAs(m.percent) + "\n\n" +90 pad + helpStyle("Press any key to quit"))91}9293func tickCmd() tea.Cmd {94 return tea.Tick(time.Second, func(t time.Time) tea.Msg {95 return tickMsg(t)96 })97}