/
picture.go
77 lines (68 loc) · 1.92 KB
/
picture.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
// picture is a goldmark extension to render images as html picture blocks
// instead of img tags in a paragraph
package picture
import (
"fmt"
"path"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/util"
)
var Picture = &Renderer{}
type Renderer struct{}
func (r *Renderer) Extend(m goldmark.Markdown) {
m.Renderer().AddOptions(
renderer.WithNodeRenderers(
util.Prioritized(r, 0),
),
)
}
func (r *Renderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {
reg.Register(ast.KindParagraph, r.renderParagraph)
reg.Register(ast.KindImage, r.renderImage)
}
func (r *Renderer) renderParagraph(w util.BufWriter, source []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {
var pic bool
if n.ChildCount() == 1 && n.FirstChild().Kind() == ast.KindImage {
pic = true
}
if entering {
if pic {
_, _ = w.WriteString("<picture ")
} else {
_, _ = w.WriteString("<p ")
}
if n.Attributes() != nil {
html.RenderAttributes(w, n, html.ParagraphAttributeFilter)
}
_ = w.WriteByte('>')
if pic {
_ = w.WriteByte('\n')
}
} else {
if n.ChildCount() == 1 && n.FirstChild().Kind() == ast.KindImage {
_, _ = w.WriteString("</picture>\n")
} else {
_, _ = w.WriteString("</p>\n")
}
}
return ast.WalkContinue, nil
}
func (r *Renderer) renderImage(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) {
if !entering {
return ast.WalkContinue, nil
}
n := node.(*ast.Image)
dst := string(n.Destination)
if strings.HasPrefix(dst, "/") {
ext := path.Ext(dst)
for _, e := range []string{".jpg", ".png", ".webp"} {
w.WriteString(fmt.Sprintf("<source srcset=%q>\n", strings.TrimSuffix(dst, ext)+e))
}
}
w.WriteString(fmt.Sprintf("<img src=%q alt=%q>\n", n.Destination, util.EscapeHTML(n.Text(source))))
return ast.WalkSkipChildren, nil
}