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
/
mycomarkup.go
81 lines (72 loc) · 2.02 KB
/
mycomarkup.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
// Package mycomarkup provides an API for processing Mycomarkup-formatted documents.
package mycomarkup
import (
"sync"
"github.com/bouncepaw/mycomarkup/blocks"
"github.com/bouncepaw/mycomarkup/mycocontext"
"github.com/bouncepaw/mycomarkup/parser"
)
// BlockTree returns a slice of blocks parsed from the Mycomarkup document contained in ctx.
//
// Pass visitors. Visitors are functions (usually closures) that are called on every found block.
//
// Visitors included with mycomarkup can be gotten from OpenGraphVisitors. More visitors coming soon.
func BlockTree(ctx mycocontext.Context, visitors ...func(block blocks.Block)) []blocks.Block {
var (
tokens = make(chan blocks.Block)
ast = []blocks.Block{}
wg sync.WaitGroup
)
wg.Add(1)
go func() {
parser.Parse(ctx, tokens)
wg.Done()
}()
for token := range tokens {
ast = append(ast, token)
for _, visitor := range visitors {
visitor := visitor
visitor(token)
}
}
wg.Wait()
return ast
}
// BlocksToHTML turns the blocks into their HTML representation.
func BlocksToHTML(_ mycocontext.Context, ast []blocks.Block) string {
counter := &blocks.IDCounter{
ShouldUseResults: true,
}
return generateHTML(ast, 0, counter)
}
// transclusionVisitor returns a visitor to pass to BlockTree and a function
func transclusionVisitor(xcl blocks.Transclusion) (
visitor func(block blocks.Block),
result func() []blocks.Block,
) {
var (
collected []blocks.Block
metDescriptionAlready = false
)
visitor = func(block blocks.Block) {
switch xcl.Selector {
case blocks.SelectorAttachment:
// We don't need any of that when we only transclude attachments.
case blocks.SelectorText, blocks.SelectorFull:
collected = append(collected, block)
case blocks.SelectorOverview, blocks.SelectorDescription:
switch block.(type) {
case blocks.Paragraph:
if metDescriptionAlready {
break
}
metDescriptionAlready = true
collected = append(collected, block)
}
}
}
result = func() []blocks.Block {
return collected
}
return
}