/
html.go
334 lines (300 loc) · 8.49 KB
/
html.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
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package md
import (
"bytes"
"strings"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
var (
// headerLevel maps HTML tags to their level in parser.HeaderNode.
// we -1 as H2 is a new step
headerLevel = map[atom.Atom]int{
atom.H3: 2,
atom.H4: 3,
atom.H5: 4,
atom.H6: 5,
}
)
// isHeader returns true if hn is one of secondary headers.
// Step header is not one of them.
func isHeader(hn *html.Node) bool {
_, ok := headerLevel[hn.DataAtom]
return ok
}
// TODO rename, it only captures some meta. Maybe redo the meta system?
func isMeta(hn *html.Node) bool {
elem := strings.ToLower(hn.Data)
return strings.HasPrefix(elem, metaDuration+metaSep) || strings.HasPrefix(elem, metaEnvironment+metaSep)
}
func isBold(hn *html.Node) bool {
if hn.Type == html.TextNode {
hn = hn.Parent
} else if hn.DataAtom == atom.Code {
// Look up as many as 2 levels, to handle the case of e.g. <bold><em><code>
for i := 0; i < 2; i++ {
hn = hn.Parent
if hn.DataAtom == atom.Strong || hn.DataAtom == atom.B {
return true
}
}
return false
}
return hn.DataAtom == atom.Strong ||
hn.DataAtom == atom.B
}
func isItalic(hn *html.Node) bool {
if hn.Type == html.TextNode {
hn = hn.Parent
} else if hn.DataAtom == atom.Code {
// Look up as many as 2 levels, to handle the case of e.g. <em><bold><code>
for i := 0; i < 2; i++ {
hn = hn.Parent
if hn.DataAtom == atom.Em || hn.DataAtom == atom.I {
return true
}
}
return false
}
return hn.DataAtom == atom.Em ||
hn.DataAtom == atom.I
}
// This is different to calling isBold and isItalic separately as we must look
// up an extra level in the tree
func isBoldAndItalic(hn *html.Node) bool {
if hn.Parent == nil || hn.Parent.Parent == nil {
return false
}
if hn.Type == html.TextNode {
hn = hn.Parent
}
return (isItalic(hn) && isBold(hn.Parent)) || (isItalic(hn.Parent) && isBold(hn))
}
func isConsole(hn *html.Node) bool {
if hn.Type == html.TextNode {
hn = hn.Parent
}
if hn.DataAtom == atom.Code {
for _, a := range hn.Attr {
if a.Key == "class" && a.Val == "language-console" {
return true
}
}
}
return false
}
func isCode(hn *html.Node) bool {
if hn.Type == html.TextNode {
hn = hn.Parent
}
return hn.DataAtom == atom.Code && !isConsole(hn)
}
func isButton(hn *html.Node) bool {
return hn.DataAtom == atom.Button
}
func isAside(hn *html.Node) bool {
return hn.DataAtom == atom.Aside
}
func isNewAside(hn *html.Node) bool {
if hn.DataAtom != atom.Blockquote ||
hn.FirstChild == nil ||
hn.FirstChild.NextSibling == nil ||
hn.FirstChild.NextSibling.FirstChild == nil {
return false
}
asideText := strings.ToLower(hn.FirstChild.NextSibling.FirstChild.Data)
return strings.HasPrefix(asideText, "aside positive") || strings.HasPrefix(asideText, "aside negative")
}
func isInfobox(hn *html.Node) bool {
if hn.DataAtom != atom.Dt {
return false
}
return strings.ToLower(hn.FirstChild.Data) == "positive" || isInfoboxNegative(hn)
}
func isInfoboxNegative(hn *html.Node) bool {
if hn.DataAtom != atom.Dt {
return false
}
return strings.ToLower(hn.FirstChild.Data) == "negative"
}
func isSurvey(hn *html.Node) bool {
if hn.DataAtom != atom.Form {
return false
}
if findAtom(hn, atom.Name) == nil {
return false
}
if len(findChildAtoms(hn, atom.Input)) == 0 {
return false
}
return true
}
// TODO Write an explanation for why the countTwo checks are necessary.
func isTable(hn *html.Node) bool {
if hn.DataAtom != atom.Table {
return false
}
// TODO if =1 is fine, can we sub findAtom?
return countTwo(hn, atom.Tr) >= 1 || countTwo(hn, atom.Td) >= 1
}
func isList(hn *html.Node) bool {
return hn.DataAtom == atom.Ul || hn.DataAtom == atom.Ol
}
func isYoutube(hn *html.Node) bool {
return hn.DataAtom == atom.Video
}
func isFragmentImport(hn *html.Node) bool {
return hn.DataAtom == 0 && strings.HasPrefix(hn.Data, convertedImportsDataPrefix)
}
// countTwo starts counting the number of a Atom children in hn.
// It returns as soon as the count exceeds 1, so the returned value is inexact.
//
// The callers can test for > 1 to verify whether a node contains two
// or more children of the Atom a.
func countTwo(hn *html.Node, a atom.Atom) int {
var count int
for c := hn.FirstChild; c != nil; c = c.NextSibling {
if c.DataAtom == a {
count++
} else {
count += countTwo(c, a)
}
if count > 1 {
break
}
}
return count
}
// countDirect returns the number of immediate children of hn.
func countDirect(hn *html.Node) int {
var count int
for c := hn.FirstChild; c != nil; c = c.NextSibling {
count++
}
return count
}
// findAtom returns first child of root which matches a, nil otherwise.
// It returns root if it is the same Atom as a.
func findAtom(root *html.Node, a atom.Atom) *html.Node {
if root.DataAtom == a {
return root
}
for c := root.FirstChild; c != nil; c = c.NextSibling {
if v := findAtom(c, a); v != nil {
return v
}
}
return nil
}
// TODO reuse code with findAtom?
func findChildAtoms(root *html.Node, a atom.Atom) []*html.Node {
var nodes []*html.Node
for hn := root.FirstChild; hn != nil; hn = hn.NextSibling {
if hn.DataAtom == a {
nodes = append(nodes, hn)
}
nodes = append(nodes, findChildAtoms(hn, a)...)
}
return nodes
}
type considerSelf int
const (
doNotConsiderSelf considerSelf = iota
doConsiderSelf
)
// findNearestAncestor finds the nearest ancestor of the given node of any of the given atoms.
// A pointer to the ancestor is returned, or nil if none are found.
// If doConsiderSelf is passed, the given node itself counts as an ancestor for our purposes.
func findNearestAncestor(n *html.Node, atoms map[atom.Atom]struct{}, cs considerSelf) *html.Node {
if _, ok := atoms[n.DataAtom]; cs == doConsiderSelf && ok {
return n
}
for p := n.Parent; p != nil; p = p.Parent {
if _, ok := atoms[p.DataAtom]; ok {
return p
}
}
return nil
}
var blockParents = map[atom.Atom]struct{}{
atom.H1: {},
atom.H2: {},
atom.H3: {},
atom.H4: {},
atom.H5: {},
atom.H6: {},
atom.Li: {},
atom.P: {},
atom.Div: {},
}
// findNearestBlockAncestor finds the nearest ancestor node of a block atom.
// For instance, block parent of "text" in <ul><li>text</li></ul> is <li>,
// while block parent of "text" in <p><span>text</span></p> is <p>.
// The node passed in itself is never considered.
// A pointer to the ancestor is returned, or nil if none are found.
func findNearestBlockAncestor(n *html.Node) *html.Node {
return findNearestAncestor(n, blockParents, doNotConsiderSelf)
}
// nodeAttr checks the given node's HTML attributes for the given key.
// The corresponding value is returned, or the empty string if the key is not found.
// Keys are case insensitive.
func nodeAttr(n *html.Node, key string) string {
key = strings.ToLower(key)
for _, attr := range n.Attr {
if strings.ToLower(attr.Key) == key {
return attr.Val
}
}
return ""
}
// TODO divide into smaller functions
// TODO redo comment, more than just text nodes are handled and atom.A
// TODO should we really have trim?
// TODO part of why this is weird is because the processing is split across root and child nodes. could restructure
// stringifyNode extracts and concatenates all text nodes starting with root.
// Line breaks are inserted at <br> and any non-<span> elements.
func stringifyNode(root *html.Node, trim bool) string {
if root.Type == html.TextNode {
s := textCleaner.Replace(root.Data)
s = strings.Replace(s, "\n", " ", -1)
if !trim {
return s
}
return strings.TrimSpace(s)
}
if root.DataAtom == atom.Br && !trim {
return "\n"
}
var buf bytes.Buffer
for c := root.FirstChild; c != nil; c = c.NextSibling {
if c.DataAtom == atom.Br {
buf.WriteRune('\n')
continue
}
if c.Type == html.TextNode {
buf.WriteString(c.Data)
continue
}
if c.DataAtom != atom.Span && c.DataAtom != atom.A {
buf.WriteRune('\n')
}
buf.WriteString(stringifyNode(c, false))
}
s := textCleaner.Replace(buf.String())
if !trim {
return s
}
return strings.TrimSpace(s)
}