-
Notifications
You must be signed in to change notification settings - Fork 0
/
form.go
105 lines (84 loc) · 2.29 KB
/
form.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package ext
import (
"sort"
"github.com/rivo/tview"
)
// FormDataProvider an interface for getting options for dropdown fields.
type FormDataProvider interface {
GetDropDownOptions(label string) []string
}
// Form an extension for tview.Form. It used to avoid duplication while setting and getting field values.
type Form struct {
*tview.Form
dateFields map[string]*DateField
inputFields map[string]*tview.InputField
dropDowns map[string]*tview.DropDown
dataProvider FormDataProvider
}
// NewForm returns new extended Form.
func NewForm(form *tview.Form, dataProvider FormDataProvider) *Form {
f := &Form{
Form: form,
dateFields: make(map[string]*DateField),
inputFields: make(map[string]*tview.InputField),
dropDowns: make(map[string]*tview.DropDown),
dataProvider: dataProvider,
}
// gather form items into groups
for i := 0; i < form.GetFormItemCount(); i++ {
item := form.GetFormItem(i)
dateField, ok := item.(*DateField)
if ok {
f.dateFields[item.GetLabel()] = dateField
}
inputField, ok := item.(*tview.InputField)
if ok {
f.inputFields[item.GetLabel()] = inputField
}
dropDown, ok := item.(*tview.DropDown)
if ok {
f.dropDowns[item.GetLabel()] = dropDown
}
}
return f
}
// SetFields sets fields value from map where key is field label and value is a value.
func (f *Form) SetFields(m map[string]string) {
for label, value := range m {
dateField, ok := f.dateFields[label]
if ok {
dateField.SetTextDate(value)
continue
}
inputField, ok := f.inputFields[label]
if ok {
inputField.SetText(value)
continue
}
dropDown, ok := f.dropDowns[label]
if ok {
opts := f.dataProvider.GetDropDownOptions(label)
index := -1
if value != "" {
index = sort.SearchStrings(opts, value)
}
dropDown.SetOptions(opts, nil).SetCurrentOption(index)
continue
}
}
f.Form.SetFocus(0)
}
// GetFields returns fields values as map of strings where the key is field label.
func (f *Form) GetFields() map[string]string {
res := make(map[string]string)
for label, dateField := range f.dateFields {
res[label] = dateField.GetTextDate()
}
for label, inputField := range f.inputFields {
res[label] = inputField.GetText()
}
for label, dropDown := range f.dropDowns {
_, res[label] = dropDown.GetCurrentOption()
}
return res
}