-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstyles.go
89 lines (68 loc) · 1.57 KB
/
styles.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
package dhtml
import (
"fmt"
"maps"
"slices"
"strings"
"github.com/mitoteam/mttools"
)
// styles list handling
type Styles struct {
propertyValues map[string]string // property => value
}
// force interface implementation
var _ fmt.Stringer = (*Styles)(nil)
// Creates new Styles{} (with possible initial values).
func NewStyles(v ...any) Styles {
st := Styles{
propertyValues: make(map[string]string),
}
st.Add(v...)
return st
}
func (s *Styles) String() string {
properties := slices.Collect(maps.Keys(s.propertyValues))
slices.Sort(properties)
var sb strings.Builder
for _, property := range properties {
value := s.propertyValues[property]
if property != "" && value != "" {
if sb.Len() > 0 {
sb.WriteString(" ")
}
sb.WriteString(property + ": " + value + ";")
}
}
return sb.String()
}
func (st *Styles) Count() int {
return len(st.propertyValues)
}
func (st *Styles) Get(property string) string {
if value, ok := st.propertyValues[property]; ok {
return value
}
return ""
}
func (st *Styles) Set(property, value string) *Styles {
st.propertyValues[property] = value
return st
}
func (st *Styles) Clear() *Styles {
st.propertyValues = make(map[string]string)
return st
}
// string (or stringable) "parser"
func (st *Styles) Add(v ...any) *Styles {
for _, v := range v {
if s, ok := mttools.AnyToStringOk(v); ok {
for _, property := range strings.Split(s, ";") {
parts := strings.Split(property, ":")
if len(parts) == 2 {
st.Set(strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1]))
}
}
}
}
return st
}