This repository has been archived by the owner on Aug 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
linkvisitor.go
68 lines (66 loc) · 1.71 KB
/
linkvisitor.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
// Package tools provides visitors for external usage and will provide other tools one day.
package tools
import (
"github.com/bouncepaw/mycomarkup/v3/blocks"
"github.com/bouncepaw/mycomarkup/v3/links"
"github.com/bouncepaw/mycomarkup/v3/mycocontext"
)
// LinkVisitor creates a visitor which extracts all the links from the document in context.
//
// We consider inline link, rocket link, image gallery and transclusion targets to be links.
func LinkVisitor(ctx mycocontext.Context) (
visitor func(block blocks.Block),
result func() []links.Link,
) {
var (
collected []links.Link
extractLinks func(block blocks.Block)
)
extractLinks = func(block blocks.Block) {
switch b := block.(type) {
case blocks.Paragraph:
extractLinks(b.Formatted)
case blocks.Heading:
extractLinks(b.Contents())
case blocks.List:
for _, item := range b.Items {
for _, sub := range item.Contents {
extractLinks(sub)
}
}
case blocks.Img:
for _, entry := range b.Entries {
extractLinks(entry)
}
case blocks.ImgEntry:
collected = append(collected, b.Target)
case blocks.Transclusion:
link := links.From(b.Target, "", ctx.HyphaName())
collected = append(collected, link)
case blocks.LaunchPad:
for _, rocket := range b.Rockets {
extractLinks(rocket)
}
case blocks.Formatted:
for _, line := range b.Lines {
for _, span := range line {
switch s := span.(type) {
case blocks.InlineLink:
collected = append(collected, s.Link)
}
}
}
case blocks.RocketLink:
if !b.IsEmpty {
collected = append(collected, b.Link)
}
}
}
visitor = func(block blocks.Block) {
extractLinks(block)
}
result = func() []links.Link {
return collected
}
return
}