[READ-ONLY] Mirror of https://github.com/andrioid/humle. Write HTML with Go functions
1package humle
2
3import (
4 "slices"
5 "strings"
6)
7
8type Attributes map[string]attribute
9
10func MergeAttributes(a Attributes, attrs []attribute) Attributes {
11 for _, v := range attrs {
12 a.Set(v.name, v)
13 }
14 return a
15}
16
17// Sets or merges (according to merge strategy) an attribute
18func (a Attributes) Set(k string, newAttribute attribute) {
19
20 // If attribute already exists, we need to merge it
21 if existing, ok := (a)[k]; ok {
22 // Using the overriding attribute's merge function we merge with the existing value
23 // - This has the advantage of merging with classes that don't use merge
24 newValue := newAttribute.Merge(existing.value, newAttribute.value)
25 existing.value = newValue
26 (a)[k] = existing
27 return
28 }
29 (a)[k] = newAttribute
30}
31
32func (a Attributes) String() string {
33 var attributes = make([]attribute, len(a))
34 for _, attr := range a {
35 attributes = append(attributes, attr)
36 }
37 slices.SortFunc(attributes, func(a, b attribute) int {
38 if a.name == "id" {
39 return -1
40 }
41 if b.name == "id" {
42 return 1
43 }
44 if n := strings.Compare(a.name, b.name); n != 0 {
45 return n
46 }
47 return 0
48 })
49 attrStrings := []string{}
50 for _, as := range attributes {
51 str := as.String()
52 if str != "" {
53 attrStrings = append(attrStrings, str)
54 }
55
56 }
57
58 return strings.Join(attrStrings, " ")
59}