-
Notifications
You must be signed in to change notification settings - Fork 1
/
filters_base.go
95 lines (83 loc) · 2.09 KB
/
filters_base.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
package scopes
// Filter is implemented by all scope filter types.
type Filter interface {
serializeFilter() map[string]interface{}
}
type FilterDisplayHints int
const (
FilterDisplayDefault FilterDisplayHints = 0
FilterDisplayPrimary FilterDisplayHints = 1 << iota
)
// FilterState represents the current state of a set of filters.
type FilterState map[string]interface{}
type filterBase struct {
Id string
DisplayHints FilterDisplayHints
FilterType string
Title string
}
func (f *filterBase) serializeFilter() map[string]interface{} {
v := map[string]interface{}{
"filter_type": f.FilterType,
"id": f.Id,
"display_hints": f.DisplayHints,
}
if f.Title != "" {
v["title"] = f.Title
}
return v
}
type filterWithOptions struct {
filterBase
Options []FilterOption
}
// AddOption adds a new option to the filter.
func (f *filterWithOptions) AddOption(id, label string, defaultValue bool) {
f.Options = append(f.Options, FilterOption{
Id: id,
Label: label,
Default: defaultValue,
})
}
func (f *filterWithOptions) isValidOption(optionId interface{}) bool {
for _, o := range f.Options {
if o.Id == optionId {
return true
}
}
return false
}
// HasActiveOption returns true if any of the filters options are active.
func (f *filterWithOptions) HasActiveOption(state FilterState) bool {
for _, optionId := range f.ActiveOptions(state) {
if f.isValidOption(optionId) {
return true
}
}
return false
}
// ActiveOptions returns the filter's active options from the filter state.
func (f *filterWithOptions) ActiveOptions(state FilterState) []string {
var ret []string
if state[f.Id] != nil {
options := state[f.Id].([]interface{})
ret = make([]string, len(options))
for i, opt := range options {
ret[i] = opt.(string)
}
} else {
// We don't have this filter in the state object, so
// give defaults back.
for _, o := range f.Options {
if o.Default {
ret = append(ret, o.Id)
}
}
}
return ret
}
type FilterOption struct {
Id string `json:"id"`
Label string `json:"label"`
Default bool `json:"default"`
}