-
Notifications
You must be signed in to change notification settings - Fork 0
/
default_funcs.go
121 lines (91 loc) · 2.27 KB
/
default_funcs.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
118
119
120
121
package layout
import (
"bytes"
"html/template"
"github.com/Masterminds/sprig/v3"
"github.com/andybalholm/cascadia"
"github.com/pkg/errors"
"golang.org/x/net/html"
)
func DefaultFuncs() template.FuncMap {
funcs := sprig.FuncMap()
funcs["htmlQueryAll"] = htmlQueryAll
funcs["htmlSplit"] = htmlSplit
return funcs
}
func htmlQueryAll(rawHTML template.HTML, query string) ([]template.HTML, error) {
buff := bytes.NewBuffer([]byte(rawHTML))
root, err := html.Parse(buff)
if err != nil {
return nil, errors.WithStack(err)
}
selector, err := cascadia.Compile(query)
if err != nil {
return nil, errors.WithStack(err)
}
nodes := selector.MatchAll(root)
elements := make([]template.HTML, 0, len(nodes))
for _, n := range nodes {
var el bytes.Buffer
if err := html.Render(&el, n); err != nil {
return nil, errors.WithStack(err)
}
elements = append(elements, template.HTML(el.String()))
}
return elements, nil
}
func htmlSplit(rawHTML template.HTML, query string) ([]template.HTML, error) {
buff := bytes.NewBuffer([]byte(rawHTML))
root, err := html.Parse(buff)
if err != nil {
return nil, errors.WithStack(err)
}
bodySelector, err := cascadia.Compile("body")
if err != nil {
return nil, errors.WithStack(err)
}
elements := make([]template.HTML, 0)
body := bodySelector.MatchFirst(root)
if body == nil {
return elements, nil
}
splitSelector, err := cascadia.Compile(query)
if err != nil {
return nil, errors.WithStack(err)
}
appendBlock := func(block []html.Node) error {
var el bytes.Buffer
for _, n := range block {
if n.Type == html.ErrorNode {
continue
}
if err := html.Render(&el, &n); err != nil {
return errors.WithStack(err)
}
}
elements = append(elements, template.HTML(el.String()))
return nil
}
currentBlock := make([]html.Node, 0)
child := body.FirstChild
for {
if child == nil {
break
}
matches := splitSelector.Match(child)
if !matches {
currentBlock = append(currentBlock, *child)
child = child.NextSibling
continue
}
if err := appendBlock(currentBlock); err != nil {
return nil, errors.WithStack(err)
}
clear(currentBlock)
child = child.NextSibling
}
if err := appendBlock(currentBlock); err != nil {
return nil, errors.WithStack(err)
}
return elements, nil
}