This repository has been archived by the owner on Nov 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
form.go
282 lines (248 loc) · 6.53 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package forms
import (
"encoding/json"
"errors"
"github.com/TeaWeb/code/teautils"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/logs"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
"github.com/iwind/TeaGo/utils/string"
"github.com/robertkrimen/otto"
"net/http"
"reflect"
"strings"
)
type Form struct {
Namespace string `yaml:"namespace" json:"namespace"`
Groups []*Group `yaml:"groups" json:"groups"`
Javascript string `yaml:"javascript" json:"javascript"`
CSS string `yaml:"css" json:"css"`
ValidateCode string `yaml:"validateCode" json:"validateCode"`
ComposedAttrs map[string]string `yaml:"composedAttrs" json:"composedAttrs"`
vm *otto.Otto
}
func FormDecode(data []byte, form *Form) error {
m := map[string]interface{}{}
err := json.Unmarshal(data, &m)
if err != nil {
return err
}
namespace, found := m["namespace"]
if found {
form.Namespace = types.String(namespace)
}
validateCode, found := m["validateCode"]
if found {
form.ValidateCode = types.String(validateCode)
}
groups, found := m["groups"]
form.Groups = []*Group{}
if found && groups != nil {
if reflect.TypeOf(groups).Kind() == reflect.Slice {
lists.Each(groups, func(k int, v interface{}) {
if v == nil {
return
}
group := &Group{}
form.Groups = append(form.Groups, group)
vMap := maps.NewMap(v)
group.Namespace = vMap.GetString("namespace")
elements := vMap.GetSlice("elements")
lists.Each(elements, func(k int, v interface{}) {
vMap := maps.NewMap(v)
classType := vMap.GetString("classType")
instance, found := allElementTypes[classType]
if !found || instance == nil {
return
}
obj := reflect.New(reflect.TypeOf(instance).Elem()).Interface().(ElementInterface)
err := teautils.MapToObjectJSON(vMap, obj)
if err != nil {
logs.Error(err)
}
group.Elements = append(group.Elements, obj)
})
})
}
}
return nil
}
func NewForm(namespace string) *Form {
vm := otto.New()
_, err := vm.Run(`
function FieldError(field, message) {
return {
"field": field,
"error": message
};
}
`)
if err != nil {
logs.Error(err)
}
return &Form{
Namespace: namespace,
vm: vm,
}
}
func (this *Form) NewGroup() *Group {
group := &Group{
Namespace: this.Namespace,
}
this.Groups = append(this.Groups, group)
return group
}
func (this *Form) Compose() {
this.CSS = "<style type=\"text/css\">\n"
this.Javascript = ""
for _, g := range this.Groups {
g.ComposedAttrs = this.ComposedAttrs
g.Compose()
for _, e := range g.Elements {
s := e.Super()
if len(s.CSS) > 0 {
this.CSS += s.CSS + "\n\n"
}
if len(s.Javascript) > 0 {
this.Javascript += s.Javascript + "\n\n"
}
}
}
this.CSS += "</style>\n"
}
func (this *Form) Init(values map[string]interface{}) {
eMap := map[string]ElementInterface{} // code => []element
for _, g := range this.Groups {
for _, e := range g.Elements {
s := e.Super()
eMap[s.Code] = e
// 处理不在values中的元素的init
if len(s.InitCode) > 0 {
_, ok := values[s.Code]
if !ok {
newValue, err := this.vm.Run("(function() { var values = " + stringutil.JSONEncode(values) + ";" + s.InitCode + "})()")
if err != nil {
logs.Error(err)
} else if !newValue.IsUndefined() {
newValueInterface, err := newValue.Export()
if err == nil {
s.Value = newValueInterface
}
}
}
}
}
}
// 处理在values中的元素的init
for k, v := range values {
e, found := eMap[k]
if !found {
continue
}
// 初始化值
superElement := e.Super()
if len(superElement.InitCode) > 0 {
newValue, err := this.vm.Run("(function() { var value = " + stringutil.JSONEncode(v) + "; var values = " + stringutil.JSONEncode(values) + ";" + superElement.InitCode + "})()")
if err != nil {
logs.Error(err)
} else if !newValue.IsUndefined() {
newValueInterface, err := newValue.Export()
if err == nil {
v = newValueInterface
}
}
}
superElement.Value = v
}
}
func (this *Form) ApplyRequest(req *http.Request) (values map[string]interface{}, errField string, err error) {
values = map[string]interface{}{}
for _, g := range this.Groups {
for _, e := range g.Elements {
superElement := e.Super()
v, skip, err := e.ApplyRequest(req)
if skip {
continue
}
if err != nil {
return values, "", err
}
// 校验字段值
if len(superElement.ValidateCode) > 0 {
newValue, err := this.vm.Run("(function() { var value = " + stringutil.JSONEncode(v) + ";" + superElement.ValidateCode + "})()")
if err != nil {
return values, superElement.Namespace + "_" + superElement.Code, errors.New(strings.Replace(err.Error(), "Error:", "", -1))
}
if !newValue.IsUndefined() {
newValueInterface, err := newValue.Export()
if err == nil {
v = newValueInterface
}
}
}
values[superElement.Code] = v
}
}
// 全局校验
if len(this.ValidateCode) > 0 {
newValues, err := this.vm.Run("(function() { var values = " + stringutil.JSONEncode(values) + ";" + this.ValidateCode + "})()")
if err != nil {
return values, "", err
}
if !newValues.IsUndefined() {
newValueInterface, err := newValues.Export()
if err == nil {
m := map[string]interface{}{}
if reflect.TypeOf(newValueInterface).Kind() == reflect.Map {
mm := maps.NewMap(newValueInterface)
if mm.Has("error") {
field := mm.GetString("field")
errorString := mm.GetString("error")
return values, this.Namespace + "_" + field, errors.New(errorString)
}
m = mm
}
values = m
}
}
}
return values, "", nil
}
func (this *Form) Encode() ([]byte, error) {
for _, g := range this.Groups {
for _, e := range g.Elements {
v := reflect.ValueOf(e).Elem().FieldByName("Element")
if !v.IsValid() {
logs.Error(errors.New("element should has 'Element' field"))
continue
}
element := v.Interface().(Element)
element.ClassType = reflect.TypeOf(e).Elem().Name()
// namespace
element.Namespace = this.Namespace
v.Set(reflect.ValueOf(element))
}
}
data, err := json.Marshal(this)
if err != nil {
return nil, err
}
return data, nil
}
func (this *Form) EncodePretty() ([]byte, error) {
data, err := this.Encode()
if err != nil {
return nil, err
}
m := map[string]interface{}{}
err = json.Unmarshal(data, &m)
if err != nil {
return nil, err
}
data, err = json.MarshalIndent(m, "", " ")
if err != nil {
return nil, err
}
return data, nil
}