94 lines
2 KiB
Go
94 lines
2 KiB
Go
package main
|
|
|
|
import (
|
|
"html/template"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/blevesearch/bleve/analysis"
|
|
htmlFilter "github.com/blevesearch/bleve/analysis/char_filters/html_char_filter"
|
|
"github.com/russross/blackfriday"
|
|
)
|
|
|
|
var filter = makeFilter()
|
|
|
|
func makeFilter() analysis.CharFilter {
|
|
f, _ := htmlFilter.CharFilterConstructor(nil, nil)
|
|
return f
|
|
}
|
|
|
|
func render(text string) Article {
|
|
re := regexp.MustCompile("(<h[1-6])>(.+)(</h[1-6]>)")
|
|
ws := regexp.MustCompile("\\s+")
|
|
rend := blackfriday.MarkdownCommon([]byte(text))
|
|
html := string(rend)
|
|
index := buildIndex(html)
|
|
html = strings.Replace(html, "<table>", `<table class="table">`, -1)
|
|
html = re.ReplaceAllString(html, `${1} id="${2}">${2}${3}`)
|
|
html = strings.Replace(html, "</h1>", `</h1><hr>`, -1)
|
|
return Article{
|
|
Search: ws.ReplaceAllString(string(filter.Filter(rend)), " "),
|
|
Index: template.HTML(index),
|
|
Text: template.HTML(html),
|
|
MD: text,
|
|
}
|
|
}
|
|
|
|
func buildIndex(html string) (ret string) {
|
|
re := regexp.MustCompile("<h([1-6])>(.+)</h[1-6]>")
|
|
hn := re.FindAllStringSubmatch(html, -1)
|
|
for k, v := range hn {
|
|
ret += before(hn, k)
|
|
ret += `<li><a href="#` + v[2] + `">` + v[2] + "</a>"
|
|
ret += after(hn, k)
|
|
}
|
|
return
|
|
}
|
|
|
|
func before(arr [][]string, i int) string {
|
|
c, _ := strconv.Atoi(arr[i][1])
|
|
if c == 1 {
|
|
return `<ul type="circle">`
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func after(arr [][]string, i int) string {
|
|
c, _ := strconv.Atoi(arr[i][1])
|
|
if len(arr) <= i+1 {
|
|
return closeTag(c-1) + "</ul>"
|
|
}
|
|
n, _ := strconv.Atoi(arr[i+1][1])
|
|
if n == 1 {
|
|
return closeTag(c-n) + "</ul>"
|
|
} else if n < c {
|
|
return closeTag(c - n)
|
|
} else if n > c {
|
|
return openTag(n - c)
|
|
} else if n == c {
|
|
return "</li>"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
func openTag(j int) (ret string) {
|
|
for i := 0; i < j; i++ {
|
|
ret += `<ul type="circle"><li>`
|
|
}
|
|
if j > 1 {
|
|
ret = strings.Replace(ret, "circle", "none", j-1)
|
|
}
|
|
ret = ret[0 : len(ret)-4]
|
|
return
|
|
}
|
|
|
|
func closeTag(j int) (ret string) {
|
|
for i := 0; i < j; i++ {
|
|
ret += "</li></ul></li>"
|
|
}
|
|
if j > 1 {
|
|
ret = strings.Replace(ret, "</li></li>", "</li>", -1)
|
|
}
|
|
return
|
|
}
|