Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

StructForm widget for creating modals with a Form #57

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
162 changes: 162 additions & 0 deletions widget/struct_form.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package widget

import (
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"time"

"fyne.io/fyne/v2"
"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/widget"
)

type StructForm struct {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add some documentation for all exported type?

widget.BaseWidget
structType reflect.Type
form *widget.Form
canvas fyne.Canvas
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You do not need to store this value if you only access it from within NewStructForm.

fields []reflect.StructField
widgets []*widget.FormItem
bindings []binding.DataItem
submit func(s interface{}, err error)
}

func NewStructForm(s interface{}, submit func(s interface{}, err error), cancel func()) *StructForm {
sf := &StructForm{}
sf.ExtendBaseWidget(sf)

sf.structType = reflect.TypeOf(s)
sf.fields = parseFields(sf.structType)
sf.widgets, sf.bindings = createWidgets(sf.fields)
sf.submit = submit

sf.form = &widget.Form{
OnCancel: cancel,
OnSubmit: sf.Submit,
Items: sf.widgets,
}

return sf
}

func buildValue(
t reflect.Type,
fields []reflect.StructField,
bindings []binding.DataItem) (
*reflect.Value,
error,
) {
val := reflect.New(t)

for i, f := range fields {
var v interface{}
var err error

switch bindings[i].(type) {
case binding.Int:
v, err = bindings[i].(binding.Int).Get()
case binding.String:
v, err = bindings[i].(binding.String).Get()
case binding.Float:
v, err = bindings[i].(binding.Float).Get()
case binding.Bool:
v, err = bindings[i].(binding.Bool).Get()
default:
v, err = bindings[i].(binding.Untyped).Get()
}

if err != nil {
return nil, err
}

t_s, t_v := val.Elem().FieldByName(f.Name).Type(), reflect.TypeOf(v)
if t_s != t_v {
return nil, errors.New(fmt.Sprintf("cannot bind mismatched types %v and %v", t_s, t_v))
}
val.Elem().FieldByName(f.Name).Set(
reflect.ValueOf(v),
)
}

return &val, nil
}

func (sf *StructForm) Submit() {
s, err := buildValue(
sf.structType, sf.fields, sf.bindings,
)
if err != nil {
sf.submit(nil, err)
} else {
sf.submit(s.Interface(), err)
}
}

func parseFields(t reflect.Type) []reflect.StructField {
fields := make([]reflect.StructField, 0)
for i := 0; i < t.NumField(); i += 1 {
f := t.Field(i)
if strings.Contains(f.Tag.Get("fyne"), "field") {
fields = append(fields, f)
}
}
return fields
}

func createWidgets(fs []reflect.StructField) ([]*widget.FormItem, []binding.DataItem) {
widgets := make([]*widget.FormItem, len(fs))
binding := make([]binding.DataItem, len(fs))
matchFirstCap := regexp.MustCompile("(.)([A-Z][a-z]+)")
for i, f := range fs {
w, b := fieldToWidget(f)
widgets[i] = &widget.FormItem{
Text: matchFirstCap.ReplaceAllString(f.Name, "${1} ${2}"),
Widget: w,
}
binding[i] = b
}
return widgets, binding
}

func fieldToWidget(f reflect.StructField) (fyne.CanvasObject, binding.DataItem) {
switch f.Type.Kind() {
case reflect.Float32, reflect.Float64:
w := NewNumericalEntry()
w.AllowFloat = true
b := binding.NewString()
w.Bind(b)
return w, binding.StringToFloat(b)
case reflect.Int:
w := NewNumericalEntry()
b := binding.NewString()
w.Bind(b)
return w, binding.StringToInt(b)
case reflect.Bool:
b := binding.NewBool()
w := widget.NewCheck("", func(v bool) {
b.Set(v)
})
return w, b
case reflect.TypeOf(time.Time{}).Kind():
b := binding.NewUntyped()
if err := b.Set(time.Now()); err != nil {
panic(err)
}
w := NewCalendar(time.Now(), func(t time.Time) {
b.Set(t)
})
return w, b
default:
w := widget.NewEntry()
b := binding.NewString()
w.Bind(b)
return w, b
}
}

func (sf *StructForm) CreateRenderer() fyne.WidgetRenderer {
return widget.NewSimpleRenderer(sf.form)
}
179 changes: 179 additions & 0 deletions widget/struct_form_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
package widget

import (
"reflect"
"testing"
"time"

"fyne.io/fyne/v2/data/binding"
"fyne.io/fyne/v2/widget"
)

type testFoo struct {
Field1 string `fyne:"field"`
Field2 int
Field3 bool `fyne:"field"`
Field4 time.Time `fyne:"field"`
}

type testBar struct {
Field1 float64 `fyne:"field"`
Field2 time.Time
}

type testStruct struct {
Name string `fyne:"field"`
Age int `fyne:"field"`
Address string `fyne:"field"`
}

func StringBind(s string) binding.DataItem {
return binding.BindString(&s).(binding.DataItem)
}

func IntBind(i int) binding.DataItem {
return binding.BindInt(&i).(binding.DataItem)
}

func FloatBind(i float64) binding.DataItem {
return binding.BindFloat(&i).(binding.DataItem)
}

func TestNewStructForm(t *testing.T) {
type args struct {
s interface{}
submit func(s interface{}, err error)
cancel func()
}
type res struct {
fields []reflect.StructField
widgets []*widget.FormItem
bindings []binding.DataItem
}
tests := []struct {
name string
args args
want res
}{
{
"testFoo",
args{
testFoo{},
func(s interface{}, err error) {
if err != nil {
t.Error(err)
}
val, ok := s.(*testFoo)
if !ok {
t.Errorf("testFoo struct not created %v from %v", val, s)
}
},
func() {},
},
res{
fields: []reflect.StructField{
{
Name: "Field1",
Type: reflect.TypeOf(""),
Offset: 0,
Index: []int{0},
Tag: reflect.StructTag(`fyne:"field"`),
},
{
Name: "Field3",
Type: reflect.TypeOf(true),
Offset: 24,
Index: []int{2},
Tag: reflect.StructTag(`fyne:"field"`),
},
{
Name: "Field4",
Type: reflect.TypeOf(time.Time{}),
Offset: 32,
Index: []int{3},
Tag: reflect.StructTag(`fyne:"field"`),
},
},
widgets: []*widget.FormItem{
{
Text: "Field1",
Widget: widget.NewEntry(),
},
{
Text: "Field3",
Widget: widget.NewCheck("", func(b bool) {}),
},
{
Text: "Field4",
Widget: NewCalendar(time.Now(), func(t time.Time) {}),
},
},
},
},
{
"testBar",
args{
testBar{},
func(s interface{}, err error) {
if err != nil {
t.Error(err)
}
val, ok := s.(*testBar)
if !ok {
t.Errorf("testFoo struct not created %v from %v", val, s)
}
},
func() {},
},
res{
fields: []reflect.StructField{
{
Name: "Field1",
Type: reflect.TypeOf(float64(1.0)),
Offset: 0,
Index: []int{0},
Tag: reflect.StructTag(`fyne:"field"`),
},
},
widgets: []*widget.FormItem{
{
Text: "Field1",
Widget: NewNumericalEntry(),
},
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := NewStructForm(tt.args.s, tt.args.submit, tt.args.cancel)
if len(got.fields) != len(got.widgets) {
t.Errorf("NewStructForm() len(fields) = %v != len(widgets) = %v", len(got.fields), len(got.widgets))
}
if len(got.fields) != len(got.bindings) {
t.Errorf("NewStructForm() len(fields) = %v != len(bindings) = %v", len(got.fields), len(got.bindings))
}

if len(got.fields) != len(tt.want.fields) {
t.Errorf("NewStructForm() len(fields) = %v, want %v", len(got.fields), len(tt.want.fields))
}
if !reflect.DeepEqual(got.fields, tt.want.fields) {
t.Errorf("NewStructForm().fields got %v want %v", got.fields, tt.want.fields)
}

if len(got.widgets) != len(tt.want.widgets) {
t.Errorf("NewStructForm().widgets got length %v, wanted %v", len(got.widgets), len(tt.want.widgets))
}
for i := 0; i < len(got.widgets) && i < len(tt.want.widgets); i += 1 {
if reflect.TypeOf(got.widgets[i].Widget) != reflect.TypeOf(tt.want.widgets[i].Widget) {
t.Errorf(
"NewStructForm().widgets[%v] = %v, want %v", i,
reflect.TypeOf(got.widgets[i].Widget), reflect.TypeOf(tt.want.widgets[i].Widget),
)
}
}
got.Submit()
})
}
}