-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
79 lines (66 loc) · 1.38 KB
/
util.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
package readability
import (
"bytes"
"slices"
"github.com/andybalholm/cascadia"
"golang.org/x/net/html"
)
func indexOf[T any](el *T, a []*T) int {
return slices.IndexFunc(a, func(ell *T) bool {
return ell == el
})
}
func delete[T any](idx int, a []*T) []*T {
copy(a[idx:], a[idx+1:])
a[len(a)-1] = nil
a = a[:len(a)-1]
return a
}
func insert(newNode *Node, idx int, nodes []*Node) []*Node {
nodes = append(nodes[:idx], append([]*Node{newNode}, nodes[idx:]...)...)
return nodes
}
func anyOf(strings ...string) string {
for _, s := range strings {
if s != "" {
return s
}
}
return ""
}
func querySelectorAll(n *html.Node, query string) []*html.Node {
sel, err := cascadia.ParseGroup(query)
if err != nil {
return nil
}
return cascadia.QueryAll(n, sel)
}
func matches(n *html.Node, query string) bool {
sel, err := cascadia.Parse(query)
if err != nil {
return false
}
return cascadia.Query(n, sel) != nil
}
func attr(n *html.Node, attrName string) string {
for _, a := range n.Attr {
if a.Key == attrName {
return a.Val
}
}
return ""
}
func textContent(n *html.Node) string {
var buf bytes.Buffer
var getText func(*html.Node)
getText = func(n *html.Node) {
if n.Type == html.TextNode {
buf.WriteString(n.Data)
}
for child := n.FirstChild; child != nil; child = child.NextSibling {
getText(child)
}
}
getText(n)
return buf.String()
}