motorino/internal/mdx/mdx.go
tgiachi 917683afa4 fix: close the minor findings of the first review
Require refuses an empty value. Heading ids: an explicit {#id} must be sound
and unique, generated ids avoid the explicit ones and each other, and a heading
with no ASCII letters gets a fallback. Fenced code blocks keep their
placeholders and a backslash keeps one anywhere. The em dash rule covers the
header of the manifesto pages and the HTML entities. The feed makes src links
absolute, base_url is required, and the news page must be a folder index. A
category written twice in a post counts once, a block name in a news title is no
longer taken for a placeholder, and build refuses extra arguments.
2026-11-15 10:32:19 +01:00

150 lines
4.2 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"
"regexp"
"strconv"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"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; a level 1 heading has
// none, because it is the title of the page.
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.WithParserOptions(parser.WithHeadingAttribute()),
goldmark.WithRendererOptions(html.WithUnsafe()),
)
// Render converts md to HTML and returns the headings it found. A heading can
// set its own id with "## Title {#id}". Any other heading from level 2 gets an
// id made by Slug, with -2, -3 and so on for duplicates; the level 1 heading
// is the title of the page and gets none.
func Render(md string) (string, []Heading, error) {
src := []byte(md)
doc := engine.Parser().Parse(text.NewReader(src))
used, err := explicitIDs(doc)
if err != nil {
return "", nil, err
}
var headings []Heading
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 := ""
if explicit, ok := h.AttributeString("id"); ok {
id = attributeText(explicit)
} else if h.Level >= 2 {
base := Slug(plain)
if base == "" {
base = "section"
}
id = uniqueID(base, 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
}
// attributeText returns the text of a goldmark attribute value.
func attributeText(value any) string {
switch v := value.(type) {
case []byte:
return string(v)
case string:
return v
}
return ""
}
// explicitID is what an id set with {#id} may look like: it ends up in
// attributes and in addresses.
var explicitID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.:-]*$`)
// explicitIDs returns the ids that headings set for themselves with {#id}. A
// bad id or an id used by two headings is an error. Generated ids avoid these,
// whatever the order of the headings.
func explicitIDs(doc ast.Node) (map[string]bool, error) {
used := map[string]bool{}
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
}
value, ok := h.AttributeString("id")
if !ok {
return ast.WalkSkipChildren, nil
}
id := attributeText(value)
if !explicitID.MatchString(id) {
return ast.WalkStop, fmt.Errorf("the heading id %q may have only letters, digits and _ . : -", id)
}
if used[id] {
return ast.WalkStop, fmt.Errorf("the heading id %q is used by two headings", id)
}
used[id] = true
return ast.WalkSkipChildren, nil
})
return used, err
}
// uniqueID returns base, or base with -2, -3 and so on until the id is not
// used, and marks it as used.
func uniqueID(base string, used map[string]bool) string {
id, n := base, 1
for used[id] {
n++
id = base + "-" + strconv.Itoa(n)
}
used[id] = true
return 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()
}