Skip to content

Instantly share code, notes, and snippets.

@virtuallyunknown
Created October 15, 2023 13:45
Show Gist options
  • Save virtuallyunknown/f1621ce3dd736409b99d1a861de9242d to your computer and use it in GitHub Desktop.
Save virtuallyunknown/f1621ce3dd736409b99d1a861de9242d to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
)
type PageNumber int
const (
Page1View PageNumber = iota + 1
Page2View
)
type SomeMessage struct{}
type model struct {
page PageNumber
items []string
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
if msg.Type == tea.KeyEnter && m.page == Page1View {
return m, goToNextPage(&m)
} else {
return m, tea.Quit
}
}
return m, nil
}
func (m model) View() string {
view := ""
if m.page == Page1View {
view += fmt.Sprintf("page: %v\n", m.page)
view += fmt.Sprintf("items: %v %v %v\n", m.items[0], m.items[1], m.items[2])
view += "press enter to go to next page"
} else if m.page == Page2View {
view += fmt.Sprintf("page: %v\n", m.page)
view += fmt.Sprintf("items: %v %v %v\n", m.items[0], m.items[1], m.items[2])
view += "press enter to go to exit"
}
return view
}
func goToNextPage(m *model) tea.Cmd {
return func() tea.Msg {
m.items[0], m.items[1], m.items[2] = "four", "five", "six" // items get updated properly
m.page = Page2View // but page does NOT get updated
return SomeMessage{}
}
}
func main() {
model := model{
page: Page1View,
items: []string{"one", "two", "three"},
}
program := tea.NewProgram(model)
if _, err := program.Run(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
@virtuallyunknown
Copy link
Author

> go run .

page: 1
items: one two three
press enter to go to next page

> Enter is pressed

page: 1
items: four five six
press enter to go to next page

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment