oficina / memoria Public

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

Plain git — no account needed to clone.

Download

Download this file

1/* search.js — the typeahead, Enter, and the results page's AI answer.
2
3 App-owned, not vendored: rastrillo.js comes from estilo and is pinned
4 byte-identical by a gate; this file and drop.js are memoria's.
5
6 Same house rules as its neighbours: first-party, dependency-free, and
7 an enhancement rather than a mechanism. Delete this file and the
8 search form is still a GET form to "/" that returns the results page,
9 answer and all; what is lost is the typeahead and the AI answer
10 arriving on its own (the page then offers a link that asks for it).
11
12 Paul, 2026-10-29: "Google-style typeahead and then press enter to jump
13 to the search page where it gives an answer." So typing shows
14 suggestions under the box — the box's one checked answer, if there is
15 exactly one, and the documents the search finds — and never changes
16 the page under it. Enter submits the form, and the results page is
17 where the answer is. Arrow keys move a highlight over the suggestions
18 while the caret stays in the box; Enter on a highlighted one opens it.
19
20 The suggestions are the server's markup (/suggest), escaped there: this
21 file never builds HTML out of a document's text. */
22(function () {
23 "use strict";
24
25 // How long after a keystroke the suggestions are asked for. In-flight
26 // requests for an older prefix are aborted, so a short wait costs
27 // requests, not correctness.
28 var DEBOUNCE_MS = 60;
29
30 var form = document.querySelector("form[rst-search]");
31 var input = form && form.querySelector('input[type="search"]');
32 var box = document.querySelector("[rst-suggest-box]");
33 if (!form || !input || !box) return;
34 if (!window.fetch || !window.AbortController) return;
35
36 var timer = null;
37 var inflight = null;
38 var active = -1;
39
40 input.setAttribute("role", "combobox");
41 input.setAttribute("aria-autocomplete", "list");
42 input.setAttribute("aria-expanded", "false");
43 input.setAttribute("aria-controls", "rst-suggestions");
44 input.setAttribute("autocomplete", "off");
45
46 function items() {
47 return Array.prototype.slice.call(box.querySelectorAll("[rst-suggest-item]"));
48 }
49
50 function close() {
51 box.hidden = true;
52 box.innerHTML = "";
53 active = -1;
54 input.setAttribute("aria-expanded", "false");
55 input.removeAttribute("aria-activedescendant");
56 }
57
58 function highlight(i) {
59 var all = items();
60 active = i;
61 all.forEach(function (el, n) {
62 if (n === i) {
63 el.setAttribute("rst-suggest-active", "");
64 el.parentNode.setAttribute("aria-selected", "true");
65 input.setAttribute("aria-activedescendant", el.parentNode.id);
66 } else {
67 el.removeAttribute("rst-suggest-active");
68 el.parentNode.setAttribute("aria-selected", "false");
69 }
70 });
71 }
72
73 function suggest(q) {
74 if (inflight) inflight.abort();
75 var ctl = new AbortController();
76 inflight = ctl;
77 fetch("/suggest?q=" + encodeURIComponent(q), { signal: ctl.signal, credentials: "same-origin" })
78 .then(function (res) {
79 if (res.status === 204) return "";
80 // A session that ran out answers with a redirect to sign-in,
81 // which fetch follows; that page is not suggestions.
82 if (!res.ok || res.redirected) throw new Error("suggest " + res.status);
83 return res.text();
84 })
85 .then(function (html) {
86 if (ctl !== inflight) return;
87 inflight = null;
88 // Suggestions for a prefix the box has moved on from are not
89 // shown: the abort usually stops them, and this holds when not.
90 if (input.value.trim() !== q || !html) {
91 if (!html) close();
92 return;
93 }
94 box.innerHTML = html;
95 var list = box.querySelector("[rst-suggest-list]");
96 if (list) list.id = "rst-suggestions";
97 // Copy needs a script, so it shows only once there is one.
98 Array.prototype.forEach.call(box.querySelectorAll("[rst-suggest-copy]"), function (b) {
99 b.hidden = !(navigator.clipboard && navigator.clipboard.writeText);
100 });
101 items().forEach(function (el, n) {
102 el.parentNode.id = "rst-suggestion-" + n;
103 el.parentNode.setAttribute("aria-selected", "false");
104 // Clicking a suggestion is a link being followed; keeping the
105 // focus in the box until then stops the blur closing the list
106 // under the pointer.
107 el.addEventListener("mousedown", function (e) { e.preventDefault(); });
108 });
109 active = -1;
110 box.hidden = false;
111 input.setAttribute("aria-expanded", "true");
112 })
113 .catch(function () {
114 // A failed suggestion is no suggestion; Enter still searches.
115 if (ctl === inflight) {
116 inflight = null;
117 close();
118 }
119 });
120 }
121
122 /* Clear (Paul, 2026-10-31). The link goes to the front page without a
123 script; with one it empties the box, closes the suggestions and
124 keeps the caret where it was, and it shows only while the box holds
125 something. */
126 var clearLink = form.querySelector("[rst-search-clear]");
127 function syncClear() {
128 if (clearLink) clearLink.hidden = input.value === "";
129 }
130 if (clearLink) {
131 clearLink.addEventListener("click", function (e) {
132 if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
133 e.preventDefault();
134 input.value = "";
135 if (inflight) inflight.abort();
136 inflight = null;
137 close();
138 syncClear();
139 input.focus();
140 });
141 }
142 input.addEventListener("input", syncClear);
143
144 input.addEventListener("input", function () {
145 if (timer) clearTimeout(timer);
146 var q = input.value.trim();
147 if (q === "") {
148 if (inflight) inflight.abort();
149 inflight = null;
150 close();
151 return;
152 }
153 timer = setTimeout(function () {
154 timer = null;
155 suggest(input.value.trim());
156 }, DEBOUNCE_MS);
157 });
158
159 input.addEventListener("keydown", function (e) {
160 if (e.isComposing || e.keyCode === 229) return;
161 var all = items();
162 if (e.key === "ArrowDown" || e.key === "ArrowUp") {
163 if (box.hidden || !all.length) return;
164 e.preventDefault();
165 var n = all.length;
166 highlight(e.key === "ArrowDown" ? (active + 1) % n : (active <= 0 ? n - 1 : active - 1));
167 return;
168 }
169 if (e.key === "Escape" && !box.hidden) {
170 e.preventDefault();
171 close();
172 return;
173 }
174 if (e.key === "Enter" && !box.hidden && active >= 0 && all[active]) {
175 // A highlighted suggestion is where Enter goes. With none, Enter is
176 // the form's own submit: the results page.
177 e.preventDefault();
178 window.location.assign(all[active].href);
179 }
180 });
181
182 /* Copy the answer (Paul, 2026-10-31: "cmd+c to copy, and a little Copy
183 button"). The value is the document's own span, carried on the
184 button as text by the server. ⌘C/Ctrl+C copies it while the list is
185 open, unless something in the box is selected: then the keystroke is
186 the ordinary copy of that selection. */
187 function factValue() {
188 var b = box.hidden ? null : box.querySelector("[rst-suggest-copy]");
189 return b ? b.getAttribute("rst-copy-value") : null;
190 }
191 function copied(button) {
192 if (!button) return;
193 button.textContent = "Copied";
194 setTimeout(function () { button.textContent = "Copy"; }, 1500);
195 }
196 function copy(text, button) {
197 if (!navigator.clipboard || !navigator.clipboard.writeText) return false;
198 navigator.clipboard.writeText(text).then(function () { copied(button); }, function () {});
199 return true;
200 }
201 box.addEventListener("mousedown", function (e) {
202 // Keep the caret in the box, so the list does not close under the
203 // pointer before the click lands.
204 if (e.target.closest && e.target.closest("[rst-suggest-copy]")) e.preventDefault();
205 });
206 box.addEventListener("click", function (e) {
207 var b = e.target.closest && e.target.closest("[rst-suggest-copy]");
208 if (!b) return;
209 e.preventDefault();
210 copy(b.getAttribute("rst-copy-value"), b);
211 });
212 input.addEventListener("keydown", function (e) {
213 if (e.key !== "c" || !(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey) return;
214 if (input.selectionStart !== input.selectionEnd) return;
215 var v = factValue();
216 if (v === null) return;
217 if (copy(v, box.querySelector("[rst-suggest-copy]"))) e.preventDefault();
218 });
219
220 input.addEventListener("blur", function () { close(); });
221 form.addEventListener("submit", function () { close(); });
222 // Back to a page whose box still holds text: nothing is open.
223 window.addEventListener("pageshow", function () { close(); syncClear(); });
224})();
225
226/* Recent searches (Paul, 2026-10-30: "a short history of the last few
227 searches"). Kept in this browser's localStorage and nowhere else: a
228 query is content, and memoria keeps no query on the server, so the
229 list never leaves the device and Clear empties it. A results page
230 records its own query (whatever brought it there: Enter, a link, a
231 reload); the front page lists them, newest first, as links that
232 search again. Every string goes in as text, never as markup. */
233(function () {
234 "use strict";
235 var KEY = "memoria.recent-searches";
236 var MAX = 6;
237 var store;
238 try {
239 store = window.localStorage;
240 store.getItem(KEY);
241 } catch (e) {
242 return; // storage off: no history, and nothing else changes
243 }
244 function load() {
245 try {
246 var v = JSON.parse(store.getItem(KEY) || "[]");
247 return Array.isArray(v) ? v.filter(function (q) { return typeof q === "string" && q; }) : [];
248 } catch (e) {
249 return [];
250 }
251 }
252 var region = document.querySelector('[rst-refresh="results"]');
253 var q = region && region.getAttribute("rst-search-results-for");
254 if (q) {
255 var list = load().filter(function (x) { return x.toLowerCase() !== q.toLowerCase(); });
256 list.unshift(q);
257 store.setItem(KEY, JSON.stringify(list.slice(0, MAX)));
258 return;
259 }
260 var section = document.querySelector("[rst-home-history]");
261 if (!section) return;
262 var ul = section.querySelector("[rst-home-list]");
263 var past = load();
264 if (!past.length) return;
265 // rastrillo's list row, as the server draws "Recently updated": the
266 // one link covers the row.
267 past.forEach(function (x) {
268 var li = document.createElement("li");
269 li.setAttribute("rst-row", "");
270 var main = document.createElement("span");
271 main.setAttribute("rst-row-main", "");
272 var a = document.createElement("a");
273 a.href = "/?q=" + encodeURIComponent(x);
274 a.textContent = x;
275 main.appendChild(a);
276 li.appendChild(main);
277 ul.appendChild(li);
278 });
279 section.hidden = false;
280 var clear = section.querySelector("[rst-home-clear]");
281 if (clear) clear.addEventListener("click", function () {
282 store.removeItem(KEY);
283 section.hidden = true;
284 });
285})();
286
287/* The results page's AI answer (§8.11). The page never waits on the
288 model: a page with an answer slot asks GET /answer once it has loaded,
289 and the slot says the AI is being asked. GET /answer runs its own ruled
290 search and takes only the query. A 204 means it no longer wants to
291 answer (a card answers it now, or nothing came back), and the slot
292 goes. */
293(function () {
294 "use strict";
295 if (!window.fetch) return;
296 var region = document.querySelector('[rst-refresh="results"]');
297 var q = region && region.getAttribute("rst-search-results-for");
298 var slot = region && region.querySelector("[rst-answer-pending]");
299 if (!q || !slot) return;
300 slot.removeAttribute("rst-answer-pending");
301 slot.textContent = "🤖 Asking AI…";
302 fetch("/answer?q=" + encodeURIComponent(q), { credentials: "same-origin" })
303 .then(function (res) {
304 if (res.status === 204) return null;
305 if (!res.ok || res.redirected) throw new Error("answer " + res.status);
306 return res.text();
307 })
308 .then(function (html) {
309 if (html === null) {
310 slot.remove();
311 return;
312 }
313 slot.innerHTML = html;
314 })
315 .catch(function () {
316 slot.textContent = "🤖 The AI answer failed.";
317 });
318})();
319
320/* 👍 on an AI answer saves in place (§8.11, Paul 2026-10-27). Delegated,
321 because the answer arrives after load. 👎 is left to the form: it goes
322 to the page that asks what was wrong. A failed save falls back to the
323 form too, so the rating is never silently lost. */
324(function () {
325 "use strict";
326 if (!window.fetch || !window.URLSearchParams) return;
327 document.addEventListener("submit", function (e) {
328 var f = e.target;
329 if (!f.matches || !f.matches("[rst-ai-feedback]")) return;
330 var b = e.submitter;
331 if (!b || b.value !== "up") return;
332 e.preventDefault();
333 var body = new URLSearchParams();
334 body.set("handle", f.querySelector('input[name="handle"]').value);
335 body.set("verdict", "up");
336 body.set("inline", "1");
337 fetch("/answer/feedback", { method: "POST", body: body, credentials: "same-origin" })
338 .then(function (res) {
339 if (res.status !== 204) throw new Error("feedback " + res.status);
340 f.textContent = "Thanks.";
341 })
342 .catch(function () {
343 var up = document.createElement("input");
344 up.type = "hidden";
345 up.name = "verdict";
346 up.value = "up";
347 f.appendChild(up);
348 f.submit();
349 });
350 });
351})();
352
353/* The whole result opens it (Paul, 2026-10-26: "Can the whole segment be
354 clickable rather than just the title?"). A click anywhere on a result
355 follows its title's link, unless the click was selecting text: a drag
356 that moved, a selection left on the page, or a double-click: the first
357 click waits briefly and then goes nowhere if a selection has appeared,
358 which is what a double-click leaves. Cmd, Ctrl or Shift
359 opens a new tab, as they do on a link. Links and controls inside a
360 result keep their own clicks. The title stays the one real link, so
361 keyboard and screen-reader use is unchanged, and without this script
362 only the title is clickable. */
363(function () {
364 "use strict";
365 var WAIT_MS = 220;
366 var downAt = null;
367 document.documentElement.setAttribute("rst-results-clickable", "");
368 function selecting() {
369 return !!(window.getSelection && String(window.getSelection()));
370 }
371 document.addEventListener("mousedown", function (e) {
372 downAt = [e.clientX, e.clientY];
373 });
374 document.addEventListener("click", function (e) {
375 if (e.button !== 0 || !e.target.closest) return;
376 var row = e.target.closest("[rst-result]");
377 if (!row || e.target.closest("a, button, input, select, textarea, label")) return;
378 var link = row.querySelector("[rst-result-title]");
379 if (!link) return;
380 if (e.detail > 1 || selecting()) return;
381 if (downAt && (Math.abs(e.clientX - downAt[0]) > 4 || Math.abs(e.clientY - downAt[1]) > 4)) return;
382 if (e.metaKey || e.ctrlKey || e.shiftKey) {
383 window.open(link.href, "_blank", "noopener");
384 return;
385 }
386 setTimeout(function () {
387 if (!selecting()) window.location.assign(link.href);
388 }, WAIT_MS);
389 });
390})();
391