-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmarkdown.go
43 lines (34 loc) · 1.07 KB
/
markdown.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package graphql
import (
"html/template"
"regexp"
"strings"
"github.com/microcosm-cc/bluemonday"
"github.com/russross/blackfriday/v2"
)
var (
// HashtagRegex is a regex for finding hashtags in Markdown.
HashtagRegex = regexp.MustCompile(`(\s)#(\w+)`)
// TwitterHandleRegex is a regex for finding @username in Markdown.
TwitterHandleRegex = regexp.MustCompile(`(\s)@([_A-Za-z0-9]+)`)
)
// Markdown generator.
func Markdown(str string) template.HTML {
inc := []byte(str)
inc = twitterHandleToMarkdown(inc)
inc = hashTagsToMarkdown(inc)
s := blackfriday.Run(inc)
p := bluemonday.UGCPolicy()
return template.HTML(p.SanitizeBytes(s))
}
// SummarizeText takes a chunk of markdown and just returns the first paragraph.
func SummarizeText(str string) string {
out := strings.Split(str, "\n")
return strings.TrimSpace(out[0])
}
func twitterHandleToMarkdown(in []byte) []byte {
return TwitterHandleRegex.ReplaceAll(in, []byte("$1[@$2](https://twitter.com/$2)"))
}
func hashTagsToMarkdown(in []byte) []byte {
return HashtagRegex.ReplaceAll(in, []byte("$1[#$2](/tags/$2)"))
}