1// ermite.js: the behaviour of the pages that htmx and hx-live do not give.
2//
3// 1. Keys. A global key *sequence* state machine ("g" then "h") and the
4// keystrokes aimed at inputs cannot be declared with hx-on. The keydown
5// handler only translates keys into DOM events named "k-<name>" on <body>;
6// keys.templ binds each of them (hx-on, one line each) to a function of
7// window.ermite below, which does the work: row cursor, dialogs, filters,
8// diff layout, permalink.
9// 2. Clicks on [data-fire] elements fire the same events (header buttons).
10// 3. ermiteLive applies the fragments of the event stream (see events.go).
11// 4. The file of the diff in view is marked in the table of contents.
12// 5. A handler that fails is shown in the hint badge.
13// 6. The lines a diff hides load in place (ermiteGaps; e and E).
14// 7. The service worker (ermiteInstall).
15// 8. Chip lists kept on one line, with a … chip (ermiteFit).
16// 9. The layout of the home page, remembered in the browser (ermiteLayout).
17// 10. The wide mode: every page takes the whole width (ermiteWide).
18//
19// Preferences are kept by ermiteStore (store.js, loaded first).
20(() => {
21 // Marks the page as scripted: what does nothing without scripts (the filters,
22 // the "go to" and help buttons) is hidden until this class is set (see the
23 // utilities of 10-base.css).
24 document.documentElement.classList.add('js');
25
26 const $ = (sel, root = document) => root.querySelector(sel);
27 const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
28 const body = () => document.body;
29
30 // flash shows a message in the hint badge (body[data-flash], a status
31 // region), then clears it unless another message came in the meantime.
32 let flashTimer = 0;
33 const flash = (msg, ms = 2000) => {
34 body().dataset.flash = msg;
35 clearTimeout(flashTimer);
36 flashTimer = setTimeout(() => (body().dataset.flash = ''), ms);
37 };
38
39 const visibleRows = () => $$('[data-rows] > :not([hidden])');
40 // setCursor puts data-cursor on el and takes it from the others.
41 const setCursor = (el, others) => {
42 for (const o of others) if (o !== el) o.removeAttribute('data-cursor');
43 el.setAttribute('data-cursor', '');
44 };
45 const scrollPage = (to) => {
46 scrollTo(0, to);
47 $('#main')?.scrollTo(0, to);
48 };
49
50 const ermite = {
51 flash,
52 fire(name) {
53 body().dispatchEvent(new CustomEvent('k-' + name, { bubbles: false }));
54 },
55
56 // Row cursor: j / k. In the side panel they move the focus between its
57 // controls instead.
58 move(d) {
59 if ($('dialog[open]')) return;
60 if (window.ermiteMR?.stepFiles(d) || window.ermiteRail.step(d)) return;
61 const rows = visibleRows();
62 if (!rows.length) {
63 scrollBy(0, d * 180);
64 $('#main')?.scrollBy(0, d * 180);
65 return;
66 }
67 const i = rows.findIndex((r) => r.hasAttribute('data-cursor'));
68 const j = Math.max(0, Math.min(rows.length - 1, i + d));
69 setCursor(rows[j], $$('[data-rows] > [data-cursor]'));
70 rows[j].scrollIntoView({ block: 'nearest' });
71 window.ermiteTree?.sync(rows[j]);
72 window.ermiteFinder?.sync(); // the rows may be the file finder's options
73 const mark = j + 1 + '/' + rows.length;
74 body().dataset.nav = mark;
75 setTimeout(() => body().dataset.nav === mark && (body().dataset.nav = ''), 1500);
76 },
77 // gg / G: first or last row, or the top or bottom of the page.
78 edge(last) {
79 const rows = visibleRows();
80 const row = last ? rows.at(-1) : rows[0];
81 if (!row) return scrollPage(last ? 1e9 : 0);
82 setCursor(row, $$('[data-rows] > [data-cursor]'));
83 row.scrollIntoView({ block: 'nearest' });
84 window.ermiteTree?.sync(row);
85 window.ermiteFinder?.sync();
86 },
87 open() {
88 if ($('dialog[open]') || window.ermiteTree?.open()) return;
89 $('[data-cursor] a')?.click();
90 },
91 // l / h: in the Files view, open a directory or a file / close a directory
92 // or go up. Elsewhere: into the side panel (the current file of a merge
93 // request, else its main action, else its first control) and back to the
94 // content. Enter then activates the control.
95 rail(into) {
96 if ($('dialog[open]')) return;
97 if (window.ermiteTree?.key(into)) return;
98 if (into && window.ermiteMR?.focusFiles()) return flash('files · j k move · enter open · h back');
99 if (!into && window.ermiteMR?.leaveFiles()) return;
100 const msg = into ? window.ermiteRail.enter() : window.ermiteRail.leave();
101 if (msg) flash(msg);
102 },
103 // openFile opens a file of the diff the table of contents links to.
104 openFile(id) {
105 const f = document.getElementById(id);
106 if (f) f.open = true;
107 },
108 focusFilter() {
109 $('[data-filter]')?.focus();
110 },
111 go(sel) {
112 $(sel)?.click();
113 },
114 tab(key) {
115 $(`.tabs [data-key=${key}]`)?.click();
116 },
117
118 // The preference "single-key shortcuts" (ermiteKeys): the checkbox of the
119 // help dialog and the action of the palette.
120 setKeysOff(off) {
121 window.ermiteKeys.set(off);
122 },
123 toggleKeys() {
124 const off = !window.ermiteKeys.off();
125 window.ermiteKeys.set(off);
126 ermite.closeDialogs();
127 flash(off ? 'single-key shortcuts off · ctrl k and esc still work' : 'single-key shortcuts on');
128 },
129
130 // Dialogs.
131 closeDialogs() {
132 for (const d of $$('dialog[open]')) d.close();
133 },
134 dialog(id, focusId) {
135 const d = document.getElementById(id);
136 if (!d) return;
137 ermite.closeDialogs();
138 d.showModal();
139 if (id === 'panel-cmd') window.ermiteCmd?.sync();
140 if (focusId) document.getElementById(focusId)?.focus();
141 },
142
143 // filter hides the rows that do not contain the text of an input. The
144 // input says which rows (data-filter, or data-pick for a list without a
145 // cursor) and, optionally, the groups to hide when they have no row left
146 // (data-groups). The cursor goes to the first row left.
147 filter(input) {
148 const rows = ermite.hide(input);
149 if (input.dataset.filter) {
150 const first = rows.find((r) => !r.hidden);
151 for (const r of rows) r.toggleAttribute('data-cursor', r === first);
152 }
153 },
154 // hide applies the text of a filter input to its rows and groups, without
155 // moving the cursor, and returns the rows.
156 hide(input) {
157 const t = input.value.toLowerCase();
158 // A bare data-filter marks a field with its own search (the file finder
159 // of the Files view): there are no rows to hide.
160 const sel = input.dataset.filter || input.dataset.pick;
161 if (!sel) return [];
162 const rows = $$(sel);
163 for (const r of rows) {
164 const was = r.hidden;
165 r.hidden = !r.textContent.toLowerCase().includes(t);
166 // A row shown again lays out its chips again (it had no width hidden).
167 if (was && !r.hidden) for (const ul of $$('[data-fit]', r)) window.ermiteFit?.fit(ul);
168 }
169 if (input.dataset.groups) {
170 for (const g of $$(input.dataset.groups)) g.hidden = !rows.some((r) => !r.hidden && g.contains(r));
171 }
172 return rows;
173 },
174 // The "go to" palette (ermiteCmd below).
175 cmdFilter(input) {
176 window.ermiteCmd.filter(input);
177 },
178 cmdKey(e) {
179 window.ermiteCmd.key(e);
180 },
181
182 // Diff.
183 layout(mode) {
184 const el = $('[data-diff]');
185 if (!el) return;
186 el.dataset.diff = mode;
187 try { sessionStorage.setItem('diff', mode); } catch { /* storage refused: the layout holds for this page */ }
188 for (const d of $$('[data-file]')) if ($('.dt', d)) d.open = true;
189 },
190 collapse() {
191 const files = $$('[data-file]');
192 const open = !files.some((d) => d.open);
193 for (const d of files) d.open = open;
194 },
195 // e / E: the whole file in view, or every file of the diff, with every
196 // line its hunks hide.
197 expandFile() {
198 const f = window.ermiteGaps.current();
199 if (!f) return flash('no file in view');
200 f.open = true;
201 window.ermiteGaps.file(f).then((r) => {
202 if (!r.done) return; // load said what failed
203 flash(r.lines ? 'whole file' : 'nothing hidden in this file');
204 });
205 },
206 async expandAll() {
207 const files = $$('[data-file]').filter((f) => f.querySelector('tr.gap'));
208 if (!files.length) return flash('nothing hidden in the loaded files');
209 flash('loading every line…', 10000);
210 for (const f of files) {
211 if (!(await window.ermiteGaps.file(f)).done) return; // load said what failed
212 }
213 flash('every line of the loaded files');
214 },
215 nextNote() {
216 const notes = $$('#diffs .cmt');
217 if (!notes.length) return;
218 const i = notes.findIndex((n) => n.getBoundingClientRect().top > innerHeight / 3);
219 const n = notes[i < 0 ? 0 : i];
220 const d = n.closest('details');
221 if (d) d.open = true;
222 n.scrollIntoView({ block: 'center' });
223 },
224
225 // y: pin the URL to the commit and copy it.
226 async permalink() {
227 const b = body().dataset;
228 if (!b.sha) return flash('no ref to pin on this page');
229 const enc = (b.ref || '').split('/').map(encodeURIComponent).join('/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
230 // The ref follows the repository and the route: /<repo>/<tree|blob|commits>/<ref>.
231 const path = enc ? location.pathname.replace(new RegExp('^(/[^/]+/[^/]+/)' + enc + '(?=/|$)'), '$1' + b.sha) : location.pathname;
232 if (path === location.pathname) return flash('this page has no ref to pin');
233 history.replaceState(null, '', path + location.hash);
234 try {
235 await navigator.clipboard.writeText(location.href);
236 flash('permalink ' + b.sha.slice(0, 7) + ' copied');
237 } catch {
238 flash('permalink in the address bar (copy refused)');
239 }
240 },
241
242 // The [copy] button of a clone line: the label says "Copied" for 1.5 s,
243 // and so does the accessible name; the hint badge (a status region)
244 // announces it.
245 async copy(btn) {
246 const line = btn.closest('.clone-line')?.querySelector('code')?.textContent ?? '';
247 btn.dataset.idleName ||= btn.getAttribute('aria-label') || '';
248 let ok = true;
249 try { await navigator.clipboard.writeText(line); } catch { ok = false; }
250 btn.textContent = ok ? 'Copied' : 'Copy failed';
251 btn.setAttribute('aria-label', (ok ? 'copied: ' : 'copy failed: ') + line);
252 flash(ok ? 'copied' : 'copy failed', 1500);
253 clearTimeout(btn._restore);
254 btn._restore = setTimeout(() => {
255 btn.textContent = btn.dataset.label;
256 btn.setAttribute('aria-label', btn.dataset.idleName);
257 }, 1500);
258 },
259 };
260 window.ermite = ermite;
261
262 // The "go to" palette is an editable combobox with a listbox popup: the
263 // focus stays in #cmd-q, the options are the <li> of #cmd-list, and the one
264 // with data-cursor is the active one (aria-selected on it, aria-activedescendant
265 // on the field). sync keeps the two in step; it runs on every change of the
266 // cursor or of the list, including the file hits files.js adds later.
267 // Self-contained: jstest/palette.test.mjs evaluates this block alone.
268 window.ermiteCmd = (() => {
269 const list = () => document.getElementById('cmd-list');
270 const field = () => document.getElementById('cmd-q');
271 const options = () => [...list().querySelectorAll(':scope > li')];
272 let seq = 0;
273 const moveCursor = (li) => {
274 for (const o of options()) if (o !== li) o.removeAttribute('data-cursor');
275 li.setAttribute('data-cursor', '');
276 };
277 function sync() {
278 const input = field();
279 if (!input || !list()) return;
280 const all = options();
281 const shown = all.filter((li) => !li.hidden);
282 const cur = shown.find((li) => li.hasAttribute('data-cursor'));
283 for (const li of all) {
284 li.id ||= 'cmd-h' + seq++;
285 li.setAttribute('role', 'option');
286 li.setAttribute('aria-selected', li === cur ? 'true' : 'false');
287 }
288 input.setAttribute('aria-expanded', shown.length ? 'true' : 'false');
289 if (cur) input.setAttribute('aria-activedescendant', cur.id);
290 else input.removeAttribute('aria-activedescendant');
291 }
292 return {
293 sync,
294 // filter hides the entries that do not contain the text of the field.
295 // The file hits the finder adds (li.finder-hit, files.js) have no data-k:
296 // the finder owns them.
297 filter(input) {
298 const t = input.value.toLowerCase().trim();
299 const items = options().filter((li) => li.hasAttribute('data-k'));
300 for (const li of items) li.hidden = !li.getAttribute('data-k').includes(t);
301 const first = items.find((li) => !li.hidden);
302 if (first) moveCursor(first);
303 sync();
304 },
305 key(e) {
306 const vis = options().filter((li) => !li.hidden);
307 const i = vis.findIndex((li) => li.hasAttribute('data-cursor'));
308 const step = e.key === 'ArrowDown' ? 1 : e.key === 'ArrowUp' ? -1 : 0;
309 if (step) {
310 e.preventDefault();
311 const n = vis[Math.max(0, Math.min(vis.length - 1, i + step))];
312 if (n) {
313 moveCursor(n);
314 n.scrollIntoView({ block: 'nearest' });
315 }
316 sync();
317 } else if (e.key === 'Enter') {
318 e.preventDefault();
319 vis[Math.max(i, 0)]?.querySelector('a')?.click();
320 }
321 },
322 };
323 })();
324
325 // The side panel (aside.rail) by keyboard: l enters it on its main action
326 // (the primary button) or its first control, j / k step between its shown
327 // controls (not hidden, not in a closed <details>), h leaves it for <main>.
328 // Each returns the hint to flash, if any. Self-contained: jstest/rail.test.mjs
329 // evaluates this block alone.
330 window.ermiteRail = (() => {
331 const CONTROLS = ['a', 'button', 'select', 'summary', 'input', 'textarea'];
332 const reachable = (e) => {
333 if (e.disabled || e.closest('[hidden]')) return false;
334 if (e.tagName === 'A' && !e.hasAttribute('href')) return false;
335 if (e.tagName === 'INPUT' && e.getAttribute('type') === 'hidden') return false;
336 return !e.getClientRects || e.getClientRects().length > 0;
337 };
338 const rail = () => document.querySelector('.rail');
339 // items walks the panel in document order.
340 const items = (r) => {
341 const out = [];
342 const walk = (e) => {
343 for (const c of e.children) {
344 if (CONTROLS.includes(c.tagName.toLowerCase())) { if (reachable(c)) out.push(c); }
345 else walk(c);
346 }
347 };
348 walk(r);
349 return out;
350 };
351 const inside = (r) => r && r.contains(document.activeElement);
352 const go = (e) => { e.focus(); e.scrollIntoView({ block: 'nearest' }); };
353 return {
354 enter() {
355 const r = rail();
356 if (!r) return 'no side panel on this page';
357 const list = items(r);
358 const target = list.find((e) => e.matches('.btn.primary')) || list[0];
359 if (!target) return 'nothing to act on in the side panel';
360 go(target);
361 return 'side panel · j k move · enter act · h back';
362 },
363 leave() {
364 if (inside(rail())) document.getElementById('main')?.focus({ preventScroll: true });
365 },
366 // step moves d controls within the panel; false when the focus is not in it.
367 step(d) {
368 const r = rail();
369 if (!inside(r)) return false;
370 const list = items(r);
371 const i = list.indexOf(document.activeElement);
372 const next = list[Math.max(0, Math.min(list.length - 1, i + d))];
373 if (next) go(next);
374 return true;
375 },
376 };
377 })();
378
379 // The installed app: the service worker (/-/sw.js) is registered once the
380 // page has loaded. With it and the manifest the browser offers the install
381 // by itself (the address bar of a desktop, the menu or a banner on a phone);
382 // the page leaves that offer alone. Self-contained: jstest/install.test.mjs
383 // evaluates this block alone.
384 window.ermiteInstall = (() => {
385 const api = {
386 // register installs the service worker; a browser without one, or a
387 // refusal, leaves the site working as before.
388 register() {
389 if (!navigator.serviceWorker) return Promise.resolve(null);
390 return navigator.serviceWorker.register('/-/sw.js', { scope: '/' }).catch(() => null);
391 },
392 };
393 if (document.readyState === 'complete') api.register();
394 else addEventListener('load', () => api.register(), { once: true });
395 return api;
396 })();
397
398 // The hidden lines of a diff: a row .gap holds a button that loads them
399 // (/context); the rows that come back replace the gap in the table of each
400 // layout (the unified and the split tables hold one row each for it). A
401 // file whose lines are all loaded has no gap left.
402 window.ermiteGaps = (() => {
403 const pending = new Map();
404 // selectLoaded marks the loaded rows that fall in the range of lines the
405 // URL selects (?on=new:21-149:a.go, a shift + click), as the server marks
406 // the rows it sent: the range stays one block once its hidden lines show.
407 // The loaded rows are context lines, the same on both sides.
408 function selectLoaded(file, rows) {
409 const m = /^(new|old):(?:(\d+)-)?(\d+):(.+)$/.exec(new URLSearchParams(location.search).get('on') || '');
410 // data-file is the path comments name (the new path of a rename), as ?on=
411 if (!m || file.dataset.file !== m[4]) return;
412 const end = Number(m[3]);
413 const start = m[2] ? Number(m[2]) : end;
414 for (const r of rows) {
415 const cells = [...r.querySelectorAll('td')];
416 // unified: old, new, mark, text; split: old side, then new side
417 const num = Number((cells.length === 4 ? cells[m[1] === 'old' ? 0 : 1] : cells[m[1] === 'old' ? 0 : 3])?.textContent.trim());
418 if (!(num >= start && num <= end)) continue;
419 if (cells.length === 4) r.classList.add('sel');
420 else for (const c of cells) c.classList.add('sel');
421 }
422 }
423 // load fills the gap the button is in, in both tables of its file.
424 function load(btn) {
425 const src = btn.dataset.src;
426 const row = btn.closest('tr.gap');
427 const file = row?.closest('[data-file]');
428 if (!src || !file) return Promise.resolve(0);
429 if (pending.has(src)) return pending.get(src);
430 const key = row.dataset.gap;
431 const table = btn.closest('table');
432 const focused = document.activeElement === btn;
433 btn.disabled = true;
434 const p = fetch(src, { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
435 .then(async (res) => {
436 if (!res.ok) throw new Error('loading the hidden lines: ' + res.status);
437 const t = document.createElement('template');
438 t.innerHTML = await res.text();
439 let n = 0;
440 for (const table of file.querySelectorAll('table.dt')) {
441 const kind = table.classList.contains('spl') ? 'spl' : 'uni';
442 const from = t.content.querySelector('tbody[data-for="' + kind + '"]');
443 const at = [...table.querySelectorAll('tr.gap')].find((r) => r.dataset.gap === key);
444 if (!from || !at) continue;
445 const rows = [...from.children].map((r) => r.cloneNode(true));
446 n = Math.max(n, rows.filter((r) => !r.classList.contains('gap')).length);
447 selectLoaded(file, rows.filter((r) => !r.classList.contains('gap')));
448 at.replaceWith(...rows);
449 }
450 // The focus was on the button, which is gone: on the gap that is
451 // left in the same table, else on the content.
452 if (focused && (document.activeElement === btn || document.activeElement === document.body)) {
453 const next = [...(table?.querySelectorAll('tr.gap') || [])].find((r) => r.dataset.gap === key)?.querySelector('button');
454 if (next) next.focus({ preventScroll: true });
455 else document.getElementById('main')?.focus({ preventScroll: true });
456 }
457 return n;
458 })
459 .catch((err) => {
460 btn.disabled = false;
461 window.ermite?.flash?.(err.message, 4000);
462 return -1;
463 })
464 .finally(() => pending.delete(src));
465 pending.set(src, p);
466 return p;
467 }
468 // file loads every gap of a file, until none is left (a long gap comes
469 // back with a gap for the rest). A gap already loading is waited for.
470 // done is false when a load failed (it said why) or the file never ran
471 // out of gaps.
472 async function file(f) {
473 let lines = 0;
474 for (let guard = 0; guard < 1000; guard++) {
475 const btn = f.querySelector('tr.gap button[data-src]');
476 if (!btn) return { done: true, lines };
477 const n = await load(btn);
478 if (n < 0) return { done: false, lines };
479 if (btn.isConnected) {
480 // an answer that did not take the gap's place: stop, not loop
481 window.ermite?.flash?.('some hidden lines could not be shown', 4000);
482 return { done: false, lines };
483 }
484 lines += n;
485 }
486 window.ermite?.flash?.('the file is too long to show every line at once', 4000);
487 return { done: false, lines };
488 }
489 // current is the file in view: the one the table of contents marks, else
490 // the last whose top is above the top third of the window.
491 function current() {
492 const a = document.querySelector('.files a[aria-current="true"]');
493 const marked = a && document.getElementById(a.hash.slice(1));
494 if (marked?.matches('[data-file]')) return marked;
495 const files = [...document.querySelectorAll('[data-file]')];
496 return files.findLast((f) => f.getBoundingClientRect().top < innerHeight / 3) ?? files[0] ?? null;
497 }
498 addEventListener('click', (e) => {
499 const btn = e.target.closest?.('tr.gap button[data-src]');
500 if (btn) load(btn);
501 });
502 return { load, file, current };
503 })();
504
505 // The preference "single-character shortcuts" (WCAG 2.1.4): off, the keys
506 // that are one printable character (j, k, s, ?, :, G, 1-9 in the merge menu,
507 // …) do nothing. Shortcuts with ctrl or cmd, escape, enter and the arrows
508 // keep working. The choice is kept by ermiteStore ("keys-off": '1' when off)
509 // and is made in the help dialog (a checkbox) or the palette (an action).
510 // Self-contained with store.js: jstest/a11y.test.mjs evaluates this block.
511 window.ermiteKeys = (() => {
512 const pref = window.ermiteStore.pref('keys-off', { values: ['1', ''], fallback: '' });
513 const isOff = () => pref.get() === '1';
514 // apply shows the state: the checkbox and the note of the help dialog,
515 // and the label of the palette action.
516 function apply() {
517 const off = isOff();
518 const box = document.getElementById('keys-off');
519 if (box) box.checked = off;
520 const note = document.getElementById('keys-note');
521 if (note) {
522 note.textContent = off
523 ? 'Single-key shortcuts are off: only ctrl k and esc, enter and the arrows work. Turn them on again here.'
524 : 'Single-key shortcuts are on. ctrl k and esc work whatever this says.';
525 }
526 const act = document.querySelector('#cmd-list [data-fire="keys"] .lbl');
527 if (act) act.textContent = off ? 'turn single-key shortcuts on' : 'turn single-key shortcuts off';
528 }
529 function set(v) {
530 pref.set(v ? '1' : '');
531 apply();
532 }
533 pref.watch(apply);
534 apply();
535 return {
536 off: isOff,
537 set,
538 apply,
539 // blocks says whether the preference turns this key off.
540 blocks: (e) => isOff() && e.key.length === 1,
541 };
542 })();
543
544 // The layout of the home page: "cards" (the default), "split" (two
545 // repositories per row) or "compact" (one line each). The choice is kept by
546 // ermiteStore ("home-layout"), made with the buttons [data-set-layout] of
547 // the layout switch, and shown as .home[data-layout], which the styles
548 // follow, and as aria-pressed on the buttons. Another tab's change applies
549 // here at once. The topic chips are fitted again: their room changes with the
550 // layout. Self-contained with store.js: jstest/layout.test.mjs evaluates
551 // this block.
552 window.ermiteLayout = (() => {
553 const values = ['cards', 'split', 'compact'];
554 const pref = window.ermiteStore.pref('home-layout', { values, fallback: 'cards' });
555 function apply() {
556 const layout = pref.get();
557 const home = document.querySelector('.home');
558 if (home) home.setAttribute('data-layout', layout);
559 for (const b of document.querySelectorAll('[data-set-layout]')) {
560 b.setAttribute('aria-pressed', String(b.getAttribute('data-set-layout') === layout));
561 }
562 window.ermiteFit?.all();
563 }
564 function set(v) {
565 pref.set(v);
566 apply();
567 }
568 addEventListener('click', (e) => {
569 const btn = e.target.closest?.('[data-set-layout]');
570 if (btn) set(btn.getAttribute('data-set-layout'));
571 });
572 pref.watch(apply);
573 apply();
574 return { get: pref.get, set, apply, values };
575 })();
576
577 // The wide mode (w, on every page): the work area takes the whole width of
578 // the screen, the rail at the right edge and the content in the rest.
579 // The choice is kept by ermiteStore ("wide": '1' when wide) and shown
580 // as html.wide, which the styles follow. Another tab's change applies here
581 // at once.
582 window.ermiteWide = (() => {
583 const pref = window.ermiteStore.pref('wide', { values: ['1', ''], fallback: '' });
584 function apply() {
585 const wide = pref.get() === '1';
586 document.documentElement.classList.toggle?.('wide', wide);
587 }
588 function toggle() {
589 pref.set(pref.get() === '1' ? '' : '1');
590 apply();
591 }
592 pref.watch(apply);
593 apply();
594 return { toggle, apply };
595 })();
596
597 // The menus of the bars (<details class="menu">: the diff view, the merge
598 // menu): closing one hands the focus back to its button when it was inside,
599 // so that a keyboard user keeps their place.
600 function closeMenu(d) {
601 const had = d.contains(document.activeElement);
602 d.open = false;
603 if (had) $('summary', d)?.focus();
604 }
605 // closeMenus closes every open menu (escape); true when one was open.
606 function closeMenus() {
607 const open = $$('details.menu[open]');
608 for (const d of open) closeMenu(d);
609 return open.length > 0;
610 }
611
612 // 1. Keys.
613 const single = { j: 'j', k: 'k', G: 'bottom', '/': 'filter', '?': 'help', b: 'refs', f: 'cmd', ':': 'cmd', y: 'permalink',
614 s: 's', t: 't', c: 'c', r: 'r', m: 'm', i: 'i', n: 'next', h: 'left', l: 'right', d: 'split', u: 'unified', x: 'collapse', w: 'wide', e: 'expand', E: 'expandAll', Enter: 'open', Escape: 'esc',
615 // the merge request page (mr.js): the merge menu, mark read
616 M: 'merge', R: 'read' };
617 // "g t" is the key "t": the tabs have one event each.
618 const goto = { h: 'gh', t: 't', c: 'c', r: 'r', m: 'm', i: 'i', g: 'top', f: 'gf' };
619 let pending = 0;
620 let pendingTimer = 0;
621 addEventListener('keydown', (e) => {
622 const typing = e.target.closest('input:not([type=checkbox], [type=radio], [type=submit], [type=button]), textarea, select, [contenteditable]');
623 // ctrl k / cmd k opens the palette; in a field only cmd k, so that the
624 // field keeps ctrl k (kill to end of line on macOS).
625 if ((e.metaKey || (e.ctrlKey && !typing)) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 'k') { e.preventDefault(); pending = 0; return ermite.fire('cmd'); }
626 if (e.ctrlKey || e.metaKey || e.altKey) return;
627 const mr = window.ermiteMR;
628 if (e.key === 'Escape') {
629 pending = 0;
630 if (closeMenus() || mr?.leaveFiles()) return;
631 if (typing) e.target.blur();
632 return ermite.fire('esc');
633 }
634 // Single-character shortcuts turned off: only the keys above work.
635 if (window.ermiteKeys.blocks(e)) { pending = 0; return; }
636 // An open merge menu takes its keys (1-9, D) before the field check: its
637 // radios and its checkbox hold the focus.
638 if (mr?.menuKey(e)) return;
639 if (typing) return;
640 // An open dialog takes only the keys that move between dialogs: the page
641 // behind it does not react (scripted clicks would go through inert).
642 if ($('dialog[open]') && !['?', 'b', ':', 'f', 'Enter'].includes(e.key)) { pending = 0; return; }
643 if (e.key === 'Enter' && e.target.closest('a, button, summary')) return;
644 if (pending) {
645 const name = goto[e.key];
646 pending = 0;
647 if (name) { e.preventDefault(); ermite.fire(name); }
648 return;
649 }
650 if (e.key === 'g') { pending = 1; clearTimeout(pendingTimer); pendingTimer = setTimeout(() => (pending = 0), 1200); return; }
651 // The arrows and Home / End are the tree's only while the focus is on one of
652 // its rows (they scroll, or move the focus, anywhere else); j k l h are
653 // page-level keys, as on the other lists.
654 if (!e.shiftKey && e.target.closest?.('#tree-rows') && window.ermiteTree?.arrow(e.key)) { e.preventDefault(); return; }
655 const name = single[e.key];
656 if (!name) return;
657 if (e.key !== 'Enter' || !$('dialog[open]')) e.preventDefault();
658 ermite.fire(name);
659 });
660
661 // 2. A [data-fire] element does what the key of that name does (the header
662 // buttons, the diff layout links). The link to the refs page works without
663 // scripts and is upgraded here to open the dialog; a click with a modifier
664 // keeps its meaning (new tab).
665 addEventListener('click', (e) => {
666 const el = e.target.closest?.('[data-fire]');
667 if (!el || e.button || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
668 e.preventDefault();
669 ermite.fire(el.dataset.fire);
670 // A choice in a menu closes it; the focus goes back to its button.
671 const menu = el.closest('details.menu');
672 if (menu) closeMenu(menu);
673 });
674 // A click outside an open menu closes it.
675 addEventListener('click', (e) => {
676 for (const d of $$('details.menu[open]')) if (!d.contains(e.target)) d.open = false;
677 });
678 for (const a of $$('a[data-fire="refs"]')) {
679 a.setAttribute('aria-haspopup', 'dialog');
680 a.setAttribute('aria-controls', 'panel-refs');
681 }
682
683 // A login link signs in without a click: its page submits its form once a
684 // browser shows it, not while it is prerendered.
685 const auto = $('form[data-autosubmit]');
686 if (auto) {
687 const go = () => auto.requestSubmit();
688 if (document.prerendering) document.addEventListener('prerenderingchange', go, { once: true });
689 else go();
690 }
691
692 // In the app shell the page does not scroll, <main> does: give it focus so arrows,
693 // PageUp/PageDown and space scroll the content without a click first.
694 if (!location.hash) document.getElementById('main')?.focus({ preventScroll: true });
695
696 // 4. The table of contents of a diff marks the file in view: the last file
697 // in the top third of the window, else the last file whose top is above that
698 // line (the first file when none is). One observer tracks the files in the
699 // band; it reports only when a file enters or leaves it, so a scroll costs
700 // nothing in between, and a jump that skips the band is caught by the scan.
701 let files = $$('.dfile');
702 const links = new Map($$('.files a[href^="#"]').map((a) => [a.hash.slice(1), a]));
703 if (files.length && links.size && 'IntersectionObserver' in window) {
704 const inBand = new Set();
705 let current = null;
706 const mark = () => {
707 const f = files.findLast((x) => inBand.has(x))
708 ?? files.findLast((x) => x.getBoundingClientRect().top < innerHeight / 3)
709 ?? files[0];
710 if (f === current) return;
711 links.get(current?.id)?.removeAttribute('aria-current');
712 const a = links.get(f.id);
713 a?.setAttribute('aria-current', 'true');
714 // The list scrolls on its own: the current file stays in it. Only the
715 // list moves, never the page (scrollIntoView would scroll the page to
716 // the list when the rail is under the diff).
717 const box = a?.closest('.files');
718 if (a && box && box.scrollHeight > box.clientHeight && !box.contains(document.activeElement)) {
719 const top = a.offsetTop;
720 if (top < box.scrollTop) box.scrollTop = top;
721 else if (top + a.offsetHeight > box.scrollTop + box.clientHeight) box.scrollTop = top + a.offsetHeight - box.clientHeight;
722 }
723 current = f;
724 };
725 const io = new IntersectionObserver((entries) => {
726 for (const e of entries) {
727 if (e.isIntersecting) inBand.add(e.target);
728 else inBand.delete(e.target);
729 }
730 mark();
731 }, { rootMargin: '0px 0px -67% 0px' });
732 for (const f of files) io.observe(f);
733 // A window of files of a merge request came in (mr.js): its files replace
734 // placeholders, which the observer and the list knew by element.
735 ermite.watchFile = (f, old) => {
736 if (old) { io.unobserve(old); inBand.delete(old); }
737 files = $$('.dfile');
738 for (const x of [...inBand]) if (!x.isConnected) inBand.delete(x);
739 if (current && !current.isConnected) current = document.getElementById(current.id);
740 io.observe(f);
741 };
742 }
743
744 // 8. A list of chips on one line ([data-fit], the topics of a home row):
745 // the chips that wrap out of sight are hidden and a "…" button after the
746 // last one shown names them; pressing it opens the list (data-open) on as
747 // many lines as it needs. Self-contained: jstest/fit.test.mjs evaluates
748 // this block alone.
749 window.ermiteFit = (() => {
750 const fit = (ul) => {
751 if (ul.hasAttribute('data-open')) return;
752 // The … button is kept across fits, so that a refit (a resize) does not
753 // take the focus from it.
754 let more = ul.querySelector(':scope > li.more');
755 let btn = more?.firstElementChild;
756 const focused = !!btn && document.activeElement === btn;
757 more?.remove();
758 const chips = [...ul.children];
759 for (const li of chips) li.hidden = false;
760 const top = chips[0]?.offsetTop;
761 if (top === undefined || chips.at(-1).offsetTop === top) {
762 // Everything fits now: a focused … button hands the focus to the
763 // last chip.
764 if (focused && chips.length) {
765 chips.at(-1).setAttribute('tabindex', '-1');
766 chips.at(-1).focus({ preventScroll: true });
767 }
768 return;
769 }
770 if (!more) {
771 more = document.createElement('li');
772 more.className = 'more';
773 btn = document.createElement('button');
774 btn.type = 'button';
775 btn.textContent = '…';
776 more.append(btn);
777 }
778 ul.append(more);
779 if (focused) btn.focus({ preventScroll: true });
780 // Keep the chips of the first line, then drop from the end until the
781 // … chip fits there too.
782 let shown = chips.findIndex((li) => li.offsetTop !== top);
783 for (const li of chips.slice(shown)) li.hidden = true;
784 while (shown > 0 && more.offsetTop !== top) chips[--shown].hidden = true;
785 const rest = chips.slice(shown).map((li) => li.textContent);
786 btn.title = rest.join(', ');
787 btn.setAttribute('aria-label', 'show ' + rest.length + ' more: ' + rest.join(', '));
788 };
789 // open shows every chip of the list of the … button pressed.
790 const open = (btn) => {
791 const ul = btn.closest('[data-fit]');
792 if (!ul) return;
793 const item = btn.closest('li');
794 // The focus goes to the first chip that was hidden, now shown.
795 const next = [...ul.children].find((li) => li.hidden);
796 ul.setAttribute('data-open', '');
797 item.remove();
798 for (const li of ul.children) li.hidden = false;
799 if (next) {
800 next.setAttribute('tabindex', '-1');
801 next.focus({ preventScroll: true });
802 }
803 };
804 const all = (root = document) => {
805 for (const ul of root.querySelectorAll('[data-fit]')) fit(ul);
806 };
807 return { fit, all, open };
808 })();
809 addEventListener('click', (e) => {
810 const btn = e.target.closest?.('[data-fit] > li.more > button');
811 if (btn) window.ermiteFit.open(btn);
812 });
813 {
814 window.ermiteFit.all();
815 // Widths change with the window and when the fonts arrive; one frame per
816 // burst. Always listening: a live update can bring the first list.
817 let pending = 0;
818 const again = () => {
819 if (pending) return;
820 pending = requestAnimationFrame(() => { pending = 0; window.ermiteFit.all(); });
821 };
822 addEventListener('resize', again);
823 document.fonts?.ready.then(again);
824 }
825
826 // 5. A failure of a handler or of a request (htmx logs it to the console
827 // already) is shown, so that a key that does nothing is not a mystery.
828 addEventListener('htmx:error', (e) => {
829 if (e.target.closest?.('.hint-live')) return; // the stream says so itself ("live updates paused")
830 const err = e.detail?.error;
831 flash('something went wrong' + (err?.message ? ': ' + err.message : ''), 4000);
832 });
833})();
834
835// ermiteLive applies the fragments of the event stream (/-/events, see
836// internal/adapters/web/events.go). A fragment is a top-level element with an
837// id: it replaces the element of the page that has the same id. A fragment
838// marked data-gone removes it; a row of a repository the home page does not
839// list yet is added at the top of the list. Activity updates also move existing
840// home rows to the top when sorted by newest activity; CI updates stay put. A slot (data-slot: the place of a
841// banner, a persistent status region) keeps its element and only gets the
842// children of the fragment, so that screen readers announce the change. A gap,
843// which says the page may have missed events or that what it shows changed,
844// reloads the page. A stream the server refuses on reconnection (the
845// repository is gone, the session ended) makes the page reload.
846window.ermiteLive = (() => {
847 let reloading = false;
848 let stopped = false;
849 // A stream that drops and comes back within LOST_AFTER (a proxy or the
850 // server closing it, a network hiccup) is not worth a message.
851 const LOST_AFTER = 5000;
852 let lostTimer = 0;
853 // The focus survives a swap. focusables are the controls of a fragment in
854 // document order; where(root) says which one has the focus (its id, else its
855 // tag and href or name, and its index among the controls) and refocus finds
856 // it again in the element that replaced root.
857 const FOCUSABLE = 'a[href], button:not([disabled]), input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea:not([disabled]), summary, [tabindex]';
858 // shown: not inside a hidden element (a filtered row, a folded block); the
859 // browser refuses the focus there.
860 const shown = (e) => !e.closest('[hidden]') && (!e.checkVisibility || e.checkVisibility());
861 const focusables = (root) => [...root.querySelectorAll(FOCUSABLE)].filter(shown);
862 // take focuses e and says whether the focus is there now.
863 const take = (e) => { e.focus({ preventScroll: true }); return document.activeElement === e; };
864 const where = (root) => {
865 const a = document.activeElement;
866 if (!a || a === document.body || !root.contains(a)) return null;
867 if (a === root) return { self: true };
868 const all = focusables(root);
869 return { id: a.id, tag: a.tagName, href: a.getAttribute('href'), name: a.getAttribute('name'), index: all.indexOf(a) };
870 };
871 const refocus = (root, w) => {
872 if (w.self) return root.focus({ preventScroll: true });
873 const all = focusables(root);
874 const same = (e) => e.tagName === w.tag;
875 const target =
876 (w.id && all.find((e) => e.id === w.id)) ||
877 (w.href != null && all.find((e) => same(e) && e.getAttribute('href') === w.href)) ||
878 (w.name != null && all.find((e) => same(e) && e.getAttribute('name') === w.name)) ||
879 (all[w.index] && same(all[w.index]) && all[w.index]) ||
880 all[0];
881 if (target) target.focus({ preventScroll: true });
882 else if (root.hasAttribute('tabindex')) root.focus({ preventScroll: true });
883 };
884 // lostFocus: the element that had the focus inside is gone. The focus goes to
885 // the first control of the next shown row, else of the nearest shown row
886 // before, else to the content.
887 const lostFocus = (after, before) => {
888 const tryRow = (e) => {
889 if (!shown(e)) return false;
890 const c = focusables(e)[0] || (e.hasAttribute('tabindex') ? e : null);
891 return !!c && take(c);
892 };
893 for (let e = after; e; e = e.nextElementSibling) if (tryRow(e)) return;
894 for (let e = before; e; e = e.previousElementSibling) if (tryRow(e)) return;
895 document.getElementById('main')?.focus({ preventScroll: true });
896 };
897 const setState = (s) => { const el = document.querySelector('.hint-live'); if (el) el.dataset.state = s; };
898 // fitIn lays out the one-line chip lists of a fragment now in the page.
899 const fitIn = (el) => { for (const ul of el.querySelectorAll('[data-fit]')) window.ermiteFit?.fit(ul); };
900 return {
901 // lost is htmx:sse:close and htmx:sse:error: "live updates paused" shows
902 // only if the stream is still down LOST_AFTER later.
903 lost() {
904 if (lostTimer) return;
905 lostTimer = setTimeout(() => { lostTimer = 0; setState('offline'); }, LOST_AFTER);
906 },
907 // back is htmx:sse:after:connection.
908 back() {
909 clearTimeout(lostTimer);
910 lostTimer = 0;
911 setState('live');
912 },
913 swap(html) {
914 const t = document.createElement('template');
915 t.innerHTML = html;
916 const cursor = document.querySelector('[data-rows] > [data-cursor]');
917 const cursorKey = cursor?.id || cursor?.querySelector('a')?.getAttribute('href');
918 for (const el of [...t.content.children]) {
919 const old = el.id && document.getElementById(el.id);
920 const had = old ? where(old) : null; // the focus is inside what is replaced
921 if (el.hasAttribute('data-gone')) {
922 const after = old?.nextElementSibling, before = old?.previousElementSibling;
923 old?.remove();
924 if (had) lostFocus(after, before);
925 continue;
926 }
927 if (!old) {
928 const rows = document.getElementById('repo-rows');
929 if (rows && el.id.startsWith('repo-')) { rows.prepend(el); window.htmx?.process(el); fitIn(el); }
930 continue;
931 }
932 if (old.hasAttribute('data-slot')) {
933 old.replaceChildren(...el.childNodes);
934 if (had) refocus(old, had);
935 continue;
936 }
937 if (old.hasAttribute('data-cursor')) el.setAttribute('data-cursor', '');
938 old.replaceWith(el);
939 const rows = document.getElementById('repo-rows');
940 if (rows && el.parentElement === rows && rows.dataset.sort === 'activity' &&
941 rows.dataset.desc === 'true' && el.hasAttribute('data-activity')) rows.prepend(el);
942 window.htmx?.process(el);
943 fitIn(el);
944 if (had) refocus(el, had);
945 }
946 // The rows may have changed under an active filter: apply it again and
947 // keep the cursor on its row while that row is still shown.
948 for (const input of document.querySelectorAll('input[data-filter]')) {
949 if (input.value) window.ermite?.hide(input);
950 }
951 if (!cursorKey) return;
952 const rows = [...document.querySelectorAll('[data-rows] > *')];
953 const back = rows.find((r) => !r.hidden && (r.id === cursorKey || r.querySelector('a')?.getAttribute('href') === cursorKey));
954 if (back) for (const r of rows) r.toggleAttribute('data-cursor', r === back);
955 },
956 reload() {
957 if (reloading) return;
958 reloading = true;
959 setTimeout(() => location.reload(), 300);
960 },
961 // error handles htmx:sse:error (detail.status is the status of a refused
962 // reconnection). hx-sse retries for ever; a 404 or a 401 will not change by
963 // itself, and the fetched page says what is the matter (or has no stream).
964 // A page that reloaded for this a moment ago and still gets refused would
965 // loop: it stops following the stream instead (see gate).
966 error(status) {
967 if (status !== 404 && status !== 401) return;
968 let last = 0;
969 try { last = +sessionStorage.getItem('ermite-live-reload') || 0; } catch { /* no storage: no guard */ }
970 if (Date.now() - last < 15000) { stopped = true; return; }
971 try { sessionStorage.setItem('ermite-live-reload', String(Date.now())); } catch { /* idem */ }
972 this.reload();
973 },
974 // gate is htmx:sse:before:connection: once stopped, no more attempts.
975 gate(event) {
976 if (stopped) event.preventDefault();
977 },
978 };
979})();