Skip to content
Myr

docs: add debounce example (#348)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* docs: add debounce example * refactor: reformat comments Co-authored-by: Maas Lalani <maas@lalani.dev> * refactor: init model before program start Co-authored-by: Maas Lalani <maas@lalani.dev> * feat: show tag in view * docs(examples): improve debounce example comments * docs(examples): remove extraneous lipgloss join

authored by bashbunni · committed by GitHub · parent 636f2c2 · Browse files · 1 file+66 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Maas Lalani <maas@lalani.dev>
  • Co-authored-by: Christian Rocha <christian@rocha.is>

Diff stats

1 file+66 added−0 removed

  • other:+66 added−0 removed

1 file+66 added−0 removed

added:examples/debounce/main.go+66 added
1package main23// 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 proceeed as11// normal. If not, we simply ignore the inbound message.1213import (14 "fmt"15 "os"16 "time"1718 tea "github.com/charmbracelet/bubbletea"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) {35 case tea.KeyMsg: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}5556func (m model) View() string {57 return fmt.Sprintf("Key presses: %d", m.tag) +58 "\nTo exit press any key, then wait for one second without pressing anything."59}6061func main() {62 if err := tea.NewProgram(model{}).Start(); err != nil {63 fmt.Println("uh oh:", err)64 os.Exit(1)65 }66}