oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package web
2
3import (
4 "html"
5 "html/template"
6 "net/url"
7 "regexp"
8 "strconv"
9 "strings"
10
11 "amadan.net/oficina/base/internal/equipo"
12)
13
14// linkRE finds a Markdown link [label](target), or a bare http(s) URL.
15var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+`)
16
17// richText is an Assistant's line as HTML, in the little Markdown it may
18// write (plan decision D16): runs of "- " or "* " lines are a bulleted
19// list, runs of "1. " or "1) " lines (1 to 3 digits) a numbered one, and
20// every other line is text with its newlines (the one next to a list
21// goes). In text and list items, a Markdown link or bare URL is a link
22// only when it goes to an http(s) address, and between links **x** is
23// bold, *x* and _x_ italic. Every other character is escaped: raw HTML,
24// relative paths and any other Markdown stay text. The panel's script does
25// the same (ask.js, rich). Its line breaks are read as a page reads them
26// (\r\n and \r are \n, and a NUL goes), so the two draw the same.
27func richText(text string) template.HTML { return richMarkdown(text, false) }
28
29// personText is the person's own message as HTML: richText's little
30// Markdown, but stricter about emphasis (strictEmphasis), since people
31// write arithmetic, file names and code: 2*3*4, x**2 and __init__.py stay
32// as written. ask.js (rich, strict) and the app (PersonMarkdown) do the
33// same.
34func personText(text string) template.HTML { return richMarkdown(text, true) }
35
36func richMarkdown(text string, strict bool) template.HTML { return markdown(text, strict, true) }
37
38// lookupSpace is the whitespace a lookup's answer ends an address at,
39// spelled out so Go, ask.js (with its u flag) and the app's ICU read it
40// alike: ASCII's, and Unicode's spaces and line breaks.
41const lookupSpace = `\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}`
42
43// mdLinkRE is a Markdown link, [label](target), in a lookup's answer;
44// plainLinkRE is linkRE for one, with lookupSpace for its whitespace.
45var (
46 mdLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)`)
47 plainLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)|https?://[^` + lookupSpace + `<>()\[\]"']+`)
48)
49
50// lookupMarkdown is a lookup's answer as HTML: personText's Markdown
51// (lists, and bold and italics at word boundaries) with no links at all,
52// since the only links under a reply are the sources Equipo recorded
53// (spec 2026-11-26-assistant-abilities §4.6). A Markdown link shows as
54// its words; a bare URL or an autolink stays as text. ask.js
55// (lookupMarkdown) and the app (LookupMarkdown) do the same.
56func lookupMarkdown(text string) template.HTML {
57 return markdown(mdLinkRE.ReplaceAllString(asPageReads.Replace(text), "$1"), true, false)
58}
59
60// markdown is richMarkdown, with links drawn only when links is set
61// (otherwise every address is text).
62func markdown(text string, strict, links bool) template.HTML {
63 var b strings.Builder
64 lines := strings.Split(asPageReads.Replace(text), "\n")
65 for i := 0; i < len(lines); {
66 kind, n, _ := listLine(lines[i])
67 if kind == "" {
68 j := i + 1
69 for j < len(lines) && !isListLine(lines[j]) {
70 j++
71 }
72 inline(&b, strings.Join(lines[i:j], "\n"), strict, links)
73 i = j
74 continue
75 }
76 if kind == "ol" && n != 1 {
77 b.WriteString(`<ol start="` + strconv.Itoa(n) + `">`)
78 } else {
79 b.WriteString("<" + kind + ">")
80 }
81 for ; i < len(lines); i++ {
82 k, _, item := listLine(lines[i])
83 if k != kind {
84 break
85 }
86 b.WriteString("<li>")
87 inline(&b, item, strict, links)
88 b.WriteString("</li>")
89 }
90 b.WriteString("</" + kind + ">")
91 }
92 return template.HTML(b.String())
93}
94
95var asPageReads = strings.NewReplacer("\r\n", "\n", "\r", "\n", "\x00", "")
96
97// numberRE is a numbered list line's start: 1 to 3 digits, "." or ")",
98// a space.
99var numberRE = regexp.MustCompile(`^(\d{1,3})[.)] `)
100
101// listLine is line's list ("ul" or "ol", else ""), its number for "ol",
102// and the item after the marker, which is never empty.
103func listLine(line string) (kind string, n int, item string) {
104 if len(line) > 2 && (line[0] == '-' || line[0] == '*') && line[1] == ' ' {
105 return "ul", 0, line[2:]
106 }
107 if m := numberRE.FindStringSubmatch(line); m != nil && len(line) > len(m[0]) {
108 n, _ := strconv.Atoi(m[1])
109 return "ol", n, line[len(m[0]):]
110 }
111 return "", 0, ""
112}
113
114func isListLine(line string) bool { k, _, _ := listLine(line); return k != "" }
115
116// inline writes text with its safe links, and bold and italics between
117// them. Without links, each address is written as text, untouched by
118// emphasis.
119func inline(b *strings.Builder, text string, strict, links bool) {
120 emphasis := emphasis
121 if strict {
122 emphasis = strictEmphasis
123 }
124 re := linkRE
125 if !links {
126 re = plainLinkRE
127 }
128 last := 0
129 for _, m := range re.FindAllStringSubmatchIndex(text, -1) {
130 end, label, target := m[1], "", ""
131 if m[2] >= 0 {
132 label, target = text[m[2]:m[3]], text[m[4]:m[5]]
133 } else {
134 target = strings.TrimRight(text[m[0]:m[1]], ".,;:!?")
135 end, label = m[0]+len(target), target
136 }
137 if !links {
138 // An address is text, whatever it is: no URL check decides
139 // how it is drawn.
140 emphasis(b, text[last:m[0]])
141 b.WriteString(html.EscapeString(text[m[0]:end]))
142 last = end
143 continue
144 }
145 href := equipo.WebURL(target)
146 if href == "" {
147 continue
148 }
149 emphasis(b, text[last:m[0]])
150 b.WriteString(`<a href="` + html.EscapeString(href) + `" target="_blank" rel="noopener">` + html.EscapeString(label) + `</a>`)
151 last = end
152 }
153 emphasis(b, text[last:])
154}
155
156// emphasis writes text escaped, with **x** as <strong> and *x* or _x_ as
157// <em>: x is the text up to the next same marker, not empty, on one line,
158// and neither starting nor ending with a space; an _ also needs no word
159// character just outside it, so snake_case stays as it is. Nothing nests.
160func emphasis(b *strings.Builder, text string) {
161 last := 0
162 for i := 0; i < len(text); {
163 c := text[i]
164 if c == '*' && strings.HasPrefix(text[i+1:], "*") {
165 if j := strings.Index(text[i+2:], "**"); j >= 0 && emphasized(text[i+2:i+2+j]) {
166 b.WriteString(html.EscapeString(text[last:i]) + "<strong>" + html.EscapeString(text[i+2:i+2+j]) + "</strong>")
167 i += j + 4
168 last = i
169 continue
170 }
171 }
172 if c == '*' || c == '_' && (i == 0 || !wordByte(text[i-1])) {
173 j := strings.IndexByte(text[i+1:], c)
174 if j >= 0 && emphasized(text[i+1:i+1+j]) && (c == '*' || i+2+j == len(text) || !wordByte(text[i+2+j])) {
175 b.WriteString(html.EscapeString(text[last:i]) + "<em>" + html.EscapeString(text[i+1:i+1+j]) + "</em>")
176 i += j + 2
177 last = i
178 continue
179 }
180 }
181 i++
182 }
183 b.WriteString(html.EscapeString(text[last:]))
184}
185
186// strictEmphasis is emphasis for the person's words: **x** and *x* or _x_
187// only at word boundaries. A run of markers opens only at the start or
188// after a character that is no word's (a space, punctuation), closes only
189// at the end or before one, and is exactly one * or _, or two *: so
190// 2*3*4, a*b + c*d, x**2 + y**2 and __init__.py stay as written. x is as
191// in emphasis. Each run looks only as far as the next of its marker, so it
192// is linear.
193func strictEmphasis(b *strings.Builder, text string) {
194 last := 0
195 for i := 0; i < len(text); {
196 c := text[i]
197 if c != '*' && c != '_' {
198 i++
199 continue
200 }
201 run := markerRun(text, i)
202 if (i == 0 || !wordByte(text[i-1])) && (run == 1 || run == 2 && c == '*') {
203 from := i + run
204 if k := strings.IndexByte(text[from:], c); k >= 0 {
205 j := from + k
206 end := j + markerRun(text, j)
207 if x := text[from:j]; end-j == run && emphasized(x) && (end == len(text) || !wordByte(text[end])) {
208 tag := "em"
209 if run == 2 {
210 tag = "strong"
211 }
212 b.WriteString(html.EscapeString(text[last:i]) + "<" + tag + ">" + html.EscapeString(x) + "</" + tag + ">")
213 i, last = end, end
214 continue
215 }
216 }
217 }
218 i += run
219 }
220 b.WriteString(html.EscapeString(text[last:]))
221}
222
223// markerRun is how many of text[i] follow one another from i.
224func markerRun(text string, i int) int {
225 n := 1
226 for i+n < len(text) && text[i+n] == text[i] {
227 n++
228 }
229 return n
230}
231
232// emphasized is whether x may be bold or italic: not empty, on one line,
233// with no space at either end.
234func emphasized(x string) bool {
235 return x != "" && !strings.Contains(x, "\n") && !space(x[0]) && !space(x[len(x)-1])
236}
237
238func space(c byte) bool { return c == ' ' || c == '\t' }
239
240// wordByte is whether c is part of a word: an ASCII letter, digit or _, or
241// any byte of a character beyond ASCII (ask.js sees the same in UTF-16).
242func wordByte(c byte) bool {
243 return c >= 0x80 || c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
244}
245
246// Rich is an Assistant's line with its links (richText), for templates.
247func (v askView) Rich(text string) template.HTML { return richText(text) }
248
249// sourceHost is u's host name as a source line shows it after the
250// source's title, without a leading "www.". ask.js has the same
251// (sourceHost).
252func sourceHost(u string) string {
253 p, err := url.Parse(u)
254 if err != nil {
255 return ""
256 }
257 return strings.TrimPrefix(strings.ToLower(p.Hostname()), "www.")
258}
259
260// RichPerson is the person's own message (personText), for templates.
261func (v askView) RichPerson(text string) template.HTML { return personText(text) }
262