-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhelpers.go
358 lines (291 loc) · 8.49 KB
/
helpers.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package readability
import (
"bytes"
"net/url"
"strings"
"golang.org/x/net/html"
)
// firstElementChild returns the object's first child Element, or nil if there
// are no child elements.
func firstElementChild(node *html.Node) *html.Node {
for child := node.FirstChild; child != nil; child = child.NextSibling {
if child.Type == html.ElementNode {
return child
}
}
return nil
}
// nextElementSibling returns the Element immediately following the specified
// one in its parent's children list, or nil if the specified Element is the
// last one in the list.
func nextElementSibling(node *html.Node) *html.Node {
for sibling := node.NextSibling; sibling != nil; sibling = sibling.NextSibling {
if sibling.Type == html.ElementNode {
return sibling
}
}
return nil
}
// appendChild adds a node to the end of the list of children of a specified
// parent node. If the given child is a reference to an existing node in the
// document, appendChild moves it from its current position to the new position
// (there is no requirement to remove the node from its parent node before
// appending it to some other node).
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild
func appendChild(node *html.Node, child *html.Node) {
if child.Parent != nil {
temp := cloneNode(child)
node.AppendChild(temp)
child.Parent.RemoveChild(child)
return
}
node.AppendChild(child)
}
// childNodes returns list of a node's direct children.
func childNodes(node *html.Node) []*html.Node {
var list []*html.Node
for c := node.FirstChild; c != nil; c = c.NextSibling {
list = append(list, c)
}
return list
}
// includeNode determines if node is included inside nodeList.
func includeNode(nodeList []*html.Node, node *html.Node) bool {
for i := 0; i < len(nodeList); i++ {
if nodeList[i] == node {
return true
}
}
return false
}
// cloneNode returns a duplicate of the node on which this method was called.
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode
func cloneNode(node *html.Node) *html.Node {
clone := &html.Node{
Type: node.Type,
DataAtom: node.DataAtom,
Data: node.Data,
Attr: make([]html.Attribute, len(node.Attr)),
}
copy(clone.Attr, node.Attr)
for c := node.FirstChild; c != nil; c = c.NextSibling {
clone.AppendChild(cloneNode(c))
}
return clone
}
// createElement creates the HTML element specified by tagName.
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement
func createElement(tagName string) *html.Node {
return &html.Node{Type: html.ElementNode, Data: tagName}
}
// createTextNode creates a new Text node.
func createTextNode(data string) *html.Node {
return &html.Node{Type: html.TextNode, Data: data}
}
// getElementsByTagName returns a collection of HTML elements with the given
// tag name. If tag name is an asterisk, a list of all the available HTML nodes
// will be returned instead.
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName
func getElementsByTagName(node *html.Node, tag string) []*html.Node {
var lst []*html.Node
var fun func(*html.Node)
fun = func(n *html.Node) {
if n.Type == html.ElementNode && (tag == "*" || n.Data == tag) {
lst = append(lst, n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
fun(c)
}
}
fun(node)
return lst
}
// getAttribute returns the value of a specified attribute on the element. If
// the given attribute does not exist, the function returns an empty string.
func getAttribute(node *html.Node, attrName string) string {
for i := 0; i < len(node.Attr); i++ {
if node.Attr[i].Key == attrName {
return node.Attr[i].Val
}
}
return ""
}
// setAttribute sets attribute for node. If attribute already exists, it will
// be replaced.
func setAttribute(node *html.Node, attrName string, attrValue string) {
attrIdx := -1
for i := 0; i < len(node.Attr); i++ {
if node.Attr[i].Key == attrName {
attrIdx = i
break
}
}
if attrIdx >= 0 {
node.Attr[attrIdx].Val = attrValue
return
}
node.Attr = append(node.Attr, html.Attribute{
Key: attrName,
Val: attrValue,
})
}
// removeAttribute removes attribute with given name.
func removeAttribute(node *html.Node, attrName string) {
attrIdx := -1
for i := 0; i < len(node.Attr); i++ {
if node.Attr[i].Key == attrName {
attrIdx = i
break
}
}
if attrIdx >= 0 {
a := node.Attr
a = append(a[:attrIdx], a[attrIdx+1:]...)
node.Attr = a
}
}
// hasAttribute returns a Boolean value indicating whether the specified node
// has the specified attribute or not.
func hasAttribute(node *html.Node, attrName string) bool {
for i := 0; i < len(node.Attr); i++ {
if node.Attr[i].Key == attrName {
return true
}
}
return false
}
// outerHTML returns an HTML serialization of the element and its descendants.
func outerHTML(node *html.Node) string {
var buffer bytes.Buffer
if err := html.Render(&buffer, node); err != nil {
return ""
}
return buffer.String()
}
// innerHTML returns the HTML content (inner HTML) of an element.
func innerHTML(node *html.Node) string {
var err error
var buffer bytes.Buffer
for child := node.FirstChild; child != nil; child = child.NextSibling {
if err = html.Render(&buffer, child); err != nil {
return ""
}
}
return strings.TrimSpace(buffer.String())
}
// documentElement returns the root element of the document.
func documentElement(doc *html.Node) *html.Node {
nodes := getElementsByTagName(doc, "html")
if len(nodes) > 0 {
return nodes[0]
}
return nil
}
// className returns the value of the class attribute of the element.
func className(node *html.Node) string {
className := getAttribute(node, "class")
className = strings.TrimSpace(className)
className = rxNormalize.ReplaceAllString(className, "\x20")
return className
}
// id returns the value of the id attribute of the specified element.
func id(node *html.Node) string {
id := getAttribute(node, "id")
id = strings.TrimSpace(id)
return id
}
// children returns an HTMLCollection of the child elements of Node.
func children(node *html.Node) []*html.Node {
var children []*html.Node
if node == nil {
return nil
}
for child := node.FirstChild; child != nil; child = child.NextSibling {
if child.Type == html.ElementNode {
children = append(children, child)
}
}
return children
}
// wordCount returns number of word in str.
func wordCount(str string) int {
return len(strings.Fields(str))
}
// indexOf returns the first index at which a given element can be found in the
// array, or -1 if it is not present.
func indexOf(array []string, key string) int {
for idx, val := range array {
if val == key {
return idx
}
}
return -1
}
// replaceNode replaces a child node within the given (parent) node.
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
func replaceNode(oldNode *html.Node, newNode *html.Node) {
if oldNode.Parent == nil {
return
}
newNode.Parent = nil
newNode.PrevSibling = nil
newNode.NextSibling = nil
oldNode.Parent.InsertBefore(newNode, oldNode)
oldNode.Parent.RemoveChild(oldNode)
}
// tagName returns the tag name of the element on which it’s called.
//
// For example, if the element is an <img>, its tagName property is “IMG” (for
// HTML documents; it may be cased differently for XML/XHTML documents).
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName
func tagName(node *html.Node) string {
if node.Type != html.ElementNode {
return ""
}
return node.Data
}
// textContent returns text content of a Node and its descendants.
//
// See: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
func textContent(node *html.Node) string {
var buffer bytes.Buffer
var finder func(*html.Node)
finder = func(n *html.Node) {
if n.Type == html.TextNode {
buffer.WriteString(n.Data)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
finder(c)
}
}
finder(node)
return buffer.String()
}
// toAbsoluteURI convert uri to absolute path based on base.
// However, if uri is prefixed with hash (#), the uri won't be changed.
func toAbsoluteURI(uri string, base *url.URL) string {
if uri == "" || base == nil {
return ""
}
// If it is hash tag, return as it is
if uri[:1] == "#" {
return uri
}
// If it is already an absolute URL, return as it is
tmp, err := url.ParseRequestURI(uri)
if err == nil && tmp.Scheme != "" && tmp.Hostname() != "" {
return uri
}
// Otherwise, resolve against base URI.
tmp, err = url.Parse(uri)
if err != nil {
return uri
}
return base.ResolveReference(tmp).String()
}