repos / pico

pico services mono repo
git clone https://github.com/picosh/pico.git

pico / pkg / tui
Antonio Mika  ·  2025-03-12

input.go

 1package tui
 2
 3import (
 4	"git.sr.ht/~rockorager/vaxis"
 5	"git.sr.ht/~rockorager/vaxis/vxfw"
 6	"git.sr.ht/~rockorager/vaxis/vxfw/text"
 7	"git.sr.ht/~rockorager/vaxis/vxfw/textfield"
 8)
 9
10type TextInput struct {
11	input *textfield.TextField
12	label string
13	focus bool
14}
15
16func (m *TextInput) GetValue() string {
17	return m.input.Value
18}
19
20func (m *TextInput) Reset() {
21	m.input.Reset()
22}
23
24func NewTextInput(label string) *TextInput {
25	input := textfield.New()
26	return &TextInput{
27		label: label,
28		input: input,
29	}
30}
31
32func (m *TextInput) FocusIn() (vxfw.Command, error) {
33	m.focus = true
34	return vxfw.FocusWidgetCmd(m.input), nil
35}
36
37func (m *TextInput) FocusOut() (vxfw.Command, error) {
38	m.focus = false
39	return vxfw.RedrawCmd{}, nil
40}
41
42func (m *TextInput) HandleEvent(ev vaxis.Event, phase vxfw.EventPhase) (vxfw.Command, error) {
43	switch msg := ev.(type) {
44	case vaxis.Key:
45		if msg.Matches(vaxis.KeyTab) {
46			m.focus = !m.focus
47			return vxfw.RedrawCmd{}, nil
48		}
49	}
50	return nil, nil
51}
52
53func (m *TextInput) Draw(ctx vxfw.DrawContext) (vxfw.Surface, error) {
54	txt := text.New("> ")
55	if m.focus {
56		txt.Style = vaxis.Style{Foreground: oj}
57	} else {
58		txt.Style = vaxis.Style{Foreground: purp}
59	}
60	txtSurf, _ := txt.Draw(ctx)
61	inputSurf, _ := m.input.Draw(ctx)
62	stack := NewGroupStack([]vxfw.Surface{
63		txtSurf,
64		inputSurf,
65	})
66	stack.Direction = "horizontal"
67	brd := NewBorder(stack)
68	brd.Label = m.label
69	if m.focus {
70		brd.Style = vaxis.Style{Foreground: oj}
71	} else {
72		brd.Style = vaxis.Style{Foreground: purp}
73	}
74	surf, _ := brd.Draw(ctx)
75	return surf, nil
76}