Skip to content

Instantly share code, notes, and snippets.

@nicolasparada
Created February 3, 2022 17:20
Show Gist options
  • Save nicolasparada/728259e321d44f513948759c75b8572a to your computer and use it in GitHub Desktop.
Save nicolasparada/728259e321d44f513948759c75b8572a to your computer and use it in GitHub Desktop.
Bubbletea many views
package main
import (
"fmt"
"os"
tea "github.com/charmbracelet/bubbletea"
)
func main() {
err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Start()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func initialModel() model {
return model{
currentView: "A",
}
}
type model struct {
currentView string
viewA viewA
viewB viewB
}
type (
msgWentToA struct{}
msgWentToB struct{}
)
func cmdGoToA() tea.Msg { return msgWentToA{} }
func cmdGoToB() tea.Msg { return msgWentToB{} }
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:
switch {
case msg.String() == "ctrl+c":
return m, tea.Quit
}
case msgWentToA:
m.currentView = "A"
return m, nil
case msgWentToB:
m.currentView = "B"
return m, nil
}
switch m.currentView {
case "A":
var cmd tea.Cmd
m.viewA, cmd = m.viewA.Update(msg)
return m, cmd
case "B":
var cmd tea.Cmd
m.viewB, cmd = m.viewB.Update(msg)
return m, cmd
}
return m, nil
}
func (m model) View() string {
switch m.currentView {
case "A":
return m.viewA.View()
case "B":
return m.viewB.View()
default:
return ""
}
}
package main
import (
"strings"
tea "github.com/charmbracelet/bubbletea"
)
type viewA struct{}
func (m viewA) Update(msg tea.Msg) (viewA, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case strings.ToUpper(msg.String()) == "B":
return m, cmdGoToB
}
}
return m, nil
}
func (m viewA) View() string {
return "Viewing A...\nPress B to switch to B view."
}
package main
import (
"strings"
tea "github.com/charmbracelet/bubbletea"
)
type viewB struct{}
func (m viewB) Update(msg tea.Msg) (viewB, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case strings.ToUpper(msg.String()) == "A":
return m, cmdGoToA
}
}
return m, nil
}
func (m viewB) View() string {
return "Viewing B...\nPress A to switch to A view."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment