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

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 proceed as11// normal. If not, we simply ignore the inbound message.1213import (14	"fmt"15	"os"16	"time"1718	tea "charm.land/bubbletea/v2"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.KeyPressMsg: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() 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.")59}6061func main() {62	if _, err := tea.NewProgram(model{}).Run(); err != nil {63		fmt.Println("uh oh:", err)64		os.Exit(1)65	}66}