-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcard.go
70 lines (57 loc) · 1.37 KB
/
card.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
package mobiledoc
import (
"encoding/json"
"errors"
"fmt"
)
// Card renders a Card
type Card func(payload interface{}) string
func imagecard(payload interface{}) string {
m, ok := payload.(map[string]interface{})
if !ok {
return ""
}
src, ok := m["src"]
if !ok {
return ""
}
return fmt.Sprintf("![](%s)", src.(string))
}
type card struct {
name string
payload interface{}
}
// UnmarshalJSON decodes the Card JSON
func (c *card) UnmarshalJSON(b []byte) error {
var tmp []json.RawMessage
err := json.Unmarshal(b, &tmp)
if err != nil {
return fmt.Errorf("unable to unmarshal card: %w", err)
}
if len(tmp) != 2 {
return errors.New("card too short")
}
err = json.Unmarshal(tmp[0], &c.name)
if err != nil {
return fmt.Errorf("unable to unmarshal card name: %w", err)
}
err = json.Unmarshal(tmp[1], &c.payload)
if err != nil {
return fmt.Errorf("unable to unmarshal card payload: %w", err)
}
return nil
}
// Render the card to the specified format
func (md *Mobiledoc) renderCard(c *card) (*node, error) {
if md.cards == nil {
return nil, fmt.Errorf("unable to locate renderer for card %q", c.name)
}
renderer, ok := md.cards[c.name]
if !ok {
return nil, fmt.Errorf("unable to locate renderer for card %q", c.name)
}
wrapper := newNode("div", "")
render := newNode("", renderer(c.payload))
wrapper.appendChild(render)
return wrapper, nil
}