-
Notifications
You must be signed in to change notification settings - Fork 6
/
list_multiselect.go
367 lines (316 loc) · 9 KB
/
list_multiselect.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
package control
import (
"bytes"
"context"
"github.com/goradd/gengen/pkg/maps"
"github.com/goradd/goradd/pkg/html"
"github.com/goradd/goradd/pkg/page"
"reflect"
"strconv"
"strings"
)
type MultiselectListI interface {
page.ControlI
ItemListI
DataManagerEmbedder
}
// MultiselectList is a generic list box which allows multiple selections. It is here for completeness, but is not used
// very often since it doesn't present an intuitive interface and is very browser dependent on what is presented.
// A CheckboxList is better.
type MultiselectList struct {
page.ControlBase
ItemList
DataManager
selectedValues map[string]bool
}
func NewMultiselectList(parent page.ControlI, id string) *MultiselectList {
l := &MultiselectList{}
l.Self = l
l.Init(parent, id)
return l
}
func (l *MultiselectList) Init(parent page.ControlI, id string) {
l.ControlBase.Init(parent, id)
l.ItemList = NewItemList(l)
l.selectedValues = map[string]bool{}
l.Tag = "select"
}
func (l *MultiselectList) this() MultiselectListI {
return l.Self.(MultiselectListI)
}
func (l *MultiselectList) SetSize(size int) MultiselectListI {
l.SetAttribute("size", strconv.Itoa(size))
l.Refresh()
return l.this()
}
func (l *MultiselectList) Size() int {
a := l.Attribute("size")
if a == "" {
return 0
} else {
s, err := strconv.Atoi(a)
if err != nil {
return 0
}
return s
}
}
func (l *MultiselectList) Validate(ctx context.Context) bool {
if l.IsRequired() && len(l.selectedValues) == 0 {
if l.ErrorForRequired == "" {
l.SetValidationError(l.GT("A selection is required"))
} else {
l.SetValidationError(l.ErrorForRequired)
}
return false
}
return true
}
// UpdateFormValues is used by the framework to cause the control to retrieve its values from the form
func (l *MultiselectList) UpdateFormValues(ctx *page.Context) {
id := l.ID()
if a, ok := ctx.FormValues(id); ok {
l.selectedValues = map[string]bool{}
for _, v := range a {
l.selectedValues[v] = true
}
}
}
func (l *MultiselectList) SelectedItems() []*ListItem {
var items []*ListItem
if len(l.selectedValues) == 0 {
return nil
}
for v := range l.selectedValues {
_, item := l.GetItemByValue(v)
if item != nil {
items = append(items, item)
}
}
return items
}
// SetSelectedValues sets the current selection to the given ids. You must ensure that the items with the ids exist, it will
// not attempt to make sure the items exist.
func (l *MultiselectList) SetSelectedValues(ids []string) {
l.SetSelectedValuesNoRefresh(ids)
l.Refresh()
}
func (l *MultiselectList) SetSelectedValuesNoRefresh(values []string) {
l.selectedValues = map[string]bool{}
if values == nil {
return
}
for _, v := range values {
l.selectedValues[v] = true
}
}
func (l *MultiselectList) SetSelectedValueNoRefresh(value string, on bool) {
if on {
l.selectedValues[value] = true
} else {
delete(l.selectedValues, value)
}
}
// Value implements the Valuer interface for general purpose value getting and setting
func (l *MultiselectList) Value() interface{} {
return l.SelectedValues()
}
// SetValue implements the Valuer interface for general purpose value getting and setting
func (l *MultiselectList) SetValue(v interface{}) {
l.selectedValues = map[string]bool{}
switch values := v.(type) {
case string:
a := strings.Split(values, ",")
for _, v := range a {
l.selectedValues[v] = true
}
case []string:
for _, v := range values {
l.selectedValues[v] = true
}
case *ListItem:
l.selectedValues[values.ID()] = true
case []*ListItem:
for _, v := range values {
l.selectedValues[v.ID()] = true
}
default:
panic("Unknown id list type")
}
}
// SelectedIds returns a list of ids sorted by id number that correspond to the selection
func (l *MultiselectList) SelectedIds() []string {
ids := make([]string, 0, len(l.selectedValues))
for v := range l.selectedValues {
id, _ := l.GetItemByValue(v)
if id != "" {
ids = append(ids, id)
}
}
SortIds(ids)
return ids
}
func (l *MultiselectList) SelectedLabels() []string {
var labels []string
for v := range l.selectedValues {
_, item := l.GetItemByValue(v)
if item != nil {
labels = append(labels, item.Label())
}
}
return labels
}
func (l *MultiselectList) SelectedValues() []string {
var values []string
for v := range l.selectedValues {
values = append(values, v)
}
return values
}
// SetData overrides the default data setter to add objects to the item list.
// The result is kept in memory currently.
// ItemLister, ItemIDer, Labeler or Stringer types. This function can accept one or more lists of items, or
// single items.
func (l *MultiselectList) SetData(data interface{}) {
kind := reflect.TypeOf(data).Kind()
if !(kind == reflect.Slice || kind == reflect.Array) {
panic("you must call SetData with a slice or array")
}
l.ItemList.Clear()
l.AddListItems(data)
}
// MarshalState is an internal function to save the state of the control
func (l *MultiselectList) MarshalState(m maps.Setter) {
values := l.SelectedValues()
m.Set("sel", values)
}
// UnmarshalState is an internal function to restore the state of the control
func (l *MultiselectList) UnmarshalState(m maps.Loader) {
l.selectedValues = map[string]bool{}
if s, ok := m.Load("sel"); ok {
if values, ok := s.([]string); ok {
for _, v := range values {
l.selectedValues[v] = true
}
}
}
}
func (l *MultiselectList) DrawTag(ctx context.Context) string {
if l.HasDataProvider() {
l.LoadData(ctx, l.this())
defer l.ResetData()
}
return l.ControlBase.DrawTag(ctx)
}
// DrawingAttributes retrieves the tag's attributes at draw time. You should not normally need to call this, and the
// attributes are disposed of after drawing, so they are essentially read-only.
func (l *MultiselectList) DrawingAttributes(ctx context.Context) html.Attributes {
a := l.ControlBase.DrawingAttributes(ctx)
a.SetDataAttribute("grctl", "multilist")
a.Set("name", l.ID()) // needed for posts
a.Set("multiple", "")
if l.IsRequired() {
a.Set("required", "")
}
return a
}
func (l *MultiselectList) DrawInnerHtml(ctx context.Context, buf *bytes.Buffer) (err error) {
h := l.getItemsHtml(l.items)
buf.WriteString(h)
return nil
}
func (l *MultiselectList) getItemsHtml(items []*ListItem) string {
var h = ""
for _, item := range items {
if item.HasChildItems() {
tag := "optgroup"
innerhtml := l.getItemsHtml(item.ListItems())
attributes := item.Attributes().Copy()
attributes.Set("label", item.Label())
h += html.RenderTag(tag, attributes, innerhtml) + "\n"
} else {
attributes := item.Attributes().Copy()
attributes.Set("value", item.Value())
if l.IsValueSelected(item.Value()) {
attributes.Set("selected", "")
}
h += html.RenderTag("option", attributes, item.Label()) + "\n"
}
}
return h
}
func (l *MultiselectList) IsValueSelected(v string) bool {
b, ok := l.selectedValues[v]
return ok && b
}
func (l *MultiselectList) Serialize(e page.Encoder) (err error) {
if err = l.ControlBase.Serialize(e); err != nil {
return
}
if err = l.ItemList.Serialize(e); err != nil {
return
}
if err = l.DataManager.Serialize(e); err != nil {
return
}
if err = e.Encode(l.selectedValues); err != nil {
return
}
return
}
func (l *MultiselectList) Deserialize(dec page.Decoder) (err error) {
if err = l.ControlBase.Deserialize(dec); err != nil {
return
}
if err = l.ItemList.Deserialize(dec); err != nil {
return
}
if err = l.DataManager.Deserialize(dec); err != nil {
return
}
if err = dec.Decode(&l.selectedValues); err != nil {
return
}
return
}
type MultiselectListCreator struct {
ID string
// Items is a static list of labels and values that will be in the list. Or, use a DataProvider to dynamically generate the items.
Items []ListValue
// DataProvider is the control that will dynamically provide the data for the list and that implements the DataBinder interface.
DataProvider DataBinder
// DataProviderID is the id of a control that will dynamically provide the data for the list and that implements the DataBinder interface.
DataProviderID string
// Size specifies how many items to show, and turns the list into a scrolling list
Size int
// SaveState saves the selected value so that it is restored if the form is returned to.
SaveState bool
page.ControlOptions
}
func (c MultiselectListCreator) Create(ctx context.Context, parent page.ControlI) page.ControlI {
ctrl := NewMultiselectList(parent, c.ID)
if c.Items != nil {
ctrl.AddListItems(c.Items)
}
if c.DataProvider != nil {
ctrl.SetDataProvider(c.DataProvider)
} else if c.DataProviderID != "" {
provider := ctrl.Page().GetControl(c.DataProviderID).(DataBinder)
ctrl.SetDataProvider(provider)
}
if c.Size != 0 {
ctrl.SetSize(c.Size)
}
ctrl.ApplyOptions(ctx, c.ControlOptions)
if c.SaveState {
ctrl.SaveState(ctx, c.SaveState)
}
return ctrl
}
// GetSelectList is a convenience method to return the control with the given id from the page.
func GetMultiselectList(c page.ControlI, id string) *MultiselectList {
return c.Page().GetControl(id).(*MultiselectList)
}
func init() {
page.RegisterControl(&MultiselectList{})
}