// Cool, what was the actual key pressed? switch msg.String() {
// These keys should exit the program. case"ctrl+c", "q": return m, tea.Quit
// The "up" and "k" keys move the cursor up case"up", "k": if m.cursor > 0 { m.cursor-- }
// The "down" and "j" keys move the cursor down case"down", "j": if m.cursor < len(m.choices)-1 { m.cursor++ }
// The "enter" key and the spacebar (a literal space) toggle // the selected state for the item that the cursor is pointing at. case"enter", " ": _, ok := m.selected[m.cursor] if ok { delete(m.selected, m.cursor) } else { m.selected[m.cursor] = struct{}{} } } }
// Return the updated model to the Bubble Tea runtime for processing. // Note that we're not returning a command. return m, nil }
type Model interface { // Init is the first function that will be called. It returns an optional // initial command. To not perform an initial command return nil. Init() Cmd
// Update is called when a message is received. Use it to inspect messages // and, in response, update the model and/or send a command. Update(Msg) (Model, Cmd)
// View renders the program's UI, which is just a string. The view is // rendered after every Update. View() string }
type Msg
也就是可以接受任意类型:
1
type Msg interface{}
type KeyMsg 和 type Key
KeyMsg 就是 Key 的另一种形式:
1
type KeyMsg Key
Key 类型是一个结构体:
1 2 3 4 5
type Key struct { Type KeyType Runes []rune Alt bool }
var ( color = termenv.EnvColorProfile().Color keyword = termenv.Style{}.Foreground(color("204")).Background(color("235")).Styled help = termenv.Style{}.Foreground(color("241")).Styled )
func(m model) Update(msg Msg) (Model, Cmd) { switch msg.(type) { case TickMsg: // Return your Tick command again to loop. return m, doTick() } return m, nil }