Skip to content
Myr

main.go

This file

Path

examples/progress-animated/main.go

93 lines · 1.9 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

1package main23// A simple example that shows how to render an animated progress bar. In this4// example we bump the progress by 25% every two seconds, animating our5// progress bar to its new target state.6//7// It's also possible to render a progress bar in a more static fashion without8// transitions. For details on that approach see the progress-static example.910import (11	"fmt"12	"os"13	"strings"14	"time"1516	"charm.land/bubbles/v2/progress"17	tea "charm.land/bubbletea/v2"18	"charm.land/lipgloss/v2"19)2021const (22	padding  = 223	maxWidth = 8024)2526var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render2728func main() {29	m := model{30		progress: progress.New(progress.WithDefaultBlend()),31	}3233	if _, err := tea.NewProgram(m).Run(); err != nil {34		fmt.Println("Oh no!", err)35		os.Exit(1)36	}37}3839type tickMsg time.Time4041type model struct {42	progress progress.Model43}4445func (m model) Init() tea.Cmd {46	return tickCmd()47}4849func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {50	switch msg := msg.(type) {51	case tea.KeyPressMsg:52		return m, tea.Quit5354	case tea.WindowSizeMsg:55		m.progress.SetWidth(msg.Width - padding*2 - 4)56		if m.progress.Width() > maxWidth {57			m.progress.SetWidth(maxWidth)58		}59		return m, nil6061	case tickMsg:62		if m.progress.Percent() == 1.0 {63			return m, tea.Quit64		}6566		// Note that you can also use progress.Model.SetPercent to set the67		// percentage value explicitly, too.68		cmd := m.progress.IncrPercent(0.25)69		return m, tea.Batch(tickCmd(), cmd)7071	// FrameMsg is sent when the progress bar wants to animate itself72	case progress.FrameMsg:73		var cmd tea.Cmd74		m.progress, cmd = m.progress.Update(msg)75		return m, cmd7677	default:78		return m, nil79	}80}8182func (m model) View() tea.View {83	pad := strings.Repeat(" ", padding)84	return tea.NewView("\n" +85		pad + m.progress.View() + "\n\n" +86		pad + helpStyle("Press any key to quit"))87}8889func tickCmd() tea.Cmd {90	return tea.Tick(time.Second*1, func(t time.Time) tea.Msg {91		return tickMsg(t)92	})93}