v0.26.1 dfd6f0b

ermite.js RawHistoryFolder

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

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 4

Tags 45

↑↓ moveenter openesc close