github.com/egonelbre/exp@v0.0.0-20240430123955-ed1d3aa93911/dos/ui/input.go (about) 1 package ui 2 3 import ( 4 "fmt" 5 6 termbox "github.com/nsf/termbox-go" 7 ) 8 9 type Input struct { 10 Format string 11 Text string 12 } 13 14 func (input *Input) Focusable() bool { return true } 15 16 func (input *Input) Handle(form *Form, action Action) { 17 switch action := action.(type) { 18 case KeyPress: 19 switch action.Key { 20 case termbox.KeyBackspace: 21 if len(input.Text) > 0 { 22 input.Text = input.Text[:len(input.Text)-1] 23 } 24 default: 25 // TODO: check whether it's a character 26 input.Text = input.Text + string([]rune{action.Char}) 27 } 28 default: 29 // TODO: log ignored action 30 } 31 } 32 33 func (input *Input) Unserialize(data []byte) error { 34 input.Text = string(data) 35 return nil 36 } 37 func (input *Input) Serialize() ([]byte, error) { 38 return []byte(input.Text), nil 39 } 40 41 func (input *Input) Render(form *Form, component *Component) { 42 text := input.Text 43 if input.Format != "" { 44 text = fmt.Sprintf(input.Format, input.Text) 45 } 46 form.DrawText(component.Rect, text, component.Focused) 47 }