v0.29.0 55fcc8f

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

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 2

Tags 45

↑↓ moveenter openesc close