Skip to content
Myr

main.go

This file

Path

examples/views/main.go

275 lines · 6.5 KiB · Go

Last changed by

chore(examples): views: change KeyMsg to KeyPressMsg in Update function (#1611)jjpintobefore adoption2e0dc62

History of this file

Take it

1package main23// An example demonstrating an application with multiple views.4//5// Note that this example was produced before the Bubbles progress component6// was available (github.com/charmbracelet/bubbles/progress) and thus, we're7// implementing a progress bar from scratch here.89import (10	"fmt"11	"math"12	"strconv"13	"strings"14	"time"1516	tea "charm.land/bubbletea/v2"17	"charm.land/lipgloss/v2"18	"github.com/fogleman/ease"19	"github.com/lucasb-eyer/go-colorful"20)2122const (23	progressBarWidth  = 7124	progressFullChar  = "█"25	progressEmptyChar = "░"26	dotChar           = " • "27)2829// General stuff for styling the view30var (31	keywordStyle  = lipgloss.NewStyle().Foreground(lipgloss.Color("211"))32	subtleStyle   = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))33	ticksStyle    = lipgloss.NewStyle().Foreground(lipgloss.Color("79"))34	checkboxStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("212"))35	progressEmpty = subtleStyle.Render(progressEmptyChar)36	dotStyle      = lipgloss.NewStyle().Foreground(lipgloss.Color("236")).Render(dotChar)37	mainStyle     = lipgloss.NewStyle().MarginLeft(2)3839	// Gradient colors we'll use for the progress bar40	ramp = makeRampStyles("#B14FFF", "#00FFA3", progressBarWidth)41)4243func main() {44	initialModel := model{0, false, 10, 0, 0, false, false}45	p := tea.NewProgram(initialModel)46	if _, err := p.Run(); err != nil {47		fmt.Println("could not start program:", err)48	}49}5051type (52	tickMsg  struct{}53	frameMsg struct{}54)5556func tick() tea.Cmd {57	return tea.Tick(time.Second, func(time.Time) tea.Msg {58		return tickMsg{}59	})60}6162func frame() tea.Cmd {63	return tea.Tick(time.Second/60, func(time.Time) tea.Msg {64		return frameMsg{}65	})66}6768type model struct {69	Choice   int70	Chosen   bool71	Ticks    int72	Frames   int73	Progress float6474	Loaded   bool75	Quitting bool76}7778func (m model) Init() tea.Cmd {79	return tick()80}8182// Main update function.83func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {84	// Make sure these keys always quit85	if msg, ok := msg.(tea.KeyPressMsg); ok {86		k := msg.String()87		if k == "q" || k == "esc" || k == "ctrl+c" {88			m.Quitting = true89			return m, tea.Quit90		}91	}9293	// Hand off the message and model to the appropriate update function for the94	// appropriate view based on the current state.95	if !m.Chosen {96		return updateChoices(msg, m)97	}98	return updateChosen(msg, m)99}100101// The main view, which just calls the appropriate sub-view102func (m model) View() tea.View {103	var s string104	if m.Quitting {105		return tea.NewView("\n  See you later!\n\n")106	}107	if !m.Chosen {108		s = choicesView(m)109	} else {110		s = chosenView(m)111	}112	return tea.NewView(mainStyle.Render("\n" + s + "\n"))113}114115// Sub-update functions116117// Update loop for the first view where you're choosing a task.118func updateChoices(msg tea.Msg, m model) (tea.Model, tea.Cmd) {119	switch msg := msg.(type) {120	case tea.KeyPressMsg:121		switch msg.String() {122		case "j", "down":123			m.Choice++124			if m.Choice > 3 {125				m.Choice = 3126			}127		case "k", "up":128			m.Choice--129			if m.Choice < 0 {130				m.Choice = 0131			}132		case "enter":133			m.Chosen = true134			return m, frame()135		}136137	case tickMsg:138		if m.Ticks == 0 {139			m.Quitting = true140			return m, tea.Quit141		}142		m.Ticks--143		return m, tick()144	}145146	return m, nil147}148149// Update loop for the second view after a choice has been made150func updateChosen(msg tea.Msg, m model) (tea.Model, tea.Cmd) {151	switch msg.(type) {152	case frameMsg:153		if !m.Loaded {154			m.Frames++155			m.Progress = ease.OutBounce(float64(m.Frames) / float64(100))156			if m.Progress >= 1 {157				m.Progress = 1158				m.Loaded = true159				m.Ticks = 3160				return m, tick()161			}162			return m, frame()163		}164165	case tickMsg:166		if m.Loaded {167			if m.Ticks == 0 {168				m.Quitting = true169				return m, tea.Quit170			}171			m.Ticks--172			return m, tick()173		}174	}175176	return m, nil177}178179// Sub-views180181// The first view, where you're choosing a task182func choicesView(m model) string {183	c := m.Choice184185	tpl := "What to do today?\n\n"186	tpl += "%s\n\n"187	tpl += "Program quits in %s seconds\n\n"188	tpl += subtleStyle.Render("j/k, up/down: select") + dotStyle +189		subtleStyle.Render("enter: choose") + dotStyle +190		subtleStyle.Render("q, esc: quit")191192	choices := fmt.Sprintf(193		"%s\n%s\n%s\n%s",194		checkbox("Plant carrots", c == 0),195		checkbox("Go to the market", c == 1),196		checkbox("Read something", c == 2),197		checkbox("See friends", c == 3),198	)199200	return fmt.Sprintf(tpl, choices, ticksStyle.Render(strconv.Itoa(m.Ticks)))201}202203// The second view, after a task has been chosen204func chosenView(m model) string {205	var msg string206207	switch m.Choice {208	case 0:209		msg = fmt.Sprintf("Carrot planting?\n\nCool, we'll need %s and %s...", keywordStyle.Render("libgarden"), keywordStyle.Render("vegeutils"))210	case 1:211		msg = fmt.Sprintf("A trip to the market?\n\nOkay, then we should install %s and %s...", keywordStyle.Render("marketkit"), keywordStyle.Render("libshopping"))212	case 2:213		msg = fmt.Sprintf("Reading time?\n\nOkay, cool, then we’ll need a library. Yes, an %s.", keywordStyle.Render("actual library"))214	default:215		msg = fmt.Sprintf("It’s always good to see friends.\n\nFetching %s and %s...", keywordStyle.Render("social-skills"), keywordStyle.Render("conversationutils"))216	}217218	label := "Downloading..."219	if m.Loaded {220		label = fmt.Sprintf("Downloaded. Exiting in %s seconds...", ticksStyle.Render(strconv.Itoa(m.Ticks)))221	}222223	return msg + "\n\n" + label + "\n" + progressbar(m.Progress) + "%"224}225226func checkbox(label string, checked bool) string {227	if checked {228		return checkboxStyle.Render("[x] " + label)229	}230	return fmt.Sprintf("[ ] %s", label)231}232233func progressbar(percent float64) string {234	w := float64(progressBarWidth)235236	fullSize := int(math.Round(w * percent))237	var fullCells string238	for i := range fullSize {239		fullCells += ramp[i].Render(progressFullChar)240	}241242	emptySize := int(w) - fullSize243	emptyCells := strings.Repeat(progressEmpty, emptySize)244245	return fmt.Sprintf("%s%s %3.0f", fullCells, emptyCells, math.Round(percent*100))246}247248// Utils249250// Generate a blend of colors.251func makeRampStyles(colorA, colorB string, steps float64) (s []lipgloss.Style) {252	cA, _ := colorful.Hex(colorA)253	cB, _ := colorful.Hex(colorB)254255	for i := 0.0; i < steps; i++ {256		c := cA.BlendLuv(cB, i/steps)257		s = append(s, lipgloss.NewStyle().Foreground(lipgloss.Color(colorToHex(c))))258	}259	return s260}261262// Convert a colorful.Color to a hexadecimal format.263func colorToHex(c colorful.Color) string {264	return fmt.Sprintf("#%s%s%s", colorFloatToHex(c.R), colorFloatToHex(c.G), colorFloatToHex(c.B))265}266267// Helper function for converting colors to hex. Assumes a value between 0 and268// 1.269func colorFloatToHex(f float64) (s string) {270	s = strconv.FormatInt(int64(f*255), 16)271	if len(s) == 1 {272		s = "0" + s273	}274	return s275}