-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
renderer.go
98 lines (85 loc) · 2.14 KB
/
renderer.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
package main
import (
"bytes"
"io"
"github.com/russross/blackfriday/v2"
)
type renderer struct {
*blackfriday.HTMLRenderer
inTaskList bool
}
var (
checkedTag = []byte(`<input type="checkbox" checked="" disabled="">`)
uncheckedTag = []byte(`<input type="checkbox" disabled="">`)
taskListTagOpen = []byte(`<ul class="contains-task-list">`)
taskListTagClose = []byte(`</ul>`)
listItemTagOpen = []byte(`<li class="task-list-item">`)
listItemTagClose = []byte(`</li>`)
)
func newRenderer(params blackfriday.HTMLRendererParameters) *renderer {
return &renderer{
HTMLRenderer: blackfriday.NewHTMLRenderer(params),
}
}
func (r *renderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus {
switch node.Type {
case blackfriday.List:
if node.ListFlags == blackfriday.ListItemBeginningOfList {
if entering {
r.inTaskList = r.processTaskList(node)
if r.inTaskList {
w.Write(taskListTagOpen)
return blackfriday.GoToNext
}
} else {
r.inTaskList = false
}
}
case blackfriday.Item:
if r.inTaskList {
if entering {
w.Write(listItemTagOpen)
} else {
w.Write(listItemTagClose)
}
return blackfriday.GoToNext
}
case blackfriday.Text:
if r.inTaskList {
prefix := r.getTaskListItemPrefix(node)
if len(prefix) > 0 {
w.Write(prefix)
node.Literal = node.Literal[3:]
}
}
}
// fallback to blackfriday.Renderer
return r.HTMLRenderer.RenderNode(w, node, entering)
}
func (r *renderer) processTaskList(node *blackfriday.Node) bool {
cur := node.FirstChild
for cur != nil {
child := cur.FirstChild
if child.Type != blackfriday.Paragraph {
continue
}
child = child.FirstChild
if child.Type != blackfriday.Text {
continue
}
prefix := r.getTaskListItemPrefix(child)
if len(prefix) > 0 {
return true
}
cur = cur.Next
}
return false
}
func (r *renderer) getTaskListItemPrefix(node *blackfriday.Node) []byte {
if bytes.HasPrefix(node.Literal, []byte("[ ] ")) {
return uncheckedTag
} else if bytes.HasPrefix(node.Literal, []byte("[x] ")) || bytes.HasPrefix(node.Literal, []byte("[X] ")) {
return checkedTag
}
return []byte{}
}