Skip to content
Myr

main.go

This file

Path

examples/debounce/main.go

66 lines · 1.6 KiB · Go

Last changed by

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

History of this file

Take it

The walk stopped after 200 commits: lines older than 3dfbcd9 point at it.

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 1–17why, one step back
1package main
23// This example illustrates how to debounce commands.4//5// When the user presses a key we increment the "tag" value on the model and,6// after a short delay, we include that tag value in the message produced7// by the Tick command.8//9// In a subsequent Update, if the tag in the Msg matches current tag on the10// model's state we know that the debouncing is complete and we can proceed as11// normal. If not, we simply ignore the inbound message.1213import (14 "fmt"15 "os"16 "time"17

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 18why, one step back
18 tea "charm.land/bubbletea/v2"

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 19–34why, one step back
19)
2021const debounceDuration = time.Second2223type exitMsg int2425type model struct {26 tag int27}2829func (m model) Init() tea.Cmd {30 return nil31}3233func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {34 switch msg := msg.(type) {

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

line 35why, one step back
35 case tea.KeyPressMsg:

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 36–55why, one step back
36 // Increment the tag on the model...
37 m.tag++38 return m, tea.Tick(debounceDuration, func(_ time.Time) tea.Msg {39 // ...and include a copy of that tag value in the message.40 return exitMsg(m.tag)41 })42 case exitMsg:43 // If the tag in the message doesn't match the tag on the model then we44 // know that this message was not the last one sent and another is on45 // the way. If that's the case we know, we can ignore this message.46 // Otherwise, the debounce timeout has passed and this message is a47 // valid debounced one.48 if int(msg) == m.tag {49 return m, tea.Quit50 }51 }5253 return m, nil54}55

Merge pull request #1118 from charmbracelet/v2-expAyman Bagabasbefore adoptiond1c8c97

lines 56–58why, one step back
56func (m model) View() tea.View {
57 return tea.NewView(fmt.Sprintf("Key presses: %d", m.tag) +58 "\nTo exit press any key, then wait for one second without pressing anything.")

feat(render): skipping lines from previous frameKonstantin Antonovbefore adoption3dfbcd9

lines 59–66why, one step back
59}
6061func main() {62 if _, err := tea.NewProgram(model{}).Run(); err != nil {63 fmt.Println("uh oh:", err)64 os.Exit(1)65 }66}