-
Notifications
You must be signed in to change notification settings - Fork 6
/
textbox.go
421 lines (363 loc) · 11.3 KB
/
textbox.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package control
import (
"bytes"
"context"
"encoding/gob"
"fmt"
"github.com/goradd/gengen/pkg/maps"
"github.com/goradd/goradd/pkg/config"
"github.com/goradd/goradd/pkg/html"
"github.com/goradd/goradd/pkg/page"
html2 "html"
"reflect"
"strconv"
)
const (
TextboxTypeDefault = "text"
TextboxTypePassword = "password"
TextboxTypeSearch = "search"
TextboxTypeNumber = "number" // Puts little arrows in box, will need to widen it.
TextboxTypeEmail = "email" // see TextEmail. Prevents submission of RFC5322 email addresses (Gogh Fir <gf@example.com>)
TextboxTypeTel = "tel" // not well supported
TextboxTypeUrl = "url"
)
// A Validater can be added to a textbox to validate its input on the server side.
// A textbox can have more than one validater.
// A number of built-in validators are provided.
type Validater interface {
// Validate evaluates the input, and returns an empty string if the input is valid, and an error string to display
// to the user if the input does not pass the validator.
Validate(page.ControlI, string) string
}
type TextboxI interface {
page.ControlI
SetType(typ string) TextboxI
ΩSanitize(string) string
}
// Textbox is a goradd control that outputs an "input" html tag with a "type" attribute
// of "text", or one of the text-like types, like "password", "search", etc.
type Textbox struct {
page.Control
typ string
validators []Validater
minLength int
maxLength int
value string
columnCount int
rowCount int
readonly bool
}
// NewTextbox creates a new goradd textbox html widget.
func NewTextbox(parent page.ControlI, id string) *Textbox {
t := &Textbox{}
t.Init(t, parent, id)
return t
}
// Initializes a textbox. Normally you will not call this directly.
func (t *Textbox) Init(self TextboxI, parent page.ControlI, id string) {
t.Control.Init(self, parent, id)
t.Tag = "input"
t.IsVoidTag = true
t.typ = "text" // default
t.SetHasFor(true)
t.SetHasNoSpace(true)
}
func (t *Textbox) this() TextboxI {
return t.Self.(TextboxI)
}
// ValidateWith adds a Validater to the validator list.
func (t *Textbox) ValidateWith(v Validater) {
t.validators = append(t.validators, v)
}
// ResetValidators removes all validators
func (t *Textbox) ResetValidators() {
t.validators = nil
}
// ΩDrawingAttributes is called by the framework to retrieve the tag's private attributes at draw time.
func (t *Textbox) ΩDrawingAttributes() *html.Attributes {
a := t.Control.ΩDrawingAttributes()
a.SetDataAttribute("grctl", "textbox")
a.Set("name", t.ID()) // needed for posts
if t.IsRequired() {
a.Set("required", "")
}
if t.maxLength != 0 {
a.Set("maxlength", strconv.Itoa(t.maxLength))
}
if t.rowCount == 0 { // single-line textbox
a.Set("type", t.typ)
a.Set("value", t.value)
if t.columnCount != 0 {
a.Set("size", strconv.Itoa(t.columnCount))
}
} else {
a.Set("rowCount", strconv.Itoa(t.rowCount))
if t.columnCount != 0 {
a.Set("cols", strconv.Itoa(t.columnCount))
}
}
a.AddAttributeValue("aria-labelledby", t.ID()) // spec says inputs should label themselves so screen reader will read out content of the input
return a
}
// ΩDrawInnerHtml is an internal function that renders the inner html of a tag. In this case, it is rendering the inner
// text of a textarea
func (t *Textbox) ΩDrawInnerHtml(ctx context.Context, buf *bytes.Buffer) (err error) {
_, err = buf.WriteString(html2.EscapeString(t.Text()))
return
}
// Set the value of the text. Returns itself for chaining.
func (t *Textbox) SetText(s string) page.ControlI {
t.value = s
t.SetAttribute("value", s)
return t.this()
}
// Text returns the text entered by the user.
func (t *Textbox) Text() string {
return t.value
}
// SetValue sets the text in the textbox. This satisfies the Valuer interface.
func (t *Textbox) SetValue(v interface{}) page.ControlI {
s := fmt.Sprintf("%v", v)
t.this().SetText(s)
return t.this()
}
// Value returns the user entered text in the textbox.
func (t *Textbox) Value() interface{} {
return t.this().Text()
}
// SetMaxLength sets the maximum length allowed in the textbox. The text will be limited by the
// browser, but the server side will also make sure that the text is not too big.
func (t *Textbox) SetMaxLength(len int) *MaxLengthValidator {
t.maxLength = len
v := MaxLengthValidator{Length: len}
t.ValidateWith(v)
return &v
}
// MaxLength returns the current maximum length setting.
func (t *Textbox) MaxLength() int {
return t.maxLength
}
// SetMinLength will set the minimum length permitted. If the user does not enter enough text,
// an error message will be displayed upon submission of the form.
func (t *Textbox) SetMinLength(len int) *MinLengthValidator {
if len < 0 {
panic("Cannot set minimum length to less than zero.")
}
t.minLength = len
v := MinLengthValidator{Length: len}
t.ValidateWith(v)
return &v
}
// MinLength returns the minimum length setting.
func (t *Textbox) MinLength() int {
return t.minLength
}
// SetPlaceholder will set the html placeholder attribute, which puts text in the textbox
// when the textbox is empty as a hint to the user of what to enter.
func (t *Textbox) SetPlaceholder(s string) TextboxI {
t.SetAttribute("placeholder", s)
return t.this()
}
// Placeholder returns the value of the placeholder.
func (t *Textbox) Placeholder() string {
return t.Attribute("placeholder")
}
// SetType sets the type of textbox this is. Pass it a TEXTBOX_TYPE... constant normally,
// though you can pass any string and it will become the input type
func (t *Textbox) SetType(typ string) TextboxI {
t.typ = typ
t.Refresh() // can't change this without completely redrawing the control
return t.this()
}
// SetColumnCount sets the visible width of the text control. Each table is an approximate with of
// a character, and is browser
// dependent, so its not a very good way of setting the width.
// The css width property is more accurate. Also, this is
// only the visible width, not the maximum number of characters.
func (t *Textbox) SetColumnCount(columns int) {
t.columnCount = columns
if columns <= 0 {
panic("Invalid table value.")
}
t.Refresh()
}
// SetRowCount sets the number of rowCount the Textbox will have.
// A value of 0 produces an input tag, and a value of 1 or greater produces a textarea tag.
func (t *Textbox) SetRowCount(rows int) {
if rows < 0 {
panic("Invalid row value.")
}
if rows == 0 {
t.Tag = "input"
t.IsVoidTag = true
} else {
t.Tag = "textarea"
t.IsVoidTag = false
}
t.rowCount = rows
t.Refresh()
}
// SetReadOnly will disable editing by setting a browser attribute.
func (t *Textbox) SetReadOnly(r bool) {
t.readonly = r
t.AddRenderScript("attr", "readonly", "")
}
// Sanitize is called by the framework when taking in user input and strips it of potential
// malicious XSS scripts.
// The default uses a global sanitizer created at bootup.
// Override Sanitize in a subclass if you want a per-textbox sanitizer.
// This is a very difficult thing to get right, and depends a bit on your application on just
// how much you want to remove.
func (t *Textbox) ΩSanitize(s string) string {
if config.GlobalSanitizer == nil {
return s
}
return config.GlobalSanitizer.Sanitize(s)
}
// Validate will first check for the IsRequired attribute, and if set, will make sure a value is in the text field. It
// will then check the validators in the order assigned. The first invalid value found will return false.
func (t *Textbox) Validate(ctx context.Context) bool {
if v := t.Control.Validate(ctx); !v {
return false
}
text := t.Text()
if t.IsRequired() && text == "" {
if t.ErrorForRequired == "" {
t.SetValidationError(t.ΩT("A value is required"))
} else {
t.SetValidationError(t.ErrorForRequired)
}
return false
}
if t.validators != nil {
for _, v := range t.validators {
if msg := v.Validate(t, t.value); msg != "" {
t.SetValidationError(msg)
return false
}
}
}
return true
}
// ΩUpdateFormValues is an internal function that lets us reflect the value of the textbox on the web override
func (t *Textbox) ΩUpdateFormValues(ctx *page.Context) {
if t.readonly {
// This would happen if someone was attempting to hack the browser.
return
}
id := t.ID()
if v, ok := ctx.FormValue(id); ok {
t.value = t.this().ΩSanitize(v)
}
}
// ΩMarshalState is an internal function to save the state of the control
func (t *Textbox) ΩMarshalState(m maps.Setter) {
m.Set("text", t.Text())
}
// ΩUnmarshalState is an internal function to restore the state of the control
func (t *Textbox) ΩUnmarshalState(m maps.Loader) {
if v,ok := m.Load("text"); ok {
if s, ok := v.(string); ok {
t.value = s
}
}
}
type encodedTextbox struct {
Typ string
Validators []Validater
MinLength int
MaxLength int
Value string
ColumnCount int
RowCount int
Readonly bool
}
// Serialize is used by the framework to serialize the textbox into the pagestate.
func (t *Textbox) Serialize(e page.Encoder) (err error) {
if err = t.Control.Serialize(e); err != nil {
return
}
s := encodedTextbox{
Typ: t.typ,
Validators: t.validators,
MinLength: t.minLength,
MaxLength: t.maxLength,
Value: t.value,
ColumnCount: t.columnCount,
RowCount: t.rowCount,
Readonly: t.readonly,
}
if err = e.Encode(s); err != nil {
return err
}
return
}
// ΩisSerializer is used by the automated control serializer to determine how far down the control chain the control
// has to go before just calling serialize and deserialize.
func (t *Textbox) ΩisSerializer(i page.ControlI) bool {
return reflect.TypeOf(t) == reflect.TypeOf(i)
}
// Deserialize is used by the pagestate serializer.
func (t *Textbox) Deserialize(d page.Decoder, p *page.Page) (err error) {
if err = t.Control.Deserialize(d, p); err != nil {
return
}
s := encodedTextbox{}
if err = d.Decode(&s); err != nil {
return
}
t.typ = s.Typ
t.validators = s.Validators
t.minLength = s.MinLength
t.maxLength = s.MaxLength
t.value = s.Value
t.columnCount = s.ColumnCount
t.rowCount = s.RowCount
t.readonly = s.Readonly
return
}
// MinLenghtValidator is a validator that checks that the user has entered a minimum length.
// It is set up automatically by calling SetMinValue.
type MinLengthValidator struct {
Length int
Message string
}
// Validate runs the Validate logic to validate the control value.
func (v MinLengthValidator) Validate(c page.ControlI, s string) (msg string) {
if s == "" {
return "" // empty textbox is checked elsewhere
}
if len(s) < v.Length {
if v.Message == "" {
return fmt.Sprintf(c.ΩT("Enter at least %d characters"), v.Length) // not a great translation, probably should be an Sprintf implementation
} else {
return v.Message
}
}
return
}
// MaxLengthValidator is a Validater to test that the user did not enter too many characters.
type MaxLengthValidator struct {
Length int
Message string
}
// Validate runs the Validate logic to validate the control value.
func (v MaxLengthValidator) Validate(c page.ControlI, s string) (msg string) {
if s == "" {
return "" // empty textbox is checked elsewhere
}
if len(s) > v.Length {
if v.Message == "" {
return fmt.Sprintf(c.ΩT("Enter at most %d characters"), v.Length)
} else {
return v.Message
}
}
return
}
func init() {
// gob.Register(&Textbox{}) register control.Textbox instead
gob.Register(&MaxLengthValidator{})
gob.Register(&MinLengthValidator{})
gob.Register(&Textbox{})
}