Skip to content
Myr

First pass at text input

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

authored by Christian Rocha · committed by Christian Rocha · parent 32dc19b · Browse files · 2 files+134 added−0 removed
This commit

State

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

Diff stats

2 files+134 added−0 removed

  • other:+134 added−0 removed

2 files+134 added−0 removed

added:examples/input/main.go+68 added
1package main23// A simple program that counts down from 5 and then exits.45import (6 "fmt"7 "log"8 "tea"910 "tea/input"11)1213type model struct {14 input input.Model15}1617type tickMsg struct{}1819func main() {20 tea.UseSysLog("tea")2122 p := tea.NewProgram(23 model{24 input: input.DefaultModel(),25 },26 update,27 view,28 nil,29 //[]tea.Sub{input.Blink},30 )3132 if err := p.Start(); err != nil {33 log.Fatal(err)34 }35}3637func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) {38 var cmd tea.Cmd3940 m, _ := mdl.(model)4142 switch msg := msg.(type) {43 case tea.KeyMsg:44 switch msg.String() {45 case "break":46 fallthrough47 case "esc":48 return m, tea.Quit49 }5051 case input.CursorBlinkMsg:52 return input.Update(msg, m.input)53 }5455 m.input, cmd = input.Update(msg, m.input)56 return m, cmd57}5859func view(mdl tea.Model) string {60 m, _ := mdl.(model)61 help := "(esc to exit)"6263 return fmt.Sprintf(64 "What’s your favorite Pokémon?\n\n%s\n\n%s",65 input.View(m.input),66 help,67 )68}
added:input/input.go+66 added
1package input23import (4 "log"5 "tea"6 "time"7)89type Model struct {10 Prompt string11 Value string12 Cursor string13 HiddenCursor string14 Blink bool15 BlinkSpeed time.Duration16}1718type CursorBlinkMsg struct{}1920func DefaultModel() Model {21 return Model{22 Prompt: "> ",23 Value: "",24 Cursor: "█",25 HiddenCursor: " ",26 Blink: false,27 BlinkSpeed: time.Second,28 }29}3031func Update(msg tea.Msg, model tea.Model) (Model, tea.Cmd) {32 m, _ := model.(Model)3334 log.Printf("msg: %v\n", msg)35 switch msg := msg.(type) {3637 case tea.KeyMsg:38 switch msg.Type {39 case tea.KeyBackspace:40 m.Value = m.Value[:len(m.Value)-1]41 case tea.KeyRune:42 m.Value = m.Value + msg.String()43 }4445 case CursorBlinkMsg:46 m.Blink = !m.Blink47 }4849 return m, nil50}5152func View(model tea.Model) string {53 m, _ := model.(Model)54 cursor := m.Cursor55 //if m.Blink {56 //cursor = m.HiddenCursor57 //}58 return m.Prompt + m.Value + cursor59}6061func Blink(model tea.Model) tea.Msg {62 //m, _ := model.(Model)63 //time.Sleep(m.BlinkSpeed)64 time.Sleep(time.Second)65 return CursorBlinkMsg{}66}