package web
import (
"html"
"html/template"
"regexp"
"strings"
)
// noteLead matches a note that opens with a heading of level one to
// three, and captures the heading's inner HTML.
var noteLead = regexp.MustCompile(`(?is)^\s*<h([1-3])(?:\s[^>]*)?>(.*?)</h[1-3]>`)
var noteTag = regexp.MustCompile(`(?s)<[^>]*>`)
// plainWords is s with markup and character references read, case
// folded and its whitespace collapsed: the form two spellings of one
// title are compared in.
func plainWords(s string) string {
s = html.UnescapeString(noteTag.ReplaceAllString(s, ""))
return strings.ToLower(strings.Join(strings.Fields(s), " "))
}
// dropNoteLead removes the heading a note opens with when it is only
// the check-in's subject again. The note sits right under the message,
// and a title repeating the title above it is a stutter; a heading that
// says anything else belongs to the note and stays. Either text may be
// the shorter, because authors both abbreviate the subject and extend
// it. The wiki page itself is untouched: this is only what is shown.
func dropNoteLead(note template.HTML, subject string) template.HTML {
m := noteLead.FindStringSubmatchIndex(string(note))
if m == nil {
return note
}
head, want := plainWords(string(note)[m[4]:m[5]]), plainWords(subject)
if head == "" || want == "" || !(wordPrefix(want, head) || wordPrefix(head, want)) {
return note
}
return template.HTML(strings.TrimLeft(string(note)[m[1]:], " \t\r\n"))
}
// wordPrefix says p begins s and ends where a word of s ends, so a
// one-word heading "Design" does not swallow "Designer notes", and a
// short heading only goes when the subject really opens with it.
func wordPrefix(s, p string) bool {
if !strings.HasPrefix(s, p) {
return false
}
rest := s[len(p):]
return rest == "" || !isWordByte(rest[0]) || !isWordByte(p[len(p)-1])
}
func isWordByte(b byte) bool {
return b == '_' || b >= '0' && b <= '9' || b >= 'a' && b <= 'z' || b >= 0x80
}