Created
October 30, 2023 11:33
-
-
Save teghnet/72ece4be98bcfa8c846e6ce06712ba4e to your computer and use it in GitHub Desktop.
State Machine for Charm
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 state is for implementing a simple state machine. | |
// In a [tea.Model.Update] method one can use a `case` for a [Transition] message to change the state. | |
// | |
// case state.Transition: | |
// if !msg.Used() { | |
// m.State = msg.State() | |
// return m, msg.AsUsed() | |
// } | |
package state | |
import ( | |
tea "github.com/charmbracelet/bubbletea" | |
) | |
// State machine | |
type State string | |
// Next creates a command that returns a Transition message with previous and next states | |
func (s State) Next(ns State) tea.Cmd { | |
return func() tea.Msg { return Transition{prev: s, state: ns} } | |
} | |
// Transition is a message used to indicate a Transition between states | |
// The used field is to indicate that the message has been seen and processed | |
type Transition struct { | |
prev State | |
state State | |
used bool | |
} | |
// WasUsed returns true if the Transition has been used | |
func (t Transition) WasUsed() bool { | |
return t.used | |
} | |
// State returns the desired state after the Transition | |
func (t Transition) State() State { | |
return t.state | |
} | |
// Used returns a tea.Msg with a Transition that is marked as used | |
func (t Transition) Used() tea.Msg { | |
t.used = true | |
return t | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment