oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1// Package chatmarkdown renders a small Markdown vocabulary without raw HTML.
2package chatmarkdown
3
4import (
5 "bytes"
6 "html"
7 "html/template"
8 "net/url"
9 "regexp"
10 "strings"
11
12 "github.com/yuin/goldmark/ast"
13 "github.com/yuin/goldmark/util"
14)
15
16// Labels are the words of a paste box, from the app's copy: its Copy
17// button, the button once it has copied, what is announced when the
18// clipboard is refused and the text is selected instead, and the labels
19// of a prompt, a text and a command box. CopyIcon and CopiedIcon are the
20// app's own icons (fixed, aria-hidden markup, never input) beside Copy's
21// word: one shown before a copy, the other, a tick, after.
22type Labels struct {
23 Copy, Copied, Selected, Prompt, Text, Command string
24 CopyIcon, CopiedIcon template.HTML
25}
26
27// Render renders a finished message.
28func (l Labels) Render(body string) template.HTML { return render(body, false, l) }
29
30// RenderDraft renders a reply that is still arriving with the same rules,
31// leaving out only what the next characters could still change (see
32// draft.go). The draft of a whole reply is the reply's Render, unless the
33// reply itself ends on an unclosed opener or a bare list marker.
34func (l Labels) RenderDraft(body string) template.HTML { return render(body, true, l) }
35
36func render(body string, draft bool, l Labels) template.HTML {
37 var hide spans
38 if draft {
39 body = steady(body)
40 }
41 source := []byte(body)
42 root, seen := parse(source)
43 if draft {
44 hide = unclosed(root, source, seen)
45 }
46 var out bytes.Buffer
47 escape := func(b []byte) { out.WriteString(html.EscapeString(string(b))) }
48 var node func(ast.Node)
49 children := func(n ast.Node) {
50 for c := n.FirstChild(); c != nil; c = c.NextSibling() {
51 node(c)
52 }
53 }
54 node = func(n ast.Node) {
55 wrap := func(open, close string) { out.WriteString(open); children(n); out.WriteString(close) }
56 switch v := n.(type) {
57 case *ast.Document:
58 children(n)
59 case *ast.Paragraph, *ast.Heading:
60 wrap("<p>", "</p>\n")
61 case *ast.TextBlock:
62 children(n)
63 case *ast.Text:
64 escape(util.ResolveEntityNames(util.ResolveNumericReferences(util.UnescapePunctuations(hide.value(source, v.Segment)))))
65 if v.HardLineBreak() {
66 out.WriteString("<br>\n")
67 } else if v.SoftLineBreak() {
68 out.WriteByte('\n')
69 }
70 case *ast.String:
71 escape(v.Value)
72 case *ast.Emphasis:
73 if v.Level == 2 {
74 wrap("<strong>", "</strong>")
75 } else {
76 wrap("<em>", "</em>")
77 }
78 case *ast.CodeSpan:
79 out.WriteString("<code>")
80 for c := n.FirstChild(); c != nil; c = c.NextSibling() {
81 escape(c.(*ast.Text).Segment.Value(source))
82 }
83 out.WriteString("</code>")
84 case *ast.FencedCodeBlock:
85 // Copy waits while a draft's fence is still open.
86 l.box(&out, v, source, draft && !seen.closed(v))
87 case *ast.CodeBlock:
88 out.WriteString("<pre><code>")
89 for i := 0; i < n.Lines().Len(); i++ {
90 line := n.Lines().At(i)
91 escape(line.Value(source))
92 }
93 out.WriteString("</code></pre>\n")
94 case *ast.List:
95 if v.IsOrdered() {
96 wrap("<ol>", "</ol>\n")
97 } else {
98 wrap("<ul>", "</ul>\n")
99 }
100 case *ast.ListItem:
101 wrap("<li>", "</li>\n")
102 case *ast.Link:
103 dest := linkEntities(string(v.Destination))
104 u, err := url.Parse(dest)
105 // Absolute web and mail links, and on this site only a task's
106 // or a project's own page (the coordinator links tasks by title).
107 if err == nil && (u.Scheme == "https" || u.Scheme == "http" || u.Scheme == "mailto" || u.Scheme == "" && sitePage.MatchString(dest)) {
108 wrap(`<a href="`+html.EscapeString(dest)+`" rel="noopener">`, "</a>")
109 } else {
110 children(n)
111 }
112 case *ast.RawHTML:
113 for i := 0; i < v.Segments.Len(); i++ {
114 seg := v.Segments.At(i)
115 escape(seg.Value(source))
116 }
117 case *ast.HTMLBlock:
118 for i := 0; i < v.Lines().Len(); i++ {
119 seg := v.Lines().At(i)
120 escape(seg.Value(source))
121 }
122 if v.HasClosure() {
123 escape(v.ClosureLine.Value(source))
124 }
125 default:
126 children(n)
127 }
128 }
129 node(root)
130 return template.HTML(out.String()) // Every text leaf is escaped; tags above are fixed.
131}
132
133// A destination may contain proper HTML entities, but query parameters such
134// as &timestamp and &region are not entities. Decode exactly once and require
135// the complete name, so an unknown &notarealentity; also remains unchanged.
136var properEntity = regexp.MustCompile(`&(?:#[xX][0-9A-Fa-f]+|#[0-9]+|[A-Za-z][A-Za-z0-9]*);`)
137
138func linkEntities(value string) string {
139 return properEntity.ReplaceAllStringFunc(value, func(entity string) string {
140 if entity[1] == '#' {
141 return html.UnescapeString(entity)
142 }
143 if named, ok := util.LookUpHTML5EntityByName(entity[1 : len(entity)-1]); ok {
144 return string(named.Characters)
145 }
146 return entity
147 })
148}
149
150// sitePage is a same-origin link the chat may render: a task or a project.
151var sitePage = regexp.MustCompile(`^/(tasks/tk[a-z0-9]{1,32}|projects/p_[a-z0-9]{1,40})$`)
152
153// box is a fenced block as a paste box: a bar with its label, quietly,
154// when the fence names a safe language, and a Copy button, then the
155// text in a selectable
156// <pre><code>, which is what the button copies (paste.js reads the code's
157// text, so entities are the characters they stand for). A prompt or text
158// block is prose and wraps; anything else is code and scrolls. While a
159// draft's fence is open the button is there but aria-disabled, so a
160// half-streamed command is never copied, and the box does not move when
161// it closes: only the button's attribute changes.
162func (l Labels) box(out *bytes.Buffer, v *ast.FencedCodeBlock, source []byte, open bool) {
163 lang := string(v.Language(source))
164 if !language.MatchString(lang) {
165 lang = ""
166 }
167 kind := "code"
168 if prose[strings.ToLower(lang)] {
169 kind = "prose"
170 }
171 out.WriteString(`<div equipo-paste="` + kind + `"><div equipo-paste-bar>`)
172 if label := l.label(lang); label != "" {
173 out.WriteString(`<span equipo-paste-lang>` + html.EscapeString(label) + `</span>`)
174 }
175 out.WriteString(`<button type="button" equipo-paste-copy data-copied="` + html.EscapeString(l.Copied) + `" data-selected="` + html.EscapeString(l.Selected) + `"`)
176 if open {
177 out.WriteString(` aria-disabled="true"`)
178 }
179 out.WriteString(`><span equipo-paste-icon="copy">` + string(l.CopyIcon) + `</span><span equipo-paste-icon="copied">` + string(l.CopiedIcon) + `</span><span equipo-paste-word>` + html.EscapeString(l.Copy) + `</span></button></div><pre><code>`)
180 for i := 0; i < v.Lines().Len(); i++ {
181 line := v.Lines().At(i)
182 out.WriteString(html.EscapeString(string(line.Value(source))))
183 }
184 out.WriteString("</code></pre></div>\n")
185}
186
187// language is a fence's label that may show: a short word of letters,
188// digits and the marks language names use (c++, c#, objective-c, .env).
189var language = regexp.MustCompile(`^\.?[A-Za-z0-9][A-Za-z0-9_+#.-]{0,23}$`)
190
191// prose are the labels of text a person reads and pastes whole: it wraps.
192var prose = map[string]bool{"prompt": true, "text": true}
193
194// shells are the fence labels of a command typed into a terminal.
195var shells = map[string]bool{"bash": true, "sh": true, "zsh": true, "shell": true, "console": true}
196
197// label is what a box's bar says it holds: Prompt, Text or Command in
198// the app's words, otherwise the fence's language as written ("" for
199// none).
200func (l Labels) label(lang string) string {
201 word := ""
202 switch lower := strings.ToLower(lang); {
203 case lower == "prompt":
204 word = l.Prompt
205 case lower == "text":
206 word = l.Text
207 case shells[lower]:
208 word = l.Command
209 }
210 if word == "" {
211 return lang
212 }
213 return word
214}
215