showcase
- v0.2.4
- 37 commits
- 1 branch
- 6 tags
- updated
- CI 2/2
rawhtml.go
5.5 KB · 191 lines
1package render23import (4 "html"5 "net/url"6 "regexp"7 "slices"8 "strings"910 "github.com/yuin/goldmark/ast"11 "github.com/yuin/goldmark/renderer"12 "github.com/yuin/goldmark/util"13)1415// htmlRenderer stands in for goldmark's raw HTML output. Raw HTML is never16// passed through: each tag is parsed, and only an allowlist of tags and17// attributes is written back, built from scratch and escaped. Everything18// else (script, style, iframe, on*, style=, unknown tags) is dropped; the19// contents of script-like tags go too, other text stays as escaped text.20// Open tags are tracked over the whole document, so <div align="center">21// … </div> around Markdown works, and close() ends whatever is left open.22type htmlRenderer struct {23 links linkFixer24 open []string25 skip int // depth inside a dropped element whose text is dropped too26}2728var (29 tagRe = regexp.MustCompile(`(?s)<!--.*?(?:-->|$)|<[!?][^>]*>|<(/?)([A-Za-z][A-Za-z0-9-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>` + "`" + `]+))?)*)\s*/?>`)30 attrRe = regexp.MustCompile(`([^\s"'>/=]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s"'=<>` + "`" + `]+))?`)31 sizeRe = regexp.MustCompile(`^[0-9]{1,4}%?$`)3233 // tag → the attributes it may keep34 allowed = map[string][]string{35 "p": {"align"}, "div": {"align"}, "h1": {"align"}, "h2": {"align"}, "h3": {"align"},36 "h4": {"align"}, "h5": {"align"}, "h6": {"align"},37 "img": {"src", "alt", "title", "width", "height", "align"}, "a": {"href", "title"},38 "br": nil, "hr": nil, "b": nil, "i": nil, "em": nil, "strong": nil, "code": nil, "kbd": nil,39 "sub": nil, "sup": nil, "s": nil, "del": nil, "pre": nil, "blockquote": nil,40 "ul": nil, "ol": nil, "li": nil, "details": {"open"}, "summary": nil,41 }42 voids = []string{"br", "hr", "img"}43 dropAll = []string{"script", "style", "template", "textarea", "iframe", "object", "noscript", "svg", "math", "title", "select"}44)4546func (h *htmlRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) {47 reg.Register(ast.KindHTMLBlock, func(w util.BufWriter, src []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {48 if entering {49 b := n.(*ast.HTMLBlock)50 var s strings.Builder51 for i := 0; i < b.Lines().Len(); i++ {52 seg := b.Lines().At(i)53 s.Write(seg.Value(src))54 }55 if b.HasClosure() {56 cl := b.ClosureLine57 s.Write(cl.Value(src))58 }59 h.write(w, s.String())60 }61 return ast.WalkSkipChildren, nil62 })63 reg.Register(ast.KindRawHTML, func(w util.BufWriter, src []byte, n ast.Node, entering bool) (ast.WalkStatus, error) {64 if entering {65 var s strings.Builder66 segs := n.(*ast.RawHTML).Segments67 for i := 0; i < segs.Len(); i++ {68 seg := segs.At(i)69 s.Write(seg.Value(src))70 }71 h.write(w, s.String())72 }73 return ast.WalkSkipChildren, nil74 })75}7677func (h *htmlRenderer) write(w util.BufWriter, s string) {78 for s != "" {79 loc := tagRe.FindStringSubmatchIndex(s)80 if loc == nil {81 h.text(w, s)82 return83 }84 h.text(w, s[:loc[0]])85 if loc[4] >= 0 { // a tag, not a comment or declaration86 name := strings.ToLower(s[loc[4]:loc[5]])87 if loc[3] > loc[2] {88 h.end(w, name)89 } else {90 h.start(w, name, s[loc[6]:loc[7]])91 }92 }93 s = s[loc[1]:]94 }95}9697func (h *htmlRenderer) text(w util.BufWriter, s string) {98 if h.skip == 0 {99 w.WriteString(html.EscapeString(html.UnescapeString(s)))100 }101}102103func (h *htmlRenderer) start(w util.BufWriter, name, attrs string) {104 if slices.Contains(dropAll, name) {105 h.skip++106 }107 keep, ok := allowed[name]108 if !ok || h.skip > 0 {109 return110 }111 var out strings.Builder112 for _, m := range attrRe.FindAllStringSubmatch(attrs, -1) {113 k, v := strings.ToLower(m[1]), html.UnescapeString(strings.Trim(m[2], `"'`))114 if !slices.Contains(keep, k) {115 continue116 }117 switch k {118 case "src":119 d, ok := h.links.resolve(v, "raw", true)120 if !ok {121 continue122 }123 v = d124 case "href":125 d, ok := h.links.resolve(v, "blob", false)126 if u, err := url.Parse(d); !ok || err != nil || !slices.Contains([]string{"", "http", "https", "mailto"}, strings.ToLower(u.Scheme)) {127 continue128 }129 v = d130 case "width", "height":131 if !sizeRe.MatchString(v) {132 continue133 }134 case "align":135 if v = strings.ToLower(v); !slices.Contains([]string{"left", "center", "right"}, v) {136 continue137 }138 }139 out.WriteString(" " + k)140 if k != "open" {141 out.WriteString(`="` + html.EscapeString(v) + `"`)142 }143 }144 if name == "img" && !strings.Contains(out.String(), " src=") {145 h.text(w, attrValue(attrs, "alt")) // like a dropped Markdown image: keep the alt text146 return147 }148 w.WriteString("<" + name + out.String() + ">")149 if !slices.Contains(voids, name) {150 h.open = append(h.open, name)151 }152}153154func (h *htmlRenderer) end(w util.BufWriter, name string) {155 if slices.Contains(dropAll, name) {156 h.skip = max(0, h.skip-1)157 return158 }159 i := -1160 for j := len(h.open) - 1; j >= 0 && i < 0; j-- {161 if h.open[j] == name {162 i = j163 }164 }165 if h.skip > 0 || i < 0 {166 return // never opened here: a stray close can't end the page's own elements167 }168 for len(h.open) > i {169 w.WriteString("</" + h.open[len(h.open)-1] + ">")170 h.open = h.open[:len(h.open)-1]171 }172}173174// close returns the end tags for everything still open after the document.175func (h *htmlRenderer) close() string {176 var s strings.Builder177 for i := len(h.open) - 1; i >= 0; i-- {178 s.WriteString("</" + h.open[i] + ">")179 }180 h.open = nil181 return s.String()182}183184func attrValue(attrs, name string) string {185 for _, m := range attrRe.FindAllStringSubmatch(attrs, -1) {186 if strings.EqualFold(m[1], name) {187 return html.UnescapeString(strings.Trim(m[2], `"'`))188 }189 }190 return ""191}