showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
markdown.go
4.1 KB · 142 lines
1package render23import (4 "bytes"5 "html/template"6 "net/url"7 "path"8 "strings"910 "github.com/yuin/goldmark"11 "github.com/yuin/goldmark/ast"12 "github.com/yuin/goldmark/extension"13 "github.com/yuin/goldmark/parser"14 "github.com/yuin/goldmark/renderer"15 "github.com/yuin/goldmark/text"16 "github.com/yuin/goldmark/util"17)1819// Markdown renders src with goldmark's raw HTML output replaced by an20// allowlist (see htmlRenderer). Relative links and images are resolved21// against dir inside the repo at base (e.g. "/repo-a"); images that aren't22// relative or https are dropped.23func Markdown(src []byte, base, dir string) (template.HTML, error) {24 raw := &htmlRenderer{links: linkFixer{base, dir}}25 md := goldmark.New(26 // GFM, but table alignment as align attributes: the default inline27 // style attributes would be blocked by the CSP.28 goldmark.WithExtensions(extension.Linkify, extension.Strikethrough, extension.TaskList,29 extension.NewTable(extension.WithTableCellAlignMethod(extension.TableCellAlignAttribute))),30 goldmark.WithParserOptions(31 parser.WithAutoHeadingID(),32 parser.WithASTTransformers(util.Prioritized(linkFixer{base, dir}, 100)),33 ),34 goldmark.WithRendererOptions(renderer.WithNodeRenderers(util.Prioritized(codeRenderer{}, 100), util.Prioritized(raw, 100))),35 )36 var buf bytes.Buffer37 if err := md.Convert(src, &buf); err != nil {38 return "", err39 }40 return template.HTML(buf.String() + raw.close()), nil41}4243type linkFixer struct{ base, dir string }4445func (f linkFixer) Transform(doc *ast.Document, _ text.Reader, _ parser.Context) {46 var drop []*ast.Image47 ast.Walk(doc, func(n ast.Node, entering bool) (ast.WalkStatus, error) {48 if !entering {49 return ast.WalkContinue, nil50 }51 switch n := n.(type) {52 case *ast.Image:53 if d, ok := f.resolve(string(n.Destination), "raw", true); ok {54 n.Destination = []byte(d)55 } else {56 drop = append(drop, n)57 }58 case *ast.Link:59 if d, ok := f.resolve(string(n.Destination), "blob", false); ok {60 n.Destination = []byte(d)61 }62 }63 return ast.WalkContinue, nil64 })65 for _, img := range drop { // keep the alt text, lose the image66 parent := img.Parent()67 for c := img.FirstChild(); c != nil; {68 next := c.NextSibling()69 parent.InsertBefore(parent, img, c)70 c = next71 }72 parent.RemoveChild(parent, img)73 }74}7576// resolve maps a Markdown destination to a site URL. Absolute URLs pass77// through for links (goldmark blanks dangerous schemes); images must be https.78func (f linkFixer) resolve(dest, kind string, image bool) (string, bool) {79 u, err := url.Parse(dest)80 if err != nil {81 return "", false82 }83 if u.Scheme != "" || u.Host != "" {84 return dest, !image || u.Scheme == "https"85 }86 if u.Path == "" { // "#anchor" or "?q"87 return dest, !image88 }89 p := u.Path90 if !strings.HasPrefix(p, "/") {91 p = path.Join("/", f.dir, p)92 }93 p = strings.TrimPrefix(path.Clean(p), "/")94 if p == "" || p == "." {95 return f.base + "/", !image96 }97 if !image && strings.HasSuffix(u.Path, "/") {98 kind = "tree"99 p += "/"100 }101 out := f.base + "/" + kind + "/" + EscapePath(p)102 if !image && u.Fragment != "" {103 out += "#" + u.EscapedFragment()104 }105 return out, true106}107108// EscapePath escapes each segment of a slash-separated repo path.109func EscapePath(p string) string {110 parts := strings.Split(p, "/")111 for i, s := range parts {112 parts[i] = url.PathEscape(s)113 }114 return strings.Join(parts, "/")115}116117// codeRenderer highlights fenced code blocks with the same hl-* classes as118// file pages.119type codeRenderer struct{}120121func (codeRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {122 reg.Register(ast.KindFencedCodeBlock, func(w util.BufWriter, src []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {123 if !entering {124 return ast.WalkContinue, nil125 }126 cb := n.(*ast.FencedCodeBlock)127 var code strings.Builder128 for i := 0; i < cb.Lines().Len(); i++ {129 seg := cb.Lines().At(i)130 code.Write(seg.Value(src))131 }132 w.WriteString("<pre><code>")133 for i, line := range Highlight("", string(cb.Language(src)), code.String()) {134 if i > 0 {135 w.WriteString("\n")136 }137 w.WriteString(string(line))138 }139 w.WriteString("</code></pre>\n")140 return ast.WalkSkipChildren, nil141 })142}