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 "bytes"
5 "embed"
6 "html/template"
7 "net/http"
8 "strings"
9 "time"
10
11 "amadan.net/oficina/estilo.git/chrome"
12 "amadan.net/oficina/estilo.git/credits"
13 estilomenu "amadan.net/oficina/estilo.git/menu"
14 "amadan.net/oficina/home/connect"
15 "amadan.net/rastrillo/rastrillo"
16 "amadan.net/rastrillo/rastrillo/ui"
17
18 "amadan.net/oficina/memoria/internal/memoria/icons"
19)
20
21//go:embed templates static
22var appFS embed.FS
23
24// assets fingerprints static/: {{asset "static/tokens.css"}} in a
25// template returns a content-hashed URL, served immutable-cacheable by
26// the handler App mounts.
27var assets = rastrillo.NewAssets(appFS)
28
29// pages is one *template.Template per page, each combining layout.html
30// with that page's own file — kept separate so every page can define a
31// template named "content" without colliding with the others.
32var pages = map[string]*template.Template{}
33
34// fragments holds the templates that are also served on their own, with
35// no layout around them. results.html is parsed into both this and every
36// page, so the region search.js swaps in on a keystroke and the region a
37// scriptless form submit renders are the same markup from the same file.
38var fragments *template.Template
39
40// funcs is shared by both sets. Two call sites, one map: a helper added
41// for a page and forgotten for the fragment would fail at execute time,
42// on the request, rather than at parse time.
43func funcs() template.FuncMap {
44 return template.FuncMap{
45 "asset": assets.Path,
46 // The app's own icon set (internal/memoria/icons), scaffolded
47 // by rastrillo new. iconAssets is whatever <head> markup the
48 // chosen delivery needs — empty for the vendored-inline
49 // default, so the layout calls it unconditionally and
50 // switching delivery later needs no template edit.
51 "icon": icons.Icon,
52 "iconAssets": icons.Assets,
53 "safeSnippet": safeSnippet,
54 "sourceName": sourceName,
55 "tone": tone,
56 "inc": func(i int) int { return i + 1 },
57 }
58}
59
60func init() {
61 // Every page is the layout, the results region (the index and the
62 // fragment share it), the page's own file, and the suite's chrome:
63 // estilo's bar, account menu, switcher, error body and sign-in door
64 // (chrome), their menu rows (menu), and the rastrillo partials the door
65 // is built from (ui). ui.Funcs goes first and funcs() over it, so icon
66 // and iconAssets stay this app's own set rather than reverting to
67 // rastrillo's built-in one (ui.FuncsWith's documented trap).
68 for _, name := range []string{"index", "documents", "add", "document", "delete", "correct", "feedback", "reports", "connectors", "notion", "home", "credits", "signin", "error"} {
69 pages[name] = template.Must(template.Must(template.Must(template.Must(template.New("layout").
70 Funcs(ui.Funcs()).Funcs(funcs()).
71 ParseFS(appFS, "templates/layout.html", "templates/results.html", "templates/"+name+".html")).
72 ParseFS(ui.Templates(), "*.html")).
73 ParseFS(chrome.Templates(), "templates/*.html")).
74 ParseFS(estilomenu.Templates(), "templates/*.html"))
75 }
76 pages["credits"] = template.Must(pages["credits"].ParseFS(credits.Templates(), "templates/credits.html"))
77 pages["home"] = template.Must(pages["home"].ParseFS(connect.Templates(), "templates/home_link.html"))
78 // ui.Funcs first here too: results.html is on rastrillo's
79 // localizer-first syntax ({{$L := localizer $}}, migrate-templates),
80 // so the fragment set needs the framework's functions as the pages do.
81 fragments = template.Must(template.New("fragments").
82 Funcs(ui.Funcs()).Funcs(funcs()).
83 ParseFS(appFS, "templates/results.html"))
84}
85
86// pageFor is the page data every layout needs, for this request: the
87// chrome (Frame), and the footer's passage count and AI state. The count
88// is read only for somebody signed in, because only they are told it.
89func (a *app) pageFor(r *http.Request, f frame) page {
90 p := page{Frame: a.frameFor(r, f), ModelOn: a.modelOn()}
91 if p.Frame.Signed {
92 p.Chunks = a.chunkCount()
93 // Team mode: the corpus is counted only for a Member. Anyone
94 // else is told the count is unavailable, which is true.
95 if !a.teamReaches(r) {
96 p.Chunks = -1
97 }
98 }
99 return p
100}
101
102// render executes name's layout into a buffer before anything touches
103// the wire: a template error becomes a clean 500 instead of garbage
104// appended to a half-written page, and headers (flash cookies, say)
105// stay settable until the status line is written.
106func render(w http.ResponseWriter, name string, data any) {
107 renderStatus(w, name, data, http.StatusOK)
108}
109
110// renderStatus is render with a status other than 200: the refused door
111// is a 403 (app.refused).
112func renderStatus(w http.ResponseWriter, name string, data any, status int) {
113 var buf bytes.Buffer
114 if err := pages[name].ExecuteTemplate(&buf, "layout", data); err != nil {
115 http.Error(w, "something went wrong", http.StatusInternalServerError)
116 return
117 }
118 if status != http.StatusOK {
119 w.Header().Set("Content-Type", "text/html; charset=utf-8")
120 w.WriteHeader(status)
121 }
122 buf.WriteTo(w)
123}
124
125// renderFragment executes one template with no layout around it, for the
126// endpoints a script calls rather than a person navigates to.
127//
128// Buffered for the same reason render is: a template error becomes a
129// clean 500 rather than half a list of results, and a half-swapped
130// results region is the plausible-empty-list failure wearing a hat.
131func renderFragment(w http.ResponseWriter, name string, data any) {
132 var buf bytes.Buffer
133 if err := fragments.ExecuteTemplate(&buf, name, data); err != nil {
134 http.Error(w, "something went wrong", http.StatusInternalServerError)
135 return
136 }
137 w.Header().Set("Content-Type", "text/html; charset=utf-8")
138 buf.WriteTo(w)
139}
140
141// safeSnippet renders an FTS5 snippet, which arrives as document text with
142// <mark> tags inserted around the matched terms.
143//
144// The text around those tags is content someone stored, so it cannot be
145// trusted — a document containing "<script>" must not execute in a search
146// result. Everything is therefore escaped first and exactly two tags are
147// re-admitted afterwards. Doing it the other way round (trusting the
148// snippet and escaping selectively) is the version that ships an XSS.
149func safeSnippet(s string) template.HTML {
150 escaped := template.HTMLEscapeString(s)
151 escaped = strings.ReplaceAll(escaped, "&lt;mark&gt;", "<mark>")
152 escaped = strings.ReplaceAll(escaped, "&lt;/mark&gt;", "</mark>")
153 return template.HTML(escaped)
154}
155
156// tone maps a flash kind to the design system's tone vocabulary.
157//
158// **The tone attribute is `rst-tone`, and getting here took three tries.**
159// tokens.css pairs every kind: a class spelling and an attribute spelling,
160// weighing the same. For a callout's tone those are
161// `.rst-callout[data-tone="negative"]` and
162// `[rst-callout][rst-tone~="negative"]` — and the header says so directly:
163// *"rst-tone carries the four tones that data-tone carries today."*
164//
165// Attempt one was `rst-callout="danger"`: a value on the kind attribute,
166// which nothing selects. Attempt two was `[rst-callout] data-tone=...`:
167// half of one pair and half of the other, matching neither, and its tests
168// passed because the string `data-tone="negative"` does occur in the
169// stylesheet — inside the *class* selector standing next to the one that
170// was needed. Both rendered every flash in the product as an untoned
171// callout: the right box, the wrong colour, on every error a reader is
172// meant to act on.
173//
174// The lesson is not about tones. **Grepping for a string is not reading a
175// selector**, and a check that greps will confirm any spelling that
176// appears anywhere in the file.
177//
178// The default is deliberately the loud one. A flash whose kind nobody
179// recognised is more likely to be an error than a compliment, and an
180// unstyled warning is a worse failure than an over-coloured success.
181func tone(kind string) string {
182 switch kind {
183 case "good":
184 return "positive"
185 case "warn":
186 return "warning"
187 default:
188 return "negative"
189 }
190}
191
192// sourceName is how a page names where a document came from. The stored
193// values are identifiers ("paste", "notion"); a reader sees words.
194// Sibling apps are stored already named ("Docs") and pass through.
195func sourceName(s string) string {
196 switch s {
197 case "paste":
198 return "Pasted"
199 case "upload":
200 return "Uploaded"
201 case "notion":
202 return "Notion"
203 }
204 return s
205}
206
207// stamp is how a page prints a stored time: converted to UTC and saying
208// so. Since rastrillo fb806a2 the driver hands every stored time back in
209// UTC, where before it came back in the host's zone, so an unlabelled
210// clock reading changed meaning on any host not in UTC. The sources page
211// already said UTC; now every stored time does (TestStampSaysUTC).
212func stamp(t time.Time) string { return t.UTC().Format("2 Jan 2006, 15:04 UTC") }
213