-
Notifications
You must be signed in to change notification settings - Fork 1
/
md.go
108 lines (93 loc) · 2.35 KB
/
md.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
package templum
import (
"bytes"
"context"
"io"
d2 "github.com/FurqanSoftware/goldmark-d2"
"github.com/a-h/templ"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
fences "github.com/stefanfritsch/goldmark-fences"
"github.com/yuin/goldmark"
highlighting "github.com/yuin/goldmark-highlighting/v2"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/renderer/html"
"go.abhg.dev/goldmark/anchor"
"go.abhg.dev/goldmark/mermaid"
"mvdan.cc/xurls/v2"
"oss.terrastruct.com/d2/d2layouts/d2elklayout"
"oss.terrastruct.com/d2/d2themes/d2themescatalog"
)
func md2html(config map[string]string, md string) (string, error) {
var htmlBuffer bytes.Buffer
d2Settings := &d2.Extender{}
if d2Sketch, ok := config["d2_sketch"]; ok {
d2Settings.Sketch = d2Sketch == "true"
}
if d2ThemeName, ok := config["d2_theme_name"]; ok {
for _, theme := range d2themescatalog.LightCatalog {
if theme.Name == d2ThemeName {
d2Settings.ThemeID = &theme.ID
break
}
}
for _, theme := range d2themescatalog.DarkCatalog {
if theme.Name == d2ThemeName {
d2Settings.ThemeID = &theme.ID
break
}
}
}
if d2Layout, ok := config["d2_layout"]; ok {
if d2Layout == "elk" {
d2Settings.Layout = d2elklayout.DefaultLayout
}
}
markdown := goldmark.New(
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithXHTML(),
html.WithUnsafe(),
),
goldmark.WithExtensions(
&anchor.Extender{
Texter: anchor.Text("#"),
},
extension.NewLinkify(
extension.WithLinkifyAllowedProtocols([][]byte{
[]byte("http:"),
[]byte("https:"),
}),
extension.WithLinkifyURLRegexp(
xurls.Strict(),
),
),
&mermaid.Extender{},
d2Settings,
&fences.Extender{},
highlighting.NewHighlighting(
highlighting.WithStyle("vs"),
highlighting.WithFormatOptions(
chromahtml.WithLineNumbers(true),
chromahtml.WithClasses(true),
),
),
),
)
if err := markdown.Convert([]byte(md), &htmlBuffer); err != nil {
return "", err
}
return htmlBuffer.String(), nil
}
func Markdown(c *PageContext, md string) templ.Component {
return templ.ComponentFunc(func(_ context.Context, w io.Writer) error {
s, err := md2html(c.Config, md)
if err != nil {
return err
}
_, err = io.WriteString(w, s)
return err
})
}