-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
link.go
93 lines (71 loc) · 1.2 KB
/
link.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package hype
import (
"encoding/json"
"fmt"
"strings"
)
type Link struct {
*Element
}
func (l *Link) MarshalJSON() ([]byte, error) {
if l == nil {
return nil, ErrIsNil("link")
}
l.RLock()
defer l.RUnlock()
m, err := l.JSONMap()
if err != nil {
return nil, err
}
m["type"] = toType(l)
h, err := l.Href()
if err != nil {
return nil, err
}
m["url"] = h
return json.MarshalIndent(m, "", " ")
}
func (l *Link) Href() (string, error) {
if l == nil {
return "", ErrIsNil("link")
}
return l.ValidAttr("href")
}
func (l *Link) MD() string {
if l == nil {
return ""
}
h, err := l.Href()
if err != nil {
return ""
}
return fmt.Sprintf("[%s](%s)", l.Children().MD(), h)
}
func NewLink(el *Element) (*Link, error) {
if el == nil {
return nil, ErrIsNil("element")
}
l := &Link{
Element: el,
}
h, ok := l.Get("href")
if !ok {
return l, nil
}
if !strings.HasPrefix(h, "http") {
return l, nil
}
if _, ok := l.Get("target"); !ok {
if err := l.Set("target", "_blank"); err != nil {
return nil, err
}
}
return l, nil
}
func NewLinkNodes(p *Parser, el *Element) (Nodes, error) {
l, err := NewLink(el)
if err != nil {
return nil, err
}
return Nodes{l}, nil
}