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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package backend
import (
"errors"
"fmt"
"html/template"
"log/slog"
"strings"
"git.anhgelus.world/anhgelus/small-web/dom"
"git.anhgelus.world/anhgelus/small-web/markdown"
"github.com/pelletier/go-toml/v2"
)
type EntryInfo struct {
Title string `toml:"title"`
Description string `toml:"description"`
Img image `toml:"image"`
PubLocalDate toml.LocalDate `toml:"publication_date"`
}
func renderLinkFunc(url string) func(string, string) template.HTML {
return func(content, href string) template.HTML {
anchor := dom.NewLiteralContentElement("a", template.HTML(content))
anchor.SetAttribute("href", href)
if href == url || (href != "/" && url != "/" && strings.HasPrefix(url, href)) {
anchor.ClassList().Add("target")
}
if markdown.ExternalLink.MatchString(href) {
anchor.SetAttribute("target", "_blank").SetAttribute("rel", "noreferrer")
}
return anchor.Render()
}
}
func renderLink(content, href, url string) template.HTML {
return renderLinkFunc(url)(content, href)
}
func parse(b []byte, info *EntryInfo, d *data) (template.HTML, bool) {
var dd string
splits := strings.SplitN(string(b), "---", 2)
if len(splits) == 2 && info != nil {
err := toml.Unmarshal([]byte(splits[0]), info)
if err != nil {
slog.Warn("parsing entry info", "error", err)
} else {
dd = splits[1]
}
} else {
dd = string(b)
}
opt := new(markdown.Option)
opt.ImageSource = getStatic
opt.RenderLink = renderLinkFunc(d.URL)
content, err := markdown.Parse(dd, opt)
var errMd *markdown.ParseError
errors.As(err, &errMd)
if errMd != nil {
slog.Error("parsing markdown")
fmt.Println(errMd.Pretty())
return "", false
}
d.PageDescription = info.Description
d.title = info.Title
d.Image = info.Img.Src
return content, true
}
|