/
form.go
84 lines (69 loc) · 1.8 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
package component
import (
"gioui.org/layout"
"gioui.org/unit"
"gioui.org/widget"
"github.com/mirzakhany/chapar/ui/chapartheme"
"github.com/mirzakhany/chapar/ui/keys"
"github.com/mirzakhany/chapar/ui/widgets"
)
type Form struct {
Fields []*Field
onChange func(values map[string]string)
}
type Field struct {
Label string
Value string
Editor *widget.Editor
}
func NewForm(fields []*Field) *Form {
return &Form{
Fields: fields,
}
}
func (f *Form) SetOnChange(onChange func(values map[string]string)) {
f.onChange = onChange
}
func (f *Form) GetValues() map[string]string {
values := make(map[string]string)
for _, field := range f.Fields {
if field.Editor == nil {
field.Editor = new(widget.Editor)
}
values[field.Label] = field.Editor.Text()
}
return values
}
func (f *Form) SetValues(values map[string]string) {
for _, field := range f.Fields {
if field.Editor == nil {
field.Editor = new(widget.Editor)
}
field.Editor.SetText(values[field.Label])
}
}
func (f *Form) Layout(gtx layout.Context, theme *chapartheme.Theme) layout.Dimensions {
childs := make([]layout.FlexChild, 0)
for _, field := range f.Fields {
field := field
childs = append(childs, layout.Rigid(func(gtx layout.Context) layout.Dimensions {
if field.Editor == nil {
field.Editor = new(widget.Editor)
}
keys.OnEditorChange(gtx, field.Editor, func() {
if f.onChange != nil {
f.onChange(f.GetValues())
}
})
lb := &widgets.LabeledInput{
Label: field.Label,
SpaceBetween: 5,
MinEditorWidth: unit.Dp(150),
MinLabelWidth: unit.Dp(80),
Editor: field.Editor,
}
return lb.Layout(gtx, theme)
}), layout.Rigid(layout.Spacer{Height: unit.Dp(5)}.Layout))
}
return layout.Flex{Axis: layout.Vertical, Alignment: layout.Start}.Layout(gtx, childs...)
}