tui.go
This file
Path
examples/progress-download/tui.go
85 lines · 1.6 KiB · Go
Last changed by
Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97
History of this fileTake it
1package main23import (4 "strings"5 "time"67 "charm.land/bubbles/v2/progress"8 tea "charm.land/bubbletea/v2"9 "charm.land/lipgloss/v2"10)1112var helpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#626262")).Render1314const (15 padding = 216 maxWidth = 8017)1819type progressMsg float642021type progressErrMsg struct{ err error }2223func finalPause() tea.Cmd {24 return tea.Tick(time.Millisecond*750, func(_ time.Time) tea.Msg {25 return nil26 })27}2829type model struct {30 pw *progressWriter31 progress progress.Model32 err error33}3435func (m model) Init() tea.Cmd {36 return nil37}3839func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {40 switch msg := msg.(type) {41 case tea.KeyPressMsg:42 return m, tea.Quit4344 case tea.WindowSizeMsg:45 m.progress.SetWidth(msg.Width - padding*2 - 4)46 if m.progress.Width() > maxWidth {47 m.progress.SetWidth(maxWidth)48 }49 return m, nil5051 case progressErrMsg:52 m.err = msg.err53 return m, tea.Quit5455 case progressMsg:56 var cmds []tea.Cmd5758 if msg >= 1.0 {59 cmds = append(cmds, tea.Sequence(finalPause(), tea.Quit))60 }6162 cmds = append(cmds, m.progress.SetPercent(float64(msg)))63 return m, tea.Batch(cmds...)6465 // FrameMsg is sent when the progress bar wants to animate itself66 case progress.FrameMsg:67 var cmd tea.Cmd68 m.progress, cmd = m.progress.Update(msg)69 return m, cmd7071 default:72 return m, nil73 }74}7576func (m model) View() tea.View {77 if m.err != nil {78 return tea.NewView("Error downloading: " + m.err.Error() + "\n")79 }8081 pad := strings.Repeat(" ", padding)82 return tea.NewView("\n" +83 pad + m.progress.View() + "\n\n" +84 pad + helpStyle("Press any key to quit"))85}