summaryrefslogtreecommitdiffstats
path: root/internal/builder/markdown.go
blob: 4e00ca3c9114ef98e648e9040769d6404a8552fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package builder

import (
	"bytes"
	"regexp"
	"strings"

	"github.com/yuin/goldmark"
	"github.com/yuin/goldmark/extension"
	"github.com/yuin/goldmark/parser"
	"github.com/yuin/goldmark/renderer/html"
)

var md = goldmark.New(
	goldmark.WithExtensions(
		extension.GFM,
		extension.Table,
		extension.Strikethrough,
		extension.TaskList,
	),
	goldmark.WithParserOptions(
		parser.WithAutoHeadingID(),
	),
	goldmark.WithRendererOptions(
		// Allow raw HTML pass-through so component tags survive round-trip.
		html.WithUnsafe(),
	),
)

// MarkdownToHTML converts a markdown string to an HTML fragment.
func MarkdownToHTML(body string) (string, error) {
	var buf bytes.Buffer
	if err := md.Convert([]byte(body), &buf); err != nil {
		return "", err
	}
	return buf.String(), nil
}

var (
	htmlTagRe   = regexp.MustCompile(`<[^>]+>`)
	multiSpaceRe = regexp.MustCompile(`\s+`)
)

// StripHTML removes HTML tags and normalises whitespace for search indexing.
func StripHTML(h string) string {
	plain := htmlTagRe.ReplaceAllString(h, " ")
	plain = multiSpaceRe.ReplaceAllString(plain, " ")
	return strings.TrimSpace(plain)
}