motorino/internal/mdx/mdx.go

85 lines
2.3 KiB
Go

// SPDX-License-Identifier: GPL-3.0-or-later
// Package mdx renders the Markdown of pages and news with goldmark.
package mdx
import (
"bytes"
"fmt"
"strconv"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/renderer/html"
"github.com/yuin/goldmark/text"
)
// Heading is a heading of a rendered document.
type Heading struct {
// Level is 1 for "#", 2 for "##", and so on.
Level int
// ID is the anchor identifier given to the heading.
ID string
// Text is the heading without markup.
Text string
}
// engine converts Markdown to HTML. Raw HTML is passed through because the
// pages use it for tables with data-label cells, hidden notes and the hero.
var engine = goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
// Render converts md to HTML and returns the headings it found. Every heading
// gets an id attribute made by Slug, with -2, -3 and so on for duplicates.
func Render(md string) (string, []Heading, error) {
src := []byte(md)
doc := engine.Parser().Parse(text.NewReader(src))
var headings []Heading
used := make(map[string]int)
err := ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
h, ok := n.(*ast.Heading)
if !ok || !entering {
return ast.WalkContinue, nil
}
plain := plainText(h, src)
id := uniqueID(Slug(plain), used)
h.SetAttributeString("id", []byte(id))
headings = append(headings, Heading{Level: h.Level, ID: id, Text: plain})
return ast.WalkSkipChildren, nil
})
if err != nil {
return "", nil, fmt.Errorf("walk markdown: %w", err)
}
var out bytes.Buffer
if err := engine.Renderer().Render(&out, src, doc); err != nil {
return "", nil, fmt.Errorf("render markdown: %w", err)
}
return out.String(), headings, nil
}
// uniqueID returns id, or id with a numeric suffix when it was already used.
func uniqueID(id string, used map[string]int) string {
used[id]++
if used[id] == 1 {
return id
}
return id + "-" + strconv.Itoa(used[id])
}
// plainText returns the text of a node and its children without any markup.
func plainText(n ast.Node, src []byte) string {
var b strings.Builder
for c := n.FirstChild(); c != nil; c = c.NextSibling() {
switch t := c.(type) {
case *ast.Text:
b.Write(t.Segment.Value(src))
case *ast.String:
b.Write(t.Value)
default:
b.WriteString(plainText(c, src))
}
}
return b.String()
}