-
Notifications
You must be signed in to change notification settings - Fork 0
/
rendertext.go
58 lines (44 loc) · 958 Bytes
/
rendertext.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
package stork
import (
"regexp"
"strings"
"golang.org/x/net/html"
)
// Text renders a text version of the article.
func (a *Article) Text() string {
b := strings.Builder{}
var body *html.Node
iterate(a.output, func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "body" {
body = n
}
})
if body == nil {
return ""
}
iterate(body, func(n *html.Node) {
switch n.Type {
case html.ElementNode:
switch n.Data {
case "ul", "br", "p", "pre",
"h1", "h2", "h3", "h4", "h5", "h6":
b.WriteString("\n")
case "div":
if n.FirstChild != nil && n.FirstChild.Type == html.TextNode {
b.WriteString("\n")
}
}
if blockTags[n.Data] {
b.WriteString("\n")
}
if n.Data == "li" {
b.WriteString(" - ")
}
case html.TextNode:
b.WriteString(n.Data)
}
})
text := strings.TrimSpace(b.String())
regex := regexp.MustCompile("\n{3,}")
return regex.ReplaceAllString(text, "\n\n")
}