-
Notifications
You must be signed in to change notification settings - Fork 3
/
markdown.go
52 lines (45 loc) · 1.58 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
44
45
46
47
48
49
50
51
52
package goeditorjs
import (
"fmt"
"strings"
)
// MarkdownEngine is the engine that creates the HTML from EditorJS blocks
type MarkdownEngine struct {
BlockHandlers map[string]MarkdownBlockHandler
}
// MarkdownBlockHandler is an interface for a plugable EditorJS HTML generator
type MarkdownBlockHandler interface {
Type() string // Type returns the type the block handler supports as a string
GenerateMarkdown(editorJSBlock EditorJSBlock) (string, error)
}
// NewMarkdownEngine creates a new MarkdownEngine
func NewMarkdownEngine() *MarkdownEngine {
bhs := make(map[string]MarkdownBlockHandler)
return &MarkdownEngine{BlockHandlers: bhs}
}
// RegisterBlockHandlers registers or overrides a block handlers for blockType given by MarkdownBlockHandler.Type()
func (markdownEngine *MarkdownEngine) RegisterBlockHandlers(handlers ...MarkdownBlockHandler) {
for _, bh := range handlers {
markdownEngine.BlockHandlers[bh.Type()] = bh
}
}
// GenerateMarkdown generates markdown from the editorJS using configured set of markdown handlers
func (markdownEngine *MarkdownEngine) GenerateMarkdown(editorJSData string) (string, error) {
results := []string{}
ejs, err := parseEditorJSON(editorJSData)
if err != nil {
return "", err
}
for _, block := range ejs.Blocks {
if generator, ok := markdownEngine.BlockHandlers[block.Type]; ok {
md, err := generator.GenerateMarkdown(block)
if err != nil {
return "", err
}
results = append(results, md)
} else {
return "", fmt.Errorf("%w, Block Type: %s", ErrBlockHandlerNotFound, block.Type)
}
}
return strings.Join(results, "\n\n"), nil
}