-
Notifications
You must be signed in to change notification settings - Fork 4
/
editorjs.go
71 lines (62 loc) · 1.26 KB
/
editorjs.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package editorjs
import (
"encoding/json"
"io"
"strings"
"sync"
"bytes"
)
// Writer :
type Writer interface {
io.StringWriter
io.Writer
}
// Flusher :
type Flusher interface {
Flush() error
}
// ParseFunc :
type ParseFunc func(b []byte, w Writer) error
// EditorJS :
type EditorJS struct {
// mutex lock, to prevent race condition
mu sync.Mutex
parsers map[string]ParseFunc
}
// NewEditorJS : create new Editorjs object
func NewEditorJS() *EditorJS {
ejs := new(EditorJS)
ejs.parsers = make(map[string]ParseFunc)
// register default parser
registerDefaultParsers(ejs, DefaultParser{})
return ejs
}
// RegisterParser :
func (ejs *EditorJS) RegisterParser(name string, p ParseFunc) {
ejs.mu.Lock()
defer ejs.mu.Unlock()
ejs.parsers[name] = p
}
// ParseTo : convert editorjs data to HTML
func (ejs *EditorJS) ParseTo(b []byte, w Writer) error {
r := bytes.NewBuffer(b)
data := Data{}
if err := json.NewDecoder(r).Decode(&data); err != nil {
return err
}
f, flusher := w.(Flusher)
for _, blk := range data.Blocks {
blk.Type = strings.ToLower(strings.TrimSpace(blk.Type))
parseData, ok := ejs.parsers[blk.Type]
if !ok {
continue
}
if err := parseData(blk.Data, w); err != nil {
return err
}
if flusher {
f.Flush()
}
}
return nil
}