-
Notifications
You must be signed in to change notification settings - Fork 6
/
column_map.go
95 lines (83 loc) · 2.57 KB
/
column_map.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 column
import (
"context"
"reflect"
"github.com/goradd/goradd/pkg/page"
"github.com/goradd/goradd/pkg/page/control"
)
// MapColumn is a table that works with data that is in the form of a map. The data item itself must be convertible into
// a string, either by normal string conversion semantics, or using the supplied format string.
type MapColumn struct {
control.ColumnBase
key interface{}
}
// NewMapColumn creates a new column that will treat the data as a map. It will get the data from given index in the
// map and then attempt to convert it into a string. Call SetFormat to explicitly tell the column how to convert the
// data into a string using the fmt.Sprintf function. If the data is a Date, Time or DateTime type, you MUST call
// SetTimeFormat to describe the date or time format.
func NewMapColumn(index interface{}) *MapColumn {
i := MapColumn{}
i.Init(index)
return &i
}
func (c *MapColumn) Init(index interface{}) {
c.ColumnBase.Init(c)
c.key = index
}
func (c *MapColumn) CellData(_ context.Context, rowNum int, colNum int, data interface{}) interface{} {
vKey := reflect.ValueOf(c.key)
vMap := reflect.ValueOf(data)
vValue := vMap.MapIndex(vKey)
if vValue.IsValid() {
i := vValue.Interface()
return i
}
return ""
}
func (c *MapColumn) Serialize(e page.Encoder) {
c.ColumnBase.Serialize(e)
if err := e.Encode(&c.key); err != nil {
panic(err)
}
}
func (c *MapColumn) Deserialize(dec page.Decoder) {
c.ColumnBase.Deserialize(dec)
if err := dec.Decode(&c.key); err != nil {
panic(err)
}
}
// MapColumnCreator creates a column that treats each row of data as a map of data.
// The index can be any valid map index, and the value must be a standard kind of value that
// can be converted to a string.
type MapColumnCreator struct {
// ID will assign the given id to the column. If you do not specify it, an id will be given it by the framework.
ID string
// Index is the key to use to get to the map data
Index interface{}
// Title is the title of the column that appears in the header
Title string
// Sortable makes the column display sort arrows in the header
Sortable bool
control.ColumnOptions
}
func (c MapColumnCreator) Create(ctx context.Context, parent control.TableI) control.ColumnI {
col := NewMapColumn(c.Index)
if c.ID != "" {
col.SetID(c.ID)
}
col.SetTitle(c.Title)
if c.Format != "" {
col.SetFormat(c.Format)
}
if c.TimeFormat != "" {
col.SetTimeFormat(c.TimeFormat)
}
if c.Sortable {
col.SetSortable()
}
col.ApplyOptions(ctx, parent, c.ColumnOptions)
return col
}
func init() {
control.RegisterColumn(MapColumn{})
}