1// mr.js: the merge request page beyond what htmx and hx-live give.
2//
3// 1. Windows of files. The page holds the hunks of one window of files; the
4// other files are placeholders (.dlazy[data-src]). A placeholder that comes
5// near the screen fetches its window (/files?from=&base=&head=), whose
6// files replace the placeholders of the same ids. A window is fetched once;
7// a link to a file or to a comment of a placeholder fetches it first.
8// 2. The menus of the bar (merge, more) and their keys: M opens the merge menu
9// on its button, 1-9 pick a mode, D toggles the branch deletion, Enter
10// submits (the browser does it: the focus is on the button), Esc closes.
11// R marks the head read. Nothing merges on one key.
12// 3. g f puts the focus in the list of files (opening it when folded); j / k
13// move in it, Enter opens the file, Esc goes back to the diff. The button
14// of its header folds the list, and the choice is remembered.
15//
16// Nothing runs on a page without #diffs[data-mr]. window.ermiteMR.core is pure
17// (jstest/mr.test.mjs).
18window.ermiteMR = (() => {
19 // core: the decisions, without the DOM.
20 const core = {
21 // windowOf is the start of the window of file i (files are f1, f2, ...).
22 windowOf(id, size) {
23 const n = Number(String(id).replace(/^f/, '')) - 1;
24 return Number.isInteger(n) && n >= 0 ? n - (n % size) : -1;
25 },
26 // menuKey says what a key does while the merge menu is open: a mode
27 // (index), the branch deletion, or nothing.
28 menuKey(key, modes) {
29 if (key === 'D') return { toggle: true };
30 if (/^[1-9]$/.test(key) && Number(key) <= modes) return { mode: Number(key) - 1 };
31 return null;
32 },
33 // step moves an index within [0, n).
34 step(i, d, n) {
35 if (n === 0) return -1;
36 if (i < 0) return d > 0 ? 0 : n - 1;
37 return Math.max(0, Math.min(n - 1, i + d));
38 },
39 };
40
41 const $ = (sel, root = document) => root.querySelector(sel);
42 const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
43 const loading = new Map(); // src -> promise of the swap
44 let moved = false;
45 let lazyIO = null; // the observer of the placeholders (watch)
46 let revealGen = 0; // the last reveal wins the scroll
47
48 // load fetches the window of a placeholder and swaps its files in. The
49 // promise resolves once they are in the page (or the page said to reload).
50 function load(ph) {
51 const src = ph?.dataset.src;
52 if (!src || moved) return Promise.resolve();
53 if (loading.has(src)) return loading.get(src);
54 for (const p of $$('.dlazy[data-src]')) if (p.dataset.src === src) p.setAttribute('data-loading', '');
55 // The window renders like the page: the layout shown, and both layouts
56 // when the page switches them itself (data-diff) or one (data-view).
57 const d = $('#diffs')?.dataset || {};
58 const view = d.diff || d.view;
59 const layouts = d.diff ? 'both' : d.view ? 'one' : '';
60 const url = src + (view ? '&view=' + encodeURIComponent(view) : '') + (layouts ? '&layouts=' + layouts : '');
61 const p = fetch(url, { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
62 .then(async (res) => {
63 const html = await res.text();
64 if (res.status === 409) return stale(html);
65 if (!res.ok) throw new Error('loading files: ' + res.status);
66 // A window of the old diff after the page went stale stays out.
67 if (!moved) swap(html);
68 })
69 .catch((err) => {
70 loading.delete(src);
71 for (const p of $$('.dlazy[data-loading]')) if (p.dataset.src === src) p.removeAttribute('data-loading');
72 window.ermite?.flash?.(err.message, 4000);
73 });
74 loading.set(src, p);
75 return p;
76 }
77
78 // swap replaces each placeholder file with the file of the same id. A
79 // file the reader folded stays folded.
80 function swap(html) {
81 const t = document.createElement('template');
82 t.innerHTML = html;
83 for (const f of [...t.content.querySelectorAll('details[data-file]')]) {
84 const old = document.getElementById(f.id);
85 if (!old || !old.querySelector('.dlazy')) continue;
86 f.open = old.open;
87 for (const p of $$('.dlazy', old)) lazyIO?.unobserve(p);
88 old.replaceWith(f);
89 window.htmx?.process(f);
90 window.ermite?.watchFile?.(f, old);
91 }
92 }
93
94 // stale: the diff changed under the page. The placeholders say so; no file
95 // of another diff comes in.
96 function stale(html) {
97 moved = true;
98 for (const p of $$('.dlazy')) {
99 p.removeAttribute('data-loading');
100 p.innerHTML = html;
101 }
102 }
103
104 // reveal loads the file of an id (a file "f12" or a comment "c3") when it is
105 // a placeholder, then scrolls to it. It returns false when there is nothing
106 // to load.
107 function reveal(id, scroll = true) {
108 // Any navigation, loaded or not, makes the reveals still loading stale.
109 const gen = ++revealGen;
110 let ph = document.getElementById(id)?.querySelector(':scope > .dlazy');
111 if (!ph && /^c\d+/.test(id) && !document.getElementById(id)) {
112 const base = id.replace(/-s$/, '');
113 ph = $$('.dlazy[data-notes]').find((p) => p.dataset.notes.split(' ').includes(base));
114 }
115 if (!ph) return false;
116 load(ph).then(() => {
117 // A later reveal (another file asked meanwhile) owns the view.
118 if (gen !== revealGen) return;
119 const el = document.getElementById(id);
120 if (!el) return;
121 const d = el.closest('details');
122 if (d) d.open = true;
123 if (!scroll) return;
124 // The files above may have changed size while it loaded (placeholders,
125 // content-visibility): place it, then again once laid out.
126 el.scrollIntoView({ block: 'start' });
127 requestAnimationFrame(() => requestAnimationFrame(() => {
128 if (gen === revealGen) el.scrollIntoView({ block: 'start' });
129 }));
130 });
131 return true;
132 }
133
134 // Placeholders load as they come within two screens of the view; files
135 // that come in are marked in the list of files (ermite.js marks the one in
136 // view).
137 function watch() {
138 if (!('IntersectionObserver' in window)) {
139 for (const p of $$('.dlazy[data-src]')) load(p);
140 return;
141 }
142 lazyIO = new IntersectionObserver((entries) => {
143 for (const e of entries) {
144 if (!e.isIntersecting) continue;
145 lazyIO.unobserve(e.target);
146 load(e.target);
147 }
148 }, { rootMargin: '200% 0px 200% 0px' });
149 for (const p of $$('.dlazy[data-src]')) lazyIO.observe(p);
150 }
151
152 // The merge menu.
153 const menu = () => $('#merge-menu');
154 function openMerge() {
155 const m = menu();
156 if (!m) return false;
157 for (const d of $$('details.menu[open]')) if (d !== m) d.open = false;
158 m.open = true;
159 $('[data-default]', m)?.focus();
160 return true;
161 }
162 function closeMenus() {
163 const open = $$('details.menu[open]');
164 for (const d of open) d.open = false;
165 if (open.length) $('summary', open[0])?.focus();
166 return open.length > 0;
167 }
168 // menuKey handles a key while the merge menu is open; true when it used it.
169 function menuKey(e) {
170 const m = menu();
171 if (!m?.open || e.ctrlKey || e.metaKey || e.altKey) return false;
172 // An open dialog (help, commands) is above the menu: it keeps the keys.
173 if ($('dialog[open]')) return false;
174 // A field outside the menu (a comment being written) keeps its keys.
175 const field = e.target.closest?.('input, textarea, select, [contenteditable]');
176 if (field && !m.contains(field)) return false;
177 const radios = $$('input[name="mode"]', m);
178 const act = core.menuKey(e.key, radios.length);
179 if (!act) return false;
180 e.preventDefault();
181 if (act.toggle) {
182 const box = $('input[name="delete_branch"]', m);
183 if (box) box.checked = !box.checked;
184 } else {
185 radios[act.mode].checked = true;
186 }
187 $('[data-default]', m)?.focus();
188 return true;
189 }
190 function markRead() {
191 const b = $('button[data-read]');
192 if (!b) return false;
193 b.closest('form').requestSubmit(b);
194 return true;
195 }
196
197 // The list of files by keyboard: g f focuses the current file.
198 const links = () => $$('.r-files .files > li:not([hidden]) > a');
199 function focusFiles() {
200 foldFiles(false);
201 const all = links();
202 if (!all.length) return false;
203 const cur = all.find((a) => a.getAttribute('aria-current') === 'true') || all[0];
204 cur.focus();
205 cur.scrollIntoView({ block: 'nearest' });
206 return true;
207 }
208 // stepFiles moves the focus in the list; false when the focus is not in it.
209 function stepFiles(d) {
210 const all = links();
211 const i = all.indexOf(document.activeElement);
212 if (i < 0) return false;
213 const j = core.step(i, d, all.length);
214 all[j].focus();
215 all[j].scrollIntoView({ block: 'nearest' });
216 return true;
217 }
218 function leaveFiles() {
219 if (!links().includes(document.activeElement)) return false;
220 document.getElementById('main')?.focus({ preventScroll: true });
221 return true;
222 }
223
224 // foldFiles folds the list of files to its header, or opens it again:
225 // toggles without an argument. The choice is kept for the next pages.
226 function foldFiles(fold) {
227 const sec = $('.r-files');
228 const btn = sec && $('button.fold', sec);
229 if (!btn) return;
230 if (fold === undefined) fold = !sec.hasAttribute('data-folded');
231 sec.toggleAttribute('data-folded', fold);
232 btn.setAttribute('aria-expanded', String(!fold));
233 btn.title = fold ? 'open the list of files' : 'fold the list of files';
234 $('.sr', btn).textContent = btn.title;
235 // The list did not follow the review while folded: show its current file,
236 // moving the list only (never the page).
237 const box = !fold && $('.files', sec);
238 const a = box && $('a[aria-current="true"]', box);
239 if (a && (a.offsetTop < box.scrollTop || a.offsetTop + a.offsetHeight > box.scrollTop + box.clientHeight)) {
240 box.scrollTop = a.offsetTop - (box.clientHeight - a.offsetHeight) / 2;
241 }
242 try { localStorage.setItem('mr-files-folded', fold ? '1' : ''); } catch { /* storage refused: holds for this page */ }
243 }
244
245 // openFile opens the file of a link of the list (and loads it first).
246 function openFile(id) {
247 const f = document.getElementById(id);
248 if (f) f.open = true;
249 reveal(id);
250 }
251
252 function start() {
253 if (!$('#diffs[data-mr]')) return;
254 let folded = false;
255 try { folded = localStorage.getItem('mr-files-folded') === '1'; } catch { /* no storage: open */ }
256 if (folded) foldFiles(true);
257 watch();
258 // A link to a file or a comment that is not loaded yet.
259 const hash = () => {
260 const id = decodeURIComponent(location.hash.slice(1));
261 if (id) reveal(id);
262 };
263 addEventListener('hashchange', hash);
264 hash();
265 // A click outside an open menu closes it.
266 addEventListener('click', (e) => {
267 for (const d of $$('details.menu[open]')) if (!d.contains(e.target)) d.open = false;
268 });
269 }
270
271 return { core, start, load, reveal, openMerge, closeMenus, menuKey, markRead, focusFiles, stepFiles, leaveFiles, foldFiles, openFile };
272})();
273
274if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => window.ermiteMR.start());
275else window.ermiteMR.start();