Created
May 16, 2022 18:59
-
-
Save robinovitch61/7b545d756fc7893b8c71dd2dd24c2e6e to your computer and use it in GitHub Desktop.
BubbleTea Subcomponent Parent Updater Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For posterity