oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "html/template"
5 "regexp"
6 "strings"
7)
8
9// The document page renders a passage as a document rather than as one
10// preformatted paragraph (Paul, 2026-10-30: "de-jankifying the documents
11// themselves … formatted appropriately depending on type").
12//
13// The input is what memoria stores: the Markdown subset the Notion
14// connector writes (notion/markdown.go — lists, numbered lists, to-dos,
15// quotes, code fences, dividers, tables), a database row's "Name: value"
16// property lines, and whatever someone pasted or uploaded. **Escaping
17// runs first and the structure is added around escaped text**, as
18// boldOnly does for an AI answer: no markup in a document can become
19// markup on the page, and the only element built from a document's own
20// characters is a link, and only to http(s). A remote image is never
21// loaded: an image in the source is a caption line by the time it is
22// stored (notion/markdown.go), and Markdown image syntax is text here.
23
24var (
25 listItem = regexp.MustCompile(`^(\s*)(?:[-*]|(\d+)\.)\s+(.*)$`)
26 todoItem = regexp.MustCompile(`^\[( |x|X)\]\s+(.*)$`)
27 property = regexp.MustCompile(`^([^:\n]{1,40}):\s+(.+)$`)
28 bareURL = regexp.MustCompile(`https?://[^\s<>"'` + "`" + `]+`)
29 tableRow = regexp.MustCompile(`^\s*\|.*\|\s*$`)
30 tableRule = regexp.MustCompile(`^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$`)
31 headingRow = regexp.MustCompile(`^(#{1,6})\s+(.*)$`)
32)
33
34// renderPassage turns one stored passage into the document page's HTML.
35func renderPassage(text string) template.HTML {
36 lines := strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n")
37 var b strings.Builder
38 var para []string
39 flush := func() {
40 if len(para) == 0 {
41 return
42 }
43 writeParagraph(&b, para)
44 para = nil
45 }
46 for i := 0; i < len(lines); i++ {
47 line := lines[i]
48 trimmed := strings.TrimSpace(line)
49 switch {
50 case trimmed == "":
51 flush()
52 case strings.HasPrefix(trimmed, "```"):
53 flush()
54 var code []string
55 for i++; i < len(lines) && !strings.HasPrefix(strings.TrimSpace(lines[i]), "```"); i++ {
56 code = append(code, lines[i])
57 }
58 b.WriteString("<pre rst-doc-code><code>" + template.HTMLEscapeString(strings.Join(code, "\n")) + "</code></pre>")
59 case trimmed == "---" || trimmed == "***":
60 flush()
61 b.WriteString("<hr>")
62 case headingRow.MatchString(trimmed):
63 flush()
64 m := headingRow.FindStringSubmatch(trimmed)
65 b.WriteString("<h4 rst-doc-subhead>" + inline(m[2]) + "</h4>")
66 case tableRow.MatchString(line):
67 flush()
68 var rows []string
69 for ; i < len(lines) && tableRow.MatchString(lines[i]); i++ {
70 rows = append(rows, lines[i])
71 }
72 i--
73 writeTable(&b, rows)
74 case listItem.MatchString(line):
75 flush()
76 var items []string
77 for ; i < len(lines) && (listItem.MatchString(lines[i]) || strings.TrimSpace(lines[i]) == ""); i++ {
78 if strings.TrimSpace(lines[i]) != "" {
79 items = append(items, lines[i])
80 }
81 }
82 i--
83 writeList(&b, items)
84 case strings.HasPrefix(trimmed, ">"):
85 flush()
86 var quote []string
87 for ; i < len(lines) && strings.HasPrefix(strings.TrimSpace(lines[i]), ">"); i++ {
88 quote = append(quote, inline(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(lines[i]), ">"))))
89 }
90 i--
91 b.WriteString("<blockquote rst-doc-quote>" + strings.Join(quote, "<br>") + "</blockquote>")
92 default:
93 para = append(para, line)
94 }
95 }
96 flush()
97 return template.HTML(b.String())
98}
99
100// writeParagraph writes one blank-line-separated block. Two or more lines
101// that are all "Name: value" — a database row's properties, or a pasted
102// contact block — are a property list; anything else is a paragraph whose
103// single line breaks are kept, because an address written over three
104// lines is three lines.
105func writeParagraph(b *strings.Builder, lines []string) {
106 if len(lines) >= 2 {
107 all := true
108 for _, l := range lines {
109 if !property.MatchString(strings.TrimSpace(l)) {
110 all = false
111 break
112 }
113 }
114 if all {
115 b.WriteString("<dl rst-doc-props>")
116 for _, l := range lines {
117 m := property.FindStringSubmatch(strings.TrimSpace(l))
118 b.WriteString("<dt>" + inline(m[1]) + "</dt><dd>" + inline(m[2]) + "</dd>")
119 }
120 b.WriteString("</dl>")
121 return
122 }
123 }
124 parts := make([]string, len(lines))
125 for i, l := range lines {
126 parts[i] = inline(strings.TrimSpace(l))
127 }
128 b.WriteString("<p>" + strings.Join(parts, "<br>") + "</p>")
129}
130
131// writeList writes a run of list items. Nesting is the source's own
132// indent, two spaces a level as notion/markdown.go writes it, carried as
133// rst-depth for the stylesheet rather than rebuilt as nested lists.
134func writeList(b *strings.Builder, items []string) {
135 ordered := listItem.FindStringSubmatch(items[0])[2] != ""
136 tag := "ul"
137 if ordered {
138 tag = "ol"
139 }
140 b.WriteString("<" + tag + " rst-doc-list>")
141 for _, it := range items {
142 m := listItem.FindStringSubmatch(it)
143 depth := len(strings.ReplaceAll(m[1], "\t", " ")) / 2
144 if depth > 3 {
145 depth = 3
146 }
147 attr := ""
148 if depth > 0 {
149 attr = ` rst-depth="` + string(rune('0'+depth)) + `"`
150 }
151 body := m[3]
152 if t := todoItem.FindStringSubmatch(body); t != nil {
153 box := "☐"
154 if t[1] != " " {
155 box = "☑"
156 }
157 b.WriteString("<li" + attr + " rst-doc-todo>" + box + " " + inline(t[2]) + "</li>")
158 continue
159 }
160 b.WriteString("<li" + attr + ">" + inline(body) + "</li>")
161 }
162 b.WriteString("</" + tag + ">")
163}
164
165// writeTable writes "| a | b |" rows. A Markdown rule row under the first
166// marks it as the header; Notion's rows carry no rule, so every row is a
167// body row there.
168func writeTable(b *strings.Builder, rows []string) {
169 cells := func(row string) []string {
170 row = strings.TrimSpace(row)
171 row = strings.TrimSuffix(strings.TrimPrefix(row, "|"), "|")
172 parts := strings.Split(row, "|")
173 for i := range parts {
174 parts[i] = strings.TrimSpace(parts[i])
175 }
176 return parts
177 }
178 b.WriteString("<div rst-doc-table><table>")
179 start := 0
180 if len(rows) > 1 && tableRule.MatchString(rows[1]) {
181 b.WriteString("<thead><tr>")
182 for _, c := range cells(rows[0]) {
183 b.WriteString("<th>" + inline(c) + "</th>")
184 }
185 b.WriteString("</tr></thead>")
186 start = 2
187 }
188 b.WriteString("<tbody>")
189 for _, r := range rows[start:] {
190 b.WriteString("<tr>")
191 for _, c := range cells(r) {
192 b.WriteString("<td>" + inline(c) + "</td>")
193 }
194 b.WriteString("</tr>")
195 }
196 b.WriteString("</tbody></table></div>")
197}
198
199// inline renders a run of text: http(s) URLs become links, and between
200// them balanced **bold** is the only markup (boldOnly). The URL is taken
201// from the raw text and escaped into both the attribute and the label, so
202// nothing in it can close either.
203func inline(s string) string {
204 var b strings.Builder
205 last := 0
206 for _, m := range bareURL.FindAllStringIndex(s, -1) {
207 end := m[1]
208 // A sentence's own punctuation is not part of its link.
209 for end > m[0] && strings.ContainsRune(".,;:!?)]'\"", rune(s[end-1])) {
210 end--
211 }
212 b.WriteString(string(boldOnly(s[last:m[0]])))
213 u := template.HTMLEscapeString(s[m[0]:end])
214 b.WriteString(`<a href="` + u + `" rel="noopener noreferrer nofollow">` + u + `</a>`)
215 last = end
216 }
217 b.WriteString(string(boldOnly(s[last:])))
218 return b.String()
219}
220