package markup
import (
"bytes"
"strings"
"unicode"
"unicode/utf8"
)
// renderEmoji turns GitHub emoji shortcodes (:tada:) in rendered HTML
// into their Unicode emoji, so a README written for GitHub reads the same
// here. It works on sanitized output rather than inside goldmark because
// goldmark splits a shortcode like :notebook_with_decorative_cover: into
// one text node per underscore, and the output has already settled which
// text is code.
//
// Each emoji is wrapped in span.emoji with the shortcode in data-alias,
// both of which the sanitizer policy already names; the outline reads
// the wrapper to drop the glyph from a contents entry.
//
// Left alone: text inside <pre>, <code>, <kbd>, tag attributes, the label
// of a link that is itself a URL, and any name gemoji does not know.
// A shortcode needs a non-word character, or the edge of its text, on
// both sides, so a:b:c, 10:30:45 and URLs are not shortcodes.
func renderEmoji(h []byte) []byte {
if bytes.IndexByte(h, ':') < 0 {
return h
}
var out bytes.Buffer
out.Grow(len(h))
skip := map[string]int{} // open <pre>/<code>/<kbd> nesting
urlLink := false // inside <a> whose label is a URL
for pos := 0; pos < len(h); {
lt := bytes.IndexByte(h[pos:], '<')
if lt < 0 {
writeEmoji(&out, string(h[pos:]), skipping(skip) || urlLink)
break
}
writeEmoji(&out, string(h[pos:pos+lt]), skipping(skip) || urlLink)
pos += lt
gt := bytes.IndexByte(h[pos:], '>')
if gt < 0 {
out.Write(h[pos:])
break
}
tag := h[pos : pos+gt+1]
out.Write(tag)
pos += gt + 1
name, closing := tagName(tag)
switch name {
case "pre", "code", "kbd":
if closing {
if skip[name] > 0 {
skip[name]--
}
} else {
skip[name]++
}
case "a":
if closing {
urlLink = false
} else if end := bytes.Index(h[pos:], []byte("</a>")); end >= 0 {
label := string(h[pos : pos+end])
urlLink = strings.Contains(label, "://") || strings.HasPrefix(label, "www.")
}
}
}
return out.Bytes()
}
func skipping(m map[string]int) bool {
return m["pre"] > 0 || m["code"] > 0 || m["kbd"] > 0
}
// tagName reads the lowercase element name of a tag like <a href> or </a>.
func tagName(tag []byte) (name string, closing bool) {
s := tag[1 : len(tag)-1]
if len(s) > 0 && s[0] == '/' {
closing, s = true, s[1:]
}
end := 0
for end < len(s) && (s[end] >= 'a' && s[end] <= 'z' || s[end] >= 'A' && s[end] <= 'Z' || s[end] >= '0' && s[end] <= '9') {
end++
}
return strings.ToLower(string(s[:end])), closing
}
func isWordRune(r rune) bool { return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r) }
func isShortcodeByte(c byte) bool {
return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '+' || c == '-'
}
// writeEmoji copies one run of text, replacing the shortcodes in it
// unless keep says the run is code.
func writeEmoji(out *bytes.Buffer, s string, keep bool) {
if keep || !strings.Contains(s, ":") {
out.WriteString(s)
return
}
last := 0
for i := 0; i < len(s); i++ {
if s[i] != ':' {
continue
}
j := i + 1
for j < len(s) && isShortcodeByte(s[j]) {
j++
}
if j == i+1 || j >= len(s) || s[j] != ':' {
continue
}
glyph, ok := gemoji[s[i+1:j]]
if !ok {
continue
}
if i > 0 {
if r, _ := utf8.DecodeLastRuneInString(s[:i]); isWordRune(r) {
continue
}
}
if j+1 < len(s) {
if r, _ := utf8.DecodeRuneInString(s[j+1:]); isWordRune(r) {
continue
}
}
out.WriteString(s[last:i])
out.WriteString(`<span class="emoji" data-alias="` + s[i+1:j] + `">` + glyph + `</span>`)
last = j + 1
i = j
}
out.WriteString(s[last:])
}