-
Notifications
You must be signed in to change notification settings - Fork 0
/
hookedrenderer.go
366 lines (323 loc) · 9.98 KB
/
hookedrenderer.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
359
360
361
362
363
364
365
366
package valueobject
import (
"bytes"
"github.com/gohugonet/hugoverse/internal/domain/markdown"
"github.com/gohugonet/hugoverse/pkg/types/hstring"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
"strings"
)
type hookedRenderer struct {
linkifyProtocol []byte
html.Config
}
func (r *hookedRenderer) SetOption(name renderer.OptionName, value any) {
r.Config.SetOption(name, value)
}
// RegisterFuncs implements NodeRenderer.RegisterFuncs.
func (r *hookedRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(ast.KindLink, r.renderLink)
reg.Register(ast.KindAutoLink, r.renderAutoLink)
reg.Register(ast.KindImage, r.renderImage)
reg.Register(ast.KindHeading, r.renderHeading)
}
func (r *hookedRenderer) renderImage(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Image)
var lr markdown.LinkRenderer
ctx, ok := w.(*Context)
if ok {
h := ctx.RenderContext().GetRenderer(markdown.ImageRendererType, nil)
ok = h != nil
if ok {
lr = h.(markdown.LinkRenderer)
}
}
if !ok {
return r.renderImageDefault(w, source, node, entering)
}
if entering {
// Store the current pos so we can capture the rendered text.
ctx.PushPos(ctx.Buffer.Len())
return ast.WalkContinue, nil
}
pos := ctx.PopPos()
text := ctx.Buffer.Bytes()[pos:]
ctx.Buffer.Truncate(pos)
var (
isBlock bool
ordinal int
)
if b, ok := n.AttributeString(ImageAttrIsBlock); ok && b.(bool) {
isBlock = true
}
if n, ok := n.AttributeString(ImageAttrOrdinal); ok {
ordinal = n.(int)
}
// We use the attributes to signal from the parser whether the images is in
// a block context or not.
// We may find a better way to do that, but for now, we'll need to remove any
// internal attributes before rendering.
attrs := r.filterInternalAttributes(n.Attributes())
err := lr.RenderLink(
ctx.RenderContext().Ctx,
w,
imageLinkContext{
linkContext: linkContext{
page: ctx.DocumentContext().Document,
destination: string(n.Destination),
title: string(n.Title),
text: hstring.RenderedString(text),
plainText: string(n.Text(source)),
AttributesHolder: NewAttr(attrs, AttributesOwnerGeneral),
},
ordinal: ordinal,
isBlock: isBlock,
},
)
return ast.WalkContinue, err
}
const (
internalAttrPrefix = "_h__"
)
func (r *hookedRenderer) filterInternalAttributes(attrs []ast.Attribute) []ast.Attribute {
n := 0
for _, x := range attrs {
if !bytes.HasPrefix(x.Name, []byte(internalAttrPrefix)) {
attrs[n] = x
n++
}
}
return attrs[:n]
}
// Fall back to the default Goldmark render funcs. Method below borrowed from:
// https://github.com/yuin/goldmark/blob/b611cd333a492416b56aa8d94b04a67bf0096ab2/renderer/html/html.go#L404
func (r *hookedRenderer) renderImageDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
n := node.(*ast.Image)
_, _ = w.WriteString("<img src=\"")
if r.Unsafe || !html.IsDangerousURL(n.Destination) {
_, _ = w.Write(util.EscapeHTML(util.URLEscape(n.Destination, true)))
}
_, _ = w.WriteString(`" alt="`)
_, _ = w.Write(nodeToHTMLText(n, source))
_ = w.WriteByte('"')
if n.Title != nil {
_, _ = w.WriteString(` title="`)
r.Writer.Write(w, n.Title)
_ = w.WriteByte('"')
}
if n.Attributes() != nil {
attrs := r.filterInternalAttributes(n.Attributes())
RenderASTAttributes(w, attrs...)
}
if r.XHTML {
_, _ = w.WriteString(" />")
} else {
_, _ = w.WriteString(">")
}
return ast.WalkSkipChildren, nil
}
// Borrowed from Goldmark.
func nodeToHTMLText(n ast.Node, source []byte) []byte {
var buf bytes.Buffer
for c := n.FirstChild(); c != nil; c = c.NextSibling() {
if s, ok := c.(*ast.String); ok && s.IsCode() {
buf.Write(s.Text(source))
} else if !c.HasChildren() {
buf.Write(util.EscapeHTML(c.Text(source)))
if t, ok := c.(*ast.Text); ok && t.SoftLineBreak() {
buf.WriteByte('\n')
}
} else {
buf.Write(nodeToHTMLText(c, source))
}
}
return buf.Bytes()
}
func (r *hookedRenderer) renderLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Link)
var lr markdown.LinkRenderer
ctx, ok := w.(*Context)
if ok {
h := ctx.RenderContext().GetRenderer(markdown.LinkRendererType, nil)
ok = h != nil
if ok {
lr = h.(markdown.LinkRenderer)
}
}
if !ok {
return r.renderLinkDefault(w, source, node, entering)
}
if entering {
// Store the current pos so we can capture the rendered text.
ctx.PushPos(ctx.Buffer.Len())
return ast.WalkContinue, nil
}
pos := ctx.PopPos()
text := ctx.Buffer.Bytes()[pos:]
ctx.Buffer.Truncate(pos)
err := lr.RenderLink(
ctx.RenderContext().Ctx,
w,
linkContext{
page: ctx.DocumentContext().Document,
destination: string(n.Destination),
title: string(n.Title),
text: hstring.RenderedString(text),
plainText: string(n.Text(source)),
AttributesHolder: EmptyAttr,
},
)
return ast.WalkContinue, err
}
// Fall back to the default Goldmark render funcs. Method below borrowed from:
// https://github.com/yuin/goldmark/blob/b611cd333a492416b56aa8d94b04a67bf0096ab2/renderer/html/html.go#L404
func (r *hookedRenderer) renderLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Link)
if entering {
_, _ = w.WriteString("<a href=\"")
if r.Unsafe || !html.IsDangerousURL(n.Destination) {
_, _ = w.Write(util.EscapeHTML(util.URLEscape(n.Destination, true)))
}
_ = w.WriteByte('"')
if n.Title != nil {
_, _ = w.WriteString(` title="`)
r.Writer.Write(w, n.Title)
_ = w.WriteByte('"')
}
_ = w.WriteByte('>')
} else {
_, _ = w.WriteString("</a>")
}
return ast.WalkContinue, nil
}
func (r *hookedRenderer) renderAutoLink(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
n := node.(*ast.AutoLink)
var lr markdown.LinkRenderer
ctx, ok := w.(*Context)
if ok {
h := ctx.RenderContext().GetRenderer(markdown.LinkRendererType, nil)
ok = h != nil
if ok {
lr = h.(markdown.LinkRenderer)
}
}
if !ok {
return r.renderAutoLinkDefault(w, source, node, entering)
}
url := string(r.autoLinkURL(n, source))
label := string(n.Label(source))
if n.AutoLinkType == ast.AutoLinkEmail && !strings.HasPrefix(strings.ToLower(url), "mailto:") {
url = "mailto:" + url
}
err := lr.RenderLink(
ctx.RenderContext().Ctx,
w,
linkContext{
page: ctx.DocumentContext().Document,
destination: url,
text: hstring.RenderedString(label),
plainText: label,
AttributesHolder: EmptyAttr,
},
)
return ast.WalkContinue, err
}
// Fall back to the default Goldmark render funcs. Method below borrowed from:
// https://github.com/yuin/goldmark/blob/5588d92a56fe1642791cf4aa8e9eae8227cfeecd/renderer/html/html.go#L439
func (r *hookedRenderer) renderAutoLinkDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.AutoLink)
if !entering {
return ast.WalkContinue, nil
}
_, _ = w.WriteString(`<a href="`)
url := r.autoLinkURL(n, source)
label := n.Label(source)
if n.AutoLinkType == ast.AutoLinkEmail && !bytes.HasPrefix(bytes.ToLower(url), []byte("mailto:")) {
_, _ = w.WriteString("mailto:")
}
_, _ = w.Write(util.EscapeHTML(util.URLEscape(url, false)))
if n.Attributes() != nil {
_ = w.WriteByte('"')
html.RenderAttributes(w, n, html.LinkAttributeFilter)
_ = w.WriteByte('>')
} else {
_, _ = w.WriteString(`">`)
}
_, _ = w.Write(util.EscapeHTML(label))
_, _ = w.WriteString(`</a>`)
return ast.WalkContinue, nil
}
func (r *hookedRenderer) autoLinkURL(n *ast.AutoLink, source []byte) []byte {
url := n.URL(source)
if len(n.Protocol) > 0 && !bytes.Equal(n.Protocol, r.linkifyProtocol) {
// The CommonMark spec says "http" is the correct protocol for links,
// but this doesn't make much sense (the fact that they should care about the rendered output).
// Note that n.Protocol is not set if protocol is provided by user.
url = append(r.linkifyProtocol, url[len(n.Protocol):]...)
}
return url
}
func (r *hookedRenderer) renderHeading(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Heading)
var hr markdown.HeadingRenderer
ctx, ok := w.(*Context)
if ok {
h := ctx.RenderContext().GetRenderer(markdown.HeadingRendererType, nil)
ok = h != nil
if ok {
hr = h.(markdown.HeadingRenderer)
}
}
if !ok {
return r.renderHeadingDefault(w, source, node, entering)
}
if entering {
// Store the current pos so we can capture the rendered text.
ctx.PushPos(ctx.Buffer.Len())
return ast.WalkContinue, nil
}
pos := ctx.PopPos()
text := ctx.Buffer.Bytes()[pos:]
ctx.Buffer.Truncate(pos)
// All ast.Heading nodes are guaranteed to have an attribute called "id"
// that is an array of bytes that encode a valid string.
anchori, _ := n.AttributeString("id")
anchor := anchori.([]byte)
err := hr.RenderHeading(
ctx.RenderContext().Ctx,
w,
headingContext{
page: ctx.DocumentContext().Document,
level: n.Level,
anchor: string(anchor),
text: hstring.RenderedString(text),
plainText: string(n.Text(source)),
AttributesHolder: NewAttr(n.Attributes(), AttributesOwnerGeneral),
},
)
return ast.WalkContinue, err
}
func (r *hookedRenderer) renderHeadingDefault(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
n := node.(*ast.Heading)
if entering {
_, _ = w.WriteString("<h")
_ = w.WriteByte("0123456"[n.Level])
if n.Attributes() != nil {
RenderASTAttributes(w, node.Attributes()...)
}
_ = w.WriteByte('>')
} else {
_, _ = w.WriteString("</h")
_ = w.WriteByte("0123456"[n.Level])
_, _ = w.WriteString(">\n")
}
return ast.WalkContinue, nil
}