-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
attributes.go
117 lines (92 loc) · 1.99 KB
/
attributes.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
package hype
import (
"fmt"
"regexp"
"strings"
"github.com/markbates/syncx"
"golang.org/x/net/html"
)
type AttrNode interface {
Node
Attrs() *Attributes
}
type Attributes = syncx.Map[string, string]
// ConvertHTMLAttrs converts a slice of HTML attributes
// to a new Attributes type.
func ConvertHTMLAttrs(attrs []html.Attribute) (*Attributes, error) {
ats := &Attributes{}
for _, a := range attrs {
if err := ats.Set(a.Key, a.Val); err != nil {
return nil, err
}
}
return ats, nil
}
// AttrMatches returns true if the given keys and values in the
// query map are present, and equal, in the given attributes.
// A `*` matches any value.
func AttrMatches(ats *Attributes, query map[string]string) bool {
if ats == nil {
return false
}
for k, v := range query {
av, ok := ats.Get(k)
if !ok {
return false
}
if v == "*" {
continue
}
if len(av) == 0 || len(v) == 0 {
return false
}
rx, err := regexp.Compile(v)
if err != nil {
return false
}
if !rx.MatchString(av) {
return false
}
}
return true
}
// Language tries to determine the language of the given
// set of attributes.
// - "language" is the first attr tested.
// - "language-*" is the second attr tested. (e.g. "language-go", "language-js")
// - "lang" is the third attr tested.
func Language(ats *Attributes, lang string) string {
if ats == nil {
return lang
}
if l, ok := ats.Get("language"); ok {
if len(l) > 0 {
return l
}
}
var l string
ats.Range(func(k, v string) bool {
if !strings.HasPrefix(v, "language-") {
return true
}
l = strings.TrimPrefix(v, "language-")
return false
})
if len(l) > 0 {
return l
}
if l, ok := ats.Get("lang"); ok {
if len(l) > 0 {
return l
}
}
return lang
}
type ErrAttrNotFound string
func (e ErrAttrNotFound) Error() string {
return fmt.Sprintf("attribute %q not found", string(e))
}
type ErrAttrEmpty string
func (e ErrAttrEmpty) Error() string {
return fmt.Sprintf("attribute %q is empty", string(e))
}