htmgo/htmgo-site/internal/markdown/render.go

77 lines
1.5 KiB
Go
Raw Normal View History

2024-09-20 16:45:23 +00:00
package markdown
import (
"bytes"
2024-10-25 19:11:48 +00:00
"github.com/alecthomas/chroma/v2"
chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
2024-09-20 16:45:23 +00:00
"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"
"io"
2024-09-20 18:25:14 +00:00
"io/fs"
2024-09-20 16:45:23 +00:00
)
type Renderer struct {
cache map[string]string
}
func NewRenderer() *Renderer {
return &Renderer{cache: make(map[string]string)}
}
2024-09-20 18:25:14 +00:00
func (r *Renderer) RenderFile(source string, system fs.FS) string {
2024-09-20 16:45:23 +00:00
if val, ok := r.cache[source]; ok {
return val
}
2024-09-20 18:25:14 +00:00
o, err := system.Open(source)
if o == nil {
return ""
}
2024-09-20 18:25:14 +00:00
defer o.Close()
2024-09-20 16:45:23 +00:00
if err != nil {
return ""
}
buf := RenderMarkdown(o)
r.cache[source] = buf.String()
return r.cache[source]
}
func RenderMarkdown(reader io.Reader) bytes.Buffer {
md := goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithParserOptions(
parser.WithAutoHeadingID(),
),
goldmark.WithRendererOptions(
html.WithUnsafe(),
2024-10-26 20:15:31 +00:00
html.WithHardWraps(),
2024-09-20 16:45:23 +00:00
),
goldmark.WithExtensions(
highlighting.NewHighlighting(
2024-10-25 19:11:48 +00:00
highlighting.WithFormatOptions(
chromahtml.WithLineNumbers(true),
chromahtml.WithCustomCSS(map[chroma.TokenType]string{
chroma.PreWrapper: "padding: 12px; overflow: auto; background-color: rgb(245, 245, 245) !important;",
}),
),
2024-09-20 16:45:23 +00:00
highlighting.WithStyle("github"),
),
),
)
source, _ := io.ReadAll(reader)
var buf bytes.Buffer
if err := md.Convert(source, &buf); err != nil {
panic(err)
}
return buf
}