-
Notifications
You must be signed in to change notification settings - Fork 1
/
backend.go
91 lines (77 loc) · 2.44 KB
/
backend.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
//go:build !js
package select_menu
import (
"fmt"
"html/template"
"net/url"
"strconv"
"github.com/shurcooL/htmlg"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
// New creates the HTML for a select menu instance with the specified parameters.
func New(options []string, defaultOption string, query url.Values, queryParameter string) template.HTML {
selectElement := &html.Node{Type: html.ElementNode, Data: "select"}
var selectedOption = defaultOption
if query.Get(queryParameter) != "" {
selectedOption = query.Get(queryParameter)
}
if !contains(options, selectedOption) {
options = append(options, selectedOption)
}
for _, option := range options {
o := &html.Node{Type: html.ElementNode, Data: "option"}
o.AppendChild(htmlg.Text(option))
if option == selectedOption {
o.Attr = append(o.Attr, html.Attribute{Key: atom.Selected.String()})
}
selectElement.AppendChild(o)
}
selectElement.Attr = append(selectElement.Attr, html.Attribute{
Key: "oninput",
// HACK: Don't use Sprintf, properly encode (as json at this time).
Val: fmt.Sprintf(`SelectMenuOnInput(event, this, %q, %q);`, strconv.Quote(defaultOption), strconv.Quote(queryParameter)),
})
return template.HTML(htmlg.Render(selectElement))
}
func contains(ss []string, t string) bool {
for _, s := range ss {
if s == t {
return true
}
}
return false
}
/*
// TODO: Figure this out.
// NewFrontend creates a select menu instance with the specified parameters.
func NewFrontend(options []string, defaultOption string, query url.Values, queryParameter string) *dom.HTMLSelectElement {
selectElement := document.CreateElement("select").(*dom.HTMLSelectElement)
var selectedOption = defaultOption
if query.Get(queryParameter) != "" {
selectedOption = query.Get(queryParameter)
}
if !contains(options, selectedOption) {
options = append(options, selectedOption)
}
for _, option := range options {
o := document.CreateElement("option").(*dom.HTMLOptionElement)
o.Text = option
if option == selectedOption {
o.DefaultSelected = true
}
selectElement.AppendChild(o)
}
selectElement.AddEventListener("input", false, func(event dom.Event) {
selectedIndex := selectElement.Underlying().Get("selectedIndex").Int()
selected := options[selectedIndex]
if selected == defaultOption {
query.Del(queryParameter)
} else {
query.Set(queryParameter, selected)
}
dom.GetWindow().Location().Search = "?" + query.Encode()
})
return selectElement
}
*/