2024-10-09 22:03:53 +02:00
|
|
|
package pkg
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"io"
|
2024-10-09 22:49:34 +02:00
|
|
|
"log"
|
2024-10-09 22:03:53 +02:00
|
|
|
|
|
|
|
|
"github.com/alecthomas/chroma/v2/quick"
|
|
|
|
|
"github.com/gomarkdown/markdown"
|
|
|
|
|
"github.com/gomarkdown/markdown/ast"
|
|
|
|
|
"github.com/gomarkdown/markdown/html"
|
|
|
|
|
"github.com/gomarkdown/markdown/parser"
|
|
|
|
|
)
|
|
|
|
|
|
2024-10-09 22:49:34 +02:00
|
|
|
func (client *Client) MdToHTML(bytes []byte) []byte {
|
2024-10-09 22:03:53 +02:00
|
|
|
extensions := parser.CommonExtensions | parser.AutoHeadingIDs
|
|
|
|
|
p := parser.NewWithExtensions(extensions)
|
|
|
|
|
doc := p.Parse(bytes)
|
|
|
|
|
|
|
|
|
|
htmlFlags := html.CommonFlags
|
|
|
|
|
opts := html.RendererOptions{Flags: htmlFlags, RenderNodeHook: client.renderHookCodeBlock}
|
|
|
|
|
renderer := html.NewRenderer(opts)
|
|
|
|
|
|
2024-10-09 22:49:34 +02:00
|
|
|
return markdown.Render(doc, renderer)
|
2024-10-09 22:03:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (client *Client) renderHookCodeBlock(w io.Writer, node ast.Node, entering bool) (ast.WalkStatus, bool) {
|
|
|
|
|
block, ok := node.(*ast.CodeBlock)
|
|
|
|
|
if !ok {
|
|
|
|
|
return ast.GoToNext, false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var style string
|
|
|
|
|
switch client.Dark {
|
|
|
|
|
case true:
|
|
|
|
|
style = "github-dark"
|
|
|
|
|
default:
|
|
|
|
|
style = "github"
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-09 22:49:34 +02:00
|
|
|
err := quick.Highlight(w, string(block.Literal), string(block.Info), "html", style)
|
|
|
|
|
if err != nil {
|
|
|
|
|
log.Println("Error:", err)
|
|
|
|
|
}
|
2024-10-09 22:03:53 +02:00
|
|
|
|
|
|
|
|
return ast.GoToNext, true
|
|
|
|
|
}
|