oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package markup
2
3import (
4 "html"
5 "html/template"
6 "regexp"
7 "strconv"
8 "strings"
9)
10
11// Resolver answers where a [[link]] goes for the person reading. Mapa's
12// is per viewer: a date link opens the reader's own daily note (§3.4).
13type Resolver interface {
14 Resolve(target, anchor string) Resolution
15}
16
17// Resolution is one link's answer.
18type Resolution struct {
19 // Href is where the link goes: the page, or for a pending link the
20 // page that offers to create it.
21 Href string
22 // Pending marks text that names no page yet (§3.2).
23 Pending bool
24 // Broken is date-shaped text that is no date: shown as typed.
25 Broken bool
26 // BlockGone is a block link whose block was deleted: it resolves to
27 // the page, with a note (§3.2).
28 BlockGone bool
29 // Title is the team page's current title, when the link names one.
30 Title string
31 // Alias marks a link that reached its page through an old title.
32 Alias bool
33 // Day is a date link's day in words, from DayLabel.
34 Day string
35 // Icon is the team page's icon (columns and icons spec §2.4): an
36 // emoji, or an image's public id. The chip draws it in place of its
37 // page glyph. Never on a block link, a date or a pending link.
38 Icon ChipIcon
39}
40
41// ChipIcon is a page's icon as a chip draws it: one of the two, or
42// neither.
43type ChipIcon struct {
44 Emoji string `json:"emoji,omitempty"`
45 Image string `json:"image,omitempty"`
46}
47
48var (
49 strong = regexp.MustCompile(`\*\*(\S(?:[^*]*?\S)?)\*\*`)
50 emphasis = regexp.MustCompile(`\*(\S(?:[^*]*?\S)?)\*`)
51 taskBox = regexp.MustCompile(`^\[([ xX])\][ \t]+`)
52)
53
54// Render draws blocks as HTML: exactly the DOM the editor's schema draws
55// for them (spec §5), with no text between blocks. Every byte a person
56// typed is escaped; nothing they wrote is ever passed through as markup.
57func Render(blocks []Block, resolver Resolver) template.HTML {
58 var out strings.Builder
59 for index := 0; index < len(blocks); {
60 if blocks[index].Kind == Item {
61 index = renderList(&out, blocks, index, resolver)
62 continue
63 }
64 if blocks[index].Kind == Columns {
65 index = renderLayout(&out, blocks, index, resolver)
66 continue
67 }
68 if IsFence(blocks[index].Kind) {
69 // A fence drawn apart from its layout (History's diff draws
70 // runs of blocks) is no block of its own: it draws nothing.
71 index++
72 continue
73 }
74 renderBlock(&out, blocks[index], resolver)
75 index++
76 }
77 return template.HTML(out.String())
78}
79
80// RenderPage draws a whole body. When its last block is not a paragraph,
81// or it has none, it ends with the editor's empty paragraph (§6.2).
82func RenderPage(blocks []Block, resolver Resolver) template.HTML {
83 drawn := Render(blocks, resolver)
84 if len(blocks) == 0 || blocks[len(blocks)-1].Kind != Paragraph {
85 drawn += EmptyParagraph
86 }
87 return drawn
88}
89
90func renderBlock(out *strings.Builder, block Block, resolver Resolver) {
91 id := blockID(block)
92 switch block.Kind {
93 case Heading:
94 tag := "h" + strconv.Itoa(min(block.Level+1, 6))
95 out.WriteString("<" + tag + id + ">" +
96 inline(Strip(block), resolver) + "</" + tag + ">")
97 case Code:
98 out.WriteString("<pre><code>" + codeHTML(codeText(block.Source)) +
99 "</code></pre>")
100 case Rule:
101 out.WriteString("<hr>")
102 case Quote:
103 out.WriteString("<blockquote" + id + "><p>" +
104 inline(Strip(block), resolver) + "</p></blockquote>")
105 default:
106 out.WriteString("<p" + id + ">" + inline(Strip(block), resolver) +
107 "</p>")
108 }
109}
110
111// codeHTML is a code block's text, with the view's trailing break when
112// it is empty or ends in a newline.
113func codeHTML(text string) string {
114 if text == "" || strings.HasSuffix(text, "\n") {
115 return html.EscapeString(text) + trailingBreak
116 }
117 return html.EscapeString(text)
118}
119
120// renderList draws the run of items starting at start, nesting by level,
121// and returns the index after the run. A level skip nests one deep, and
122// an item of the other kind (bullet or numbered) starts a new list at
123// its depth.
124func renderList(out *strings.Builder, blocks []Block, start int,
125 resolver Resolver) int {
126 var open []string // the tag of each list still open, outermost first
127 index := start
128 for ; index < len(blocks) && blocks[index].Kind == Item; index++ {
129 item := blocks[index]
130 depth := min(item.Level, len(open))
131 open = closeLists(out, open, depth+1)
132 tag := listTag(item)
133 if len(open) == depth+1 && open[depth] != tag {
134 open = closeLists(out, open, depth)
135 }
136 if len(open) == depth+1 {
137 out.WriteString("</li>")
138 } else {
139 out.WriteString("<" + tag + ">")
140 open = append(open, tag)
141 }
142 task, body := itemParts(item, resolver)
143 out.WriteString("<li" + blockID(item) + task + "><p>" + body +
144 "</p>")
145 }
146 closeLists(out, open, 0)
147 return index
148}
149
150// closeLists closes open lists, each with its last item, until depth
151// remain.
152func closeLists(out *strings.Builder, open []string, depth int) []string {
153 for len(open) > depth {
154 out.WriteString("</li></" + open[len(open)-1] + ">")
155 open = open[:len(open)-1]
156 }
157 return open
158}
159
160func listTag(item Block) string {
161 if item.Ordered {
162 return "ol"
163 }
164 return "ul"
165}
166
167// itemParts is a list item's task attribute, if it is a task, and its
168// text. The box is drawn by CSS from the attribute: the item's paragraph
169// is the editor's textblock, and holds only the text.
170func itemParts(item Block, resolver Resolver) (string, string) {
171 text := Strip(item)
172 match := taskBox.FindStringSubmatch(text)
173 if match == nil {
174 return "", inline(text, resolver)
175 }
176 state := ` mapa-task="done"`
177 if match[1] == " " {
178 state = ` mapa-task="open"`
179 }
180 return state, inline(text[len(match[0]):], resolver)
181}
182
183func blockID(block Block) string {
184 if block.Marker == "" {
185 return ""
186 }
187 return ` id="b-` + html.EscapeString(block.Marker) + `"`
188}
189
190// Strip is a block's inline text: its words with the block syntax and the
191// ^id marker taken off, but its links and emphasis kept.
192func Strip(block Block) string { return Plain(block) }
193
194// Words is a block's text as a reader sees it: links as their shown
195// text, code as its text, embeds dropped. Search reads it.
196func Words(block Block) string {
197 if block.Kind == Code {
198 return codeText(block.Source)
199 }
200 var out strings.Builder
201 for _, span := range Spans(Strip(block)) {
202 switch span.Kind {
203 case WikiLink:
204 out.WriteString(firstOf(span.Text, span.Target))
205 case Embed:
206 out.WriteString(" ")
207 case Image:
208 // Alt text is body text: search and snippets find it, and
209 // never the address (images §2.1).
210 out.WriteString(span.Text)
211 default:
212 out.WriteString(span.Text)
213 }
214 }
215 return out.String()
216}
217
218// Unlinked is a block's text outside links and code, each run apart, for
219// unlinked mentions (§6.4). A code block has none.
220func Unlinked(block Block) []string {
221 if block.Kind == Code {
222 return nil
223 }
224 var runs []string
225 for _, span := range Spans(Strip(block)) {
226 if span.Kind == Text {
227 runs = append(runs, span.Text)
228 }
229 }
230 return runs
231}
232
233func firstOf(values ...string) string {
234 for _, value := range values {
235 if value != "" {
236 return value
237 }
238 }
239 return ""
240}
241