-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathrenderer.go
83 lines (66 loc) · 1.77 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
package katex
import (
"bytes"
"github.com/bluele/gcache"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
)
type HTMLRenderer struct {
html.Config
cacheInline gcache.Cache
cacheDisplay gcache.Cache
}
func (r *HTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(KindInline, r.renderInline)
reg.Register(KindBlock, r.renderBlock)
}
func (r *HTMLRenderer) renderInline(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
if entering {
node := n.(*Inline)
html, err := r.cacheInline.Get(string(node.Equation))
if err == nil {
w.Write(html.([]byte))
return ast.WalkContinue, nil
}
if err == gcache.KeyNotFoundError {
b := bytes.Buffer{}
err = Render(&b, node.Equation, false)
if err != nil {
return ast.WalkStop, err
}
html := b.Bytes()
w.Write(html)
r.cacheInline.Set(string(node.Equation), html)
return ast.WalkContinue, nil
}
return ast.WalkStop, err
}
return ast.WalkContinue, nil
}
func (r *HTMLRenderer) renderBlock(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
if entering {
node := n.(*Block)
html, err := r.cacheDisplay.Get(string(node.Equation))
if err == nil {
w.Write(html.([]byte))
return ast.WalkContinue, nil
}
if err == gcache.KeyNotFoundError {
b := bytes.Buffer{}
err = Render(&b, node.Equation, true)
if err != nil {
return ast.WalkStop, err
}
html := b.Bytes()
w.WriteString("<div>")
w.Write(html)
w.WriteString("</div>")
r.cacheDisplay.Set(string(node.Equation), html)
return ast.WalkContinue, nil
}
return ast.WalkStop, err
}
return ast.WalkContinue, nil
}