diff --git a/examples/input/main.go b/examples/input/main.go new file mode 100644 index 0000000..24ac4c9 --- /dev/null +++ b/examples/input/main.go @@ -0,0 +1,68 @@ +package main + +// A simple program that counts down from 5 and then exits. + +import ( + "fmt" + "log" + "tea" + + "tea/input" +) + +type model struct { + input input.Model +} + +type tickMsg struct{} + +func main() { + tea.UseSysLog("tea") + + p := tea.NewProgram( + model{ + input: input.DefaultModel(), + }, + update, + view, + nil, + //[]tea.Sub{input.Blink}, + ) + + if err := p.Start(); err != nil { + log.Fatal(err) + } +} + +func update(msg tea.Msg, mdl tea.Model) (tea.Model, tea.Cmd) { + var cmd tea.Cmd + + m, _ := mdl.(model) + + switch msg := msg.(type) { + case tea.KeyMsg: + switch msg.String() { + case "break": + fallthrough + case "esc": + return m, tea.Quit + } + + case input.CursorBlinkMsg: + return input.Update(msg, m.input) + } + + m.input, cmd = input.Update(msg, m.input) + return m, cmd +} + +func view(mdl tea.Model) string { + m, _ := mdl.(model) + help := "(esc to exit)" + + return fmt.Sprintf( + "What’s your favorite Pokémon?\n\n%s\n\n%s", + input.View(m.input), + help, + ) +} diff --git a/input/input.go b/input/input.go new file mode 100644 index 0000000..31b71f8 --- /dev/null +++ b/input/input.go @@ -0,0 +1,66 @@ +package input + +import ( + "log" + "tea" + "time" +) + +type Model struct { + Prompt string + Value string + Cursor string + HiddenCursor string + Blink bool + BlinkSpeed time.Duration +} + +type CursorBlinkMsg struct{} + +func DefaultModel() Model { + return Model{ + Prompt: "> ", + Value: "", + Cursor: "█", + HiddenCursor: " ", + Blink: false, + BlinkSpeed: time.Second, + } +} + +func Update(msg tea.Msg, model tea.Model) (Model, tea.Cmd) { + m, _ := model.(Model) + + log.Printf("msg: %v\n", msg) + switch msg := msg.(type) { + + case tea.KeyMsg: + switch msg.Type { + case tea.KeyBackspace: + m.Value = m.Value[:len(m.Value)-1] + case tea.KeyRune: + m.Value = m.Value + msg.String() + } + + case CursorBlinkMsg: + m.Blink = !m.Blink + } + + return m, nil +} + +func View(model tea.Model) string { + m, _ := model.(Model) + cursor := m.Cursor + //if m.Blink { + //cursor = m.HiddenCursor + //} + return m.Prompt + m.Value + cursor +} + +func Blink(model tea.Model) tea.Msg { + //m, _ := model.(Model) + //time.Sleep(m.BlinkSpeed) + time.Sleep(time.Second) + return CursorBlinkMsg{} +}