Repository navigation
Expand file tree
/
Copy pathrender_input.go
More file actions
600 lines (540 loc) · 17.7 KB
/
Copy pathrender_input.go
File metadata and controls
600 lines (540 loc) · 17.7 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package form
import (
"webtyp.com/dom"
"webtyp.com/fmt"
"webtyp.com/input"
"webtyp.com/lang"
"webtyp.com/widget"
)
// labelChars is the label's budget, calibrated against the --chip-width the
// form skin gives the chip. Truncate counts the three-byte ellipsis inside this
// number, so the visible text is labelChars-3 at most.
//
// The count is BYTES, not runes: an accented character costs two, and a cut can
// land mid-character. Field names are identifiers in practice, so this is
// tolerable here; a title with accents long enough to trip it belongs in the
// input's title, not its label.
const labelChars = 14
// fieldComponent wraps an input.Input to implement dom.Component.
type fieldComponent struct {
input.Input
value *dom.SignalString
err *dom.SignalString
label string
help string
// locked mirrors the owning Form's whole-form read-only gate (Form.SetLocked).
// Shared across every field, so toggling it re-locks/unlocks the entire form.
locked *dom.SignalBool
// onCommit fires when the user finishes editing this field (blur for
// text/textarea/datalist, change for select/radio) — the auto-save hook set
// via Form.OnFieldChange. Nil when the form has none registered.
onCommit func()
// options holds the live choice nodes of a select, radio group or datalist,
// so Form.SetOptions after render repaints them: the choices usually come
// from a Caller whose answer arrives once the form is already on screen.
// Nil until a choice control is built.
options *dom.SignalNodes
buildOptions func() []*dom.Element
}
// bindOptions writes the choices as el's children and binds them to a fresh,
// empty signal that refreshOptions fills later. dom's idiom for seeded rows
// (see datatable): the serializer emits the static children, and the first
// Set replaces them wholesale in the live DOM.
func (fc *fieldComponent) bindOptions(el *dom.Element, build func() []*dom.Element) {
for _, n := range build() {
el.Child(n)
}
fc.buildOptions = build
fc.options = dom.NewNodes()
el.BindChildren(fc.options)
}
// refreshOptions repaints the choice nodes from Input.GetOptions(). A no-op
// before the control is built: the first render reads the options directly.
func (fc *fieldComponent) refreshOptions() {
if fc.options != nil && fc.buildOptions != nil {
fc.options.Set(fc.buildOptions())
}
}
// isDisabledOrLocked combines the field's own static disabled flag with the
// form-wide locked signal — either one disables the rendered control.
func (fc *fieldComponent) isDisabledOrLocked() bool {
return fc.Input.IsDisabled() || (fc.locked != nil && fc.locked.Get())
}
func (fc *fieldComponent) String() string {
return fc.Render().String()
}
// GetID must differ from the input's own id. The framework injects a component's
// id onto its root element (here the field wrapper div); if that equalled the
// input's id, getElementById would resolve the wrapper instead of the input and
// the value binding would write to the div, leaving the input empty.
func (fc *fieldComponent) GetID() string {
return fc.Input.GetID() + ".field"
}
func (fc *fieldComponent) SetID(id string) {
fc.Input.SetID(id)
}
func (fc *fieldComponent) Children() []dom.Component {
return nil
}
// Renderer is an optional capability for custom inputs that own their markup.
// The form still owns the field wrapper (the field wrapper div), the error span, and
// validation: the widget must call onInput with the new value on user input —
// the form updates the value signal and runs live validation. The value
// signal carries the initial value and programmatic updates (SetValues).
type Renderer interface {
RenderInput(value *dom.SignalString, onInput func(string)) *dom.Element
}
func (fc *fieldComponent) validate(val string) {
// Mirrors Form.Validate()'s own skip check (validate.go) — that one already
// gates submission; this one gates the live per-keystroke error display.
// Before this, a field with SetSkipValidation(true) still submitted fine
// but showed a red error while typing, defeating the whole point of
// skipping validation for a field that must not reveal its own format.
if skipper, ok := fc.Input.(interface{ GetSkipValidation() bool }); ok && skipper.GetSkipValidation() {
fc.err.Set("")
return
}
if val == "" {
if req, ok := fc.Input.(interface{ IsRequired() bool }); ok && !req.IsRequired() {
fc.err.Set("")
return
}
}
if err := fc.Input.Validate(val); err != nil {
fc.err.Set(err.Error())
} else {
fc.err.Set("")
}
}
// labelText picks the human label for the field's chip: the title first, then
// the placeholder, then the raw field name as a last resort.
func (fc *fieldComponent) labelText() string {
return lang.Translate(fc.label).String()
}
func (fc *fieldComponent) Render() *dom.Element {
container := dom.NewElement("div").
Class(widget.NameField.Root().String()).
BindStateFunc(widget.Invalid, func() bool { return fc.err.Get() != "" }).
BindStateFunc(widget.Locked, fc.isDisabledOrLocked)
if spanner, ok := fc.Input.(interface{ IsFullWidth() bool }); ok && spanner.IsFullWidth() {
container.SetState(widget.SpanFull)
}
var control *dom.Element
var extra *dom.Element
if r, ok := fc.Input.(Renderer); ok {
control = r.RenderInput(fc.value, func(v string) {
fc.value.Set(v)
fc.validate(v)
})
} else {
htmlName := fc.Input.HTMLName()
switch htmlName {
case "radio":
control = fc.buildRadio()
case "checkbox":
control = fc.buildCheckbox()
case "select":
control = fc.buildSelect()
case "datalist":
control, extra = fc.buildDatalist()
default:
control, extra = fc.buildInput()
}
}
// Field label. Rendered structurally for every titled field so a global form
// skin (e.g. components/fieldset) can present it as a chip/legend; `for` ties
// it to the input for click-to-focus. Form ships no styling for it — the look
// is the consumer's skin.
if lbl := fc.labelText(); lbl != "" && control != nil {
container.Child(dom.NewElement("label").
For(control).
Class(widget.NameField.Class(widget.PartLabel).String()).
Attr("title", lbl). // the untruncated text stays reachable
Text(fmt.Convert(lbl).Truncate(labelChars).String()))
}
errSpan := dom.NewElement("span").
ID(fc.Input.ErrorID()).
Class(widget.NameField.Class(widget.PartError).String()).
Attr("aria-live", "polite").
BindText(fc.err)
var helpEl *dom.Element
if fc.help != "" {
helpEl = dom.NewElement("small").
Class(widget.NameField.Class(widget.PartHelp).String()).
Text(lang.Translate(fc.help).String())
container.Child(helpEl)
}
if control != nil {
if helpEl != nil {
control.DescribedBy(helpEl, errSpan)
} else {
control.DescribedBy(errSpan)
}
container.Child(control)
}
if extra != nil {
container.Child(extra)
}
container.Child(errSpan)
return container
}
func (fc *fieldComponent) buildInput() (*dom.Element, *dom.Element) {
tag := "input"
htmlName := fc.Input.HTMLName()
if htmlName == "textarea" {
tag = "textarea"
}
el := dom.NewElement(tag).
ID(fc.Input.GetID()).
Class(widget.NameField.Class(widget.PartInput).String()).
Attr("name", fc.Input.FieldName())
if htmlName == "textarea" {
el.Class(widget.NameField.Class(widget.PartTextarea).String())
el.Attr("rows", "3")
}
var reveal *dom.Element
if tag == "input" {
masker, isMasked := fc.Input.(interface{ IsMasked() bool })
if isMasked && masker.IsMasked() {
reveal = fc.wireMaskToggle(el)
} else {
el.Attr("type", htmlName)
}
}
// Initial value for SSR
val := fc.value.Get()
if val != "" {
if htmlName == "textarea" {
el.Text(val)
} else {
el.Attr("value", val)
}
}
// Two-way binding
el.Bind(fc.value)
el.OnInput(func(e dom.Event) {
val := e.TargetValue()
fc.value.Set(val)
fc.validate(val)
})
if fc.onCommit != nil {
el.OnBlur(func(dom.Event) { fc.onCommit() })
}
applyCommonAttrs(el, fc)
return el, reveal
}
// wireMaskToggle binds el's type attribute to a revealed/hidden signal
// (instead of the fixed "password" a masked field would otherwise get) and
// returns the button that flips it — the show/hide toggle NIST SP 800-63B
// §5.1.1.2 recommends, on by default for every masked field (see
// docs/PLAN.md in veltylabs/mjosefa-cms for why this replaced an app-local
// button built with syscall/js and a class no stylesheet defined).
func (fc *fieldComponent) wireMaskToggle(el *dom.Element) *dom.Element {
revealed := dom.NewBool(false)
el.BindAttrFunc("type", func() string {
if revealed.Get() {
return "text"
}
return "password"
})
return dom.NewElement("button").
Attr("type", "button"). // never submit — revealing must not send the form
ID(fc.Input.GetID()+".reveal").
Class(widget.NameField.Class(widget.PartReveal).String()).
BindState(widget.Selected, revealed).
BindAttrFunc("aria-label", func() string {
if revealed.Get() {
return "Ocultar"
}
return "Mostrar"
}).
BindAttrFunc("aria-pressed", func() string {
if revealed.Get() {
return "true"
}
return "false"
}).
OnClick(func(dom.Event) { revealed.Set(!revealed.Get()) }).
Child(eyeGlyph())
}
// eyeGlyph is a real inline SVG (fill="currentColor", so components/fieldset's
// Glyph() colors it through the cascade like any other text) — never an emoji:
// a "👁" renders a different bitmap per OS/font and ignores color entirely.
// One shape for both states; components/fieldset's When(Selected, …) is what
// changes how it reads as revealed vs hidden, not a second icon to keep in
// sync.
func eyeGlyph() *dom.Element {
return dom.NewElement("svg").
Attr("viewBox", "0 0 24 24").
Attr("width", "18").
Attr("height", "18").
Attr("aria-hidden", "true").
Attr("fill", "currentColor").
Child(dom.NewElement("path").
Attr("d", "M12 5C5 5 1 12 1 12s4 7 11 7 11-7 11-7-4-7-11-7zm0 12a5 5 0 1 1 0-10 5 5 0 0 1 0 10zm0-2a3 3 0 1 0 0-6 3 3 0 0 0 0 6z"))
}
func (fc *fieldComponent) buildSelect() *dom.Element {
el := dom.NewElement("select").
ID(fc.Input.GetID()).
Class(widget.NameField.Class(widget.PartInput).String()).
Attr("name", fc.Input.FieldName())
if fc.Input.IsRequired() {
el.Attr("required", "")
}
el.BindAttrBoolFunc("disabled", fc.isDisabledOrLocked)
// Two-way binding for select
el.Bind(fc.value)
el.OnChange(func(e dom.Event) {
val := e.TargetValue()
fc.value.Set(val)
fc.validate(val)
if fc.onCommit != nil {
fc.onCommit()
}
})
fc.bindOptions(el, func() []*dom.Element {
val := fc.value.Get()
opts := fc.Input.GetOptions()
nodes := make([]*dom.Element, 0, len(opts))
for _, opt := range opts {
option := dom.NewElement("option").Attr("value", opt.Key).Text(lang.Translate(opt.Value).String())
if val != "" && opt.Key == val {
option.Attr("selected", "")
}
nodes = append(nodes, option)
}
return nodes
})
return el
}
func (fc *fieldComponent) buildRadio() *dom.Element {
group := dom.NewElement("div").
ID(fc.Input.GetID()).
Class(widget.NameField.Class(widget.PartRadioGroup).String())
fc.bindOptions(group, func() []*dom.Element {
val := fc.value.Get()
opts := fc.Input.GetOptions()
nodes := make([]*dom.Element, 0, len(opts))
for _, opt := range opts {
optKey := opt.Key
optVal := opt.Value
radio := dom.NewElement("input").
Attr("type", "radio").
Class(widget.NameField.Class(widget.PartRadioNative).String()).
Attr("name", fc.Input.FieldName()).
Attr("value", optKey)
if val != "" && optKey == val {
radio.Attr("checked", "")
}
// Reactive checked state
radio.BindAttrBoolFunc("checked", func() bool {
return fc.value.Get() == optKey
})
radio.BindAttrBoolFunc("disabled", fc.isDisabledOrLocked)
radio.OnChange(func(e dom.Event) {
if e.TargetChecked() {
fc.value.Set(optKey)
fc.validate(optKey)
if fc.onCommit != nil {
fc.onCommit()
}
}
})
label := dom.NewElement("label").
For(radio).
Class(widget.NameField.Class(widget.PartRadioOption).String()).
BindStateFunc(widget.Selected, func() bool {
return fc.value.Get() == optKey
})
label.Child(radio)
label.Child(radioUncheckedGlyph())
label.Child(radioCheckedGlyph())
label.Child(dom.NewElement("span").Text(lang.Translate(optVal).String()))
nodes = append(nodes, label)
}
return nodes
})
return group
}
func radioUncheckedGlyph() *dom.Element {
return dom.NewElement("svg").
Class(widget.NameField.Class(widget.PartRadioUnchecked).String()).
Attr("viewBox", "0 0 24 24").
Attr("width", "24").
Attr("height", "24").
Attr("aria-hidden", "true").
Child(dom.NewElement("circle").
Attr("cx", "12").Attr("cy", "12").Attr("r", "9").
Attr("stroke", "var(--color-outline, #D1D1D6)").
Attr("stroke-width", "2").
Attr("fill", "none").
Attr("style", "fill: none;"))
}
func radioCheckedGlyph() *dom.Element {
return dom.NewElement("svg").
Class(widget.NameField.Class(widget.PartRadioChecked).String()).
Attr("viewBox", "0 0 24 24").
Attr("width", "24").
Attr("height", "24").
Attr("aria-hidden", "true").
Child(
dom.NewElement("circle").
Attr("cx", "12").Attr("cy", "12").Attr("r", "9").
Attr("stroke", "var(--color-primary, #654FF0)").
Attr("stroke-width", "2").
Attr("fill", "none").
Attr("style", "fill: none;"),
dom.NewElement("circle").
Attr("cx", "12").Attr("cy", "12").Attr("r", "5").
Attr("fill", "var(--color-primary, #654FF0)").
Attr("style", "fill: var(--color-primary, #654FF0);"),
)
}
func (fc *fieldComponent) buildCheckbox() *dom.Element {
val := fc.value.Get()
isChecked := val == "true" || val == "1" || val == "on"
chk := dom.NewElement("input").
Attr("type", "checkbox").
ID(fc.Input.GetID()).
Class(widget.NameField.Class(widget.PartCheckNative).String()).
Attr("name", fc.Input.FieldName())
if isChecked {
chk.Attr("checked", "")
}
chk.BindAttrBoolFunc("checked", func() bool {
v := fc.value.Get()
return v == "true" || v == "1" || v == "on"
})
chk.BindAttrBoolFunc("disabled", fc.isDisabledOrLocked)
chk.OnChange(func(e dom.Event) {
checked := e.TargetChecked()
v := "false"
if checked {
v = "true"
}
fc.value.Set(v)
fc.validate(v)
if fc.onCommit != nil {
fc.onCommit()
}
})
label := dom.NewElement("label").
For(chk).
Class(widget.NameField.Class(widget.PartCheckOption).String()).
BindStateFunc(widget.Selected, func() bool {
v := fc.value.Get()
return v == "true" || v == "1" || v == "on"
})
label.Child(chk)
label.Child(checkUncheckedGlyph())
label.Child(checkCheckedGlyph())
txt := fc.Input.GetPlaceholder()
if txt == "" {
txt = lang.Translate(fc.label).String()
}
label.Child(dom.NewElement("span").Text(txt))
return label
}
func checkUncheckedGlyph() *dom.Element {
return dom.NewElement("svg").
Class(widget.NameField.Class(widget.PartCheckUnchecked).String()).
Attr("viewBox", "0 0 24 24").
Attr("width", "24").
Attr("height", "24").
Attr("aria-hidden", "true").
Child(dom.NewElement("rect").
Attr("x", "3").Attr("y", "3").Attr("width", "18").Attr("height", "18").Attr("rx", "4").
Attr("stroke", "var(--color-outline, #D1D1D6)").
Attr("stroke-width", "2").
Attr("fill", "none").
Attr("style", "fill: none;"))
}
func checkCheckedGlyph() *dom.Element {
return dom.NewElement("svg").
Class(widget.NameField.Class(widget.PartCheckChecked).String()).
Attr("viewBox", "0 0 24 24").
Attr("width", "24").
Attr("height", "24").
Attr("aria-hidden", "true").
Child(
dom.NewElement("rect").
Attr("x", "3").Attr("y", "3").Attr("width", "18").Attr("height", "18").Attr("rx", "4").
Attr("fill", "var(--color-primary, #654FF0)").
Attr("style", "fill: var(--color-primary, #654FF0);"),
dom.NewElement("path").
Attr("d", "M7 12.5l3.5 3.5 7-7").
Attr("stroke", "var(--color-on-primary, #ffffff)").
Attr("stroke-width", "2.5").
Attr("stroke-linecap", "round").
Attr("stroke-linejoin", "round").
Attr("fill", "none").
Attr("style", "fill: none;"),
)
}
func (fc *fieldComponent) buildDatalist() (*dom.Element, *dom.Element) {
listID := fc.Input.GetID() + "-list"
el := dom.NewElement("input").
Attr("type", "text").
ID(fc.Input.GetID()).
Class(widget.NameField.Class(widget.PartInput).String()).
Attr("name", fc.Input.FieldName()).
Attr("list", listID)
// Two-way binding
el.Bind(fc.value)
el.OnInput(func(e dom.Event) {
val := e.TargetValue()
fc.value.Set(val)
fc.validate(val)
})
if fc.onCommit != nil {
el.OnBlur(func(dom.Event) { fc.onCommit() })
}
applyCommonAttrs(el, fc)
// dom exposes (*Element).For for for=, but nothing equivalent for list= / aria-describedby / aria-labelledby yet.
datalist := dom.NewElement("datalist").ID(listID)
fc.bindOptions(datalist, func() []*dom.Element {
opts := fc.Input.GetOptions()
nodes := make([]*dom.Element, 0, len(opts))
for _, opt := range opts {
nodes = append(nodes, dom.NewElement("option").Attr("value", opt.Key).Text(lang.Translate(opt.Value).String()))
}
return nodes
})
return el, datalist
}
func applyCommonAttrs(el *dom.Element, fc *fieldComponent) {
inp := fc.Input
if ph := inp.GetPlaceholder(); ph != "" {
el.Attr("placeholder", ph)
}
if title := inp.GetTitle(); title != "" {
el.Attr("title", title)
}
for _, attr := range inp.GetAttributes() {
if attr.Value != "" {
el.Attr(attr.Key, attr.Value)
}
}
if inp.IsRequired() {
el.Attr("required", "")
}
el.BindAttrBoolFunc("disabled", fc.isDisabledOrLocked)
if inp.IsReadonly() {
el.Attr("readonly", "")
}
}
// RenderInput is kept for backward compatibility and as a standalone helper
func RenderInput(inp input.Input) *dom.Element {
lbl := inp.GetTitle()
if lbl == "" || lbl == inp.FieldName() {
lbl = fmt.Convert(inp.FieldName()).Replace("_", " ").String()
}
fc := &fieldComponent{
Input: inp,
value: dom.NewString(""),
err: dom.NewString(""),
label: lbl,
}
// Note: this Render() returns the field wrapper div containing the input + error span.
return fc.Render()
}