forked from SoCloz/goprismic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
74 lines (66 loc) · 1.41 KB
/
group.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
72
73
74
package fragment
import (
"fmt"
"github.com/anilamilineni/goprismic/fragment/link"
)
type GroupFragments map[string]Interface
type Group []GroupFragments
func NewGroup(enc interface{}) (*Group, error) {
dec, ok := enc.([]interface{})
if !ok {
return nil, fmt.Errorf("%#v is not a slice", enc)
}
g := make(Group, 0, len(dec))
return &g, nil
}
func (g *Group) Decode(_ string, enc interface{}) error {
list := enc.([]interface{})
for _, v := range list {
gf := make(GroupFragments)
lenc, ok := v.(map[string]interface{})
if !ok {
return fmt.Errorf("%#v is not a map", v)
}
for name, enci := range lenc {
enc, ok := enci.(map[string]interface{})
if !ok {
return fmt.Errorf("%#v is not a map", enci)
}
n, err := decode(enc["type"].(string), enc["value"])
if err != nil {
return err
}
gf[name] = n
}
*g = append(*g, gf)
}
return nil
}
func (g *Group) AsHtml() string {
html := ""
for _, v := range *g {
for name, fragment := range v {
html += fmt.Sprintf("<section data-field=\"%s\">%s</section>", name, fragment.AsHtml())
}
}
return html
}
func (g *Group) AsText() string {
text := ""
for _, v := range *g {
for _, fragment := range v {
if text != "" {
text += "\n"
}
text += fragment.AsText()
}
}
return text
}
func (g *Group) ResolveLinks(r link.Resolver) {
for _, v := range *g {
for _, fragment := range v {
fragment.ResolveLinks(r)
}
}
}