opengist/internal/render/markdown.go

70 lines
1.7 KiB
Go
Raw Permalink Normal View History

package render
import (
"bytes"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/thomiceli/opengist/internal/db"
"github.com/thomiceli/opengist/internal/git"
"github.com/yuin/goldmark"
emoji "github.com/yuin/goldmark-emoji"
highlighting "github.com/yuin/goldmark-highlighting/v2"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/util"
"go.abhg.dev/goldmark/mermaid"
)
func MarkdownGistPreview(gist *db.Gist) (RenderedGist, error) {
var buf bytes.Buffer
err := newMarkdown().Convert([]byte(gist.Preview), &buf)
return RenderedGist{
Gist: gist,
HTML: buf.String(),
}, err
}
func MarkdownFile(file *git.File) (RenderedFile, error) {
var buf bytes.Buffer
2024-10-14 19:20:56 +00:00
err := newMarkdownWithSvgExtension().Convert([]byte(file.Content), &buf)
return RenderedFile{
File: file,
HTML: buf.String(),
Type: "Markdown",
}, err
}
2024-02-24 17:09:23 +00:00
func MarkdownString(content string) (string, error) {
var buf bytes.Buffer
2024-10-14 19:20:56 +00:00
err := newMarkdownWithSvgExtension().Convert([]byte(content), &buf)
2024-02-24 17:09:23 +00:00
return buf.String(), err
}
2024-10-14 19:20:56 +00:00
func newMarkdown(extraExtensions ...goldmark.Extender) goldmark.Markdown {
extensions := []goldmark.Extender{
extension.GFM,
highlighting.NewHighlighting(
highlighting.WithStyle("catppuccin-latte"),
highlighting.WithFormatOptions(html.WithClasses(true)),
),
2024-10-14 19:20:56 +00:00
emoji.Emoji,
&mermaid.Extender{},
}
extensions = append(extensions, extraExtensions...)
return goldmark.New(
goldmark.WithExtensions(extensions...),
goldmark.WithParserOptions(
parser.WithASTTransformers(
2024-10-14 19:20:56 +00:00
util.Prioritized(&checkboxTransformer{}, 10000),
),
),
)
}
2024-10-14 19:20:56 +00:00
func newMarkdownWithSvgExtension() goldmark.Markdown {
return newMarkdown(&svgToImgBase64{})
}