forked from davidscottmills/goeditorjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblock_code.go
More file actions
62 lines (52 loc) · 1.56 KB
/
block_code.go
File metadata and controls
62 lines (52 loc) · 1.56 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package goeditorjs
import (
"encoding/json"
"fmt"
"regexp"
"sort"
"strings"
)
// CodeBoxHandler is the default CodeBoxHandler for EditorJS HTML generation
type CodeBoxHandler struct{}
func (*CodeBoxHandler) parse(editorJSBlock EditorJSBlock) (*codeBox, error) {
codeBox := &codeBox{}
return codeBox, json.Unmarshal(editorJSBlock.Data, codeBox)
}
// Type "codeBox"
func (*CodeBoxHandler) Type() string {
return "codeBox"
}
// GenerateHTML generates html for CodeBoxBlocks
func (h *CodeBoxHandler) GenerateHTML(editorJSBlock EditorJSBlock) (string, error) {
codeBox, err := h.parse(editorJSBlock)
if err != nil {
return "", err
}
return fmt.Sprintf(`<pre><code class="%s">%s</code></pre>`, codeBox.Language, codeBox.Code), nil
}
// GenerateMarkdown generates markdown for CodeBoxBlocks
func (h *CodeBoxHandler) GenerateMarkdown(editorJSBlock EditorJSBlock) (string, error) {
codeBox, err := h.parse(editorJSBlock)
if err != nil {
return "", err
}
codeBox.Code = strings.ReplaceAll(codeBox.Code, "<div>", "\n")
codeBox.Code = removeHTMLTags(codeBox.Code)
return fmt.Sprintf("```%s\n%s\n```", codeBox.Language, codeBox.Code), nil
}
func removeHTMLTags(in string) string {
// regex to match html tag
const pattern = `(<\/?[a-zA-A]+?[^>]*\/?>)*`
r := regexp.MustCompile(pattern)
groups := r.FindAllString(in, -1)
// should replace long string first
sort.Slice(groups, func(i, j int) bool {
return len(groups[i]) > len(groups[j])
})
for _, group := range groups {
if strings.TrimSpace(group) != "" {
in = strings.ReplaceAll(in, group, "")
}
}
return in
}