Skip to content

Instantly share code, notes, and snippets.

@robinovitch61
Created May 16, 2022 18:59
Show Gist options
  • Save robinovitch61/7b545d756fc7893b8c71dd2dd24c2e6e to your computer and use it in GitHub Desktop.
Save robinovitch61/7b545d756fc7893b8c71dd2dd24c2e6e to your computer and use it in GitHub Desktop.
BubbleTea Subcomponent Parent Updater Functions
package main
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"os"
)
type SubComponentModel struct {
onClick func()
}
func NewSubComponentModel(onClick func()) SubComponentModel {
return SubComponentModel{onClick: onClick}
}
func (m SubComponentModel) Update(msg tea.Msg) (SubComponentModel, tea.Cmd) {
switch msg := msg.(type) {
case tea.MouseMsg:
if msg.Type == tea.MouseRelease {
m.onClick()
}
}
return m, nil
}
func (m SubComponentModel) View() string {
return ""
}
type model struct {
clicked bool
clickCount int
subComponent SubComponentModel
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
switch msg := msg.(type) {
case tea.KeyMsg:
return m, tea.Quit
case tea.MouseMsg:
if msg.Type == tea.MouseRelease {
m.clickCount += 1
}
}
m.subComponent, cmd = m.subComponent.Update(msg)
return m, cmd
}
func (m model) View() string {
if m.clicked {
return fmt.Sprintf("clicked! (%d)", m.clickCount)
} else {
return fmt.Sprintf("not clicked (%d)", m.clickCount)
}
}
func main() {
initialModel := model{clicked: false}
onClick := func() {
initialModel.clicked = true
}
initialModel.subComponent = NewSubComponentModel(onClick)
program := tea.NewProgram(initialModel, tea.WithAltScreen(), tea.WithMouseAllMotion())
if err := program.Start(); err != nil {
fmt.Printf("Error on startup: %v\n", err)
os.Exit(1)
}
}
@robinovitch61
Copy link
Author

For posterity
2022-05-16_15-40-10

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