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]), loaded by lazy.js (which
5// the commit and compare pages use too) when they come near the screen. A
6// link to a file or to a comment of a placeholder loads it first (reveal).
7// 2. The menus of the bar (merge, more) and their keys: M opens the merge menu
8// on its button, 1-9 pick a mode, D toggles the branch deletion, Enter
9// submits (the browser does it: the focus is on the button), Esc closes.
10// R marks the head read. Nothing merges on one key.
11// 3. g f puts the focus in the list of files (opening it when folded); j / k
12// move in it, Enter opens the file, Esc goes back to the diff. The button
13// of its header folds the list, and the choice is remembered.
14//
15// Nothing runs on a page without #diffs[data-mr]. window.ermiteMR.core is pure
16// (jstest/mr.test.mjs).
17window.ermiteMR = (() => {
18 // core: the decisions, without the DOM.
19 const core = {
20 rangeURL(previous, current, base) {
21 const a = new URL(previous, base), b = new URL(current, base);
22 const parse = (u) => /^(new|old):(\d+):(.+)$/.exec(u.searchParams.get('on') || '');
23 const x = parse(a), y = parse(b);
24 if (!x || !y || a.pathname !== b.pathname || x[1] !== y[1] || x[3] !== y[3] || x[2] === y[2]) return null;
25 const nums = [Number(x[2]), Number(y[2])].sort((a,b) => a-b);
26 b.searchParams.set('on', `${y[1]}:${nums[0]}-${nums[1]}:${y[3]}`);
27 return b.href;
28 },
29 // Range mode is explicit: ordinary taps still open single-line forms.
30 touchRange(previous, current, base) {
31 if (!previous) return { start: current, url: null };
32 const url = core.rangeURL(previous, current, base);
33 if (url) return { start: null, url };
34 if (previous === current) return { start: null, url: current };
35 return { start: current, url: null }; // another file/side starts afresh
36 },
37 mobileURL(href, view, narrow) {
38 if (!narrow || view !== 'split') return null;
39 const url = new URL(href);
40 url.searchParams.set('view', 'unified');
41 return url.href;
42 },
43 quote(button) {
44 const thread = button.closest('.cmt').closest('[data-thread]');
45 const details = thread?.querySelector(':scope > details[data-reply]');
46 const field = details?.querySelector('textarea');
47 if (!field) return false;
48 details.open = true;
49 field.value = button.dataset.quote;
50 field.focus();
51 return true;
52 },
53 // windowOf is the start of the window of file i (files are f1, f2, ...).
54 windowOf(id, size) {
55 const n = Number(String(id).replace(/^f/, '')) - 1;
56 return Number.isInteger(n) && n >= 0 ? n - (n % size) : -1;
57 },
58 // menuKey says what a key does while the merge menu is open: a mode
59 // (index), the branch deletion, or nothing.
60 menuKey(key, modes) {
61 if (key === 'D') return { toggle: true };
62 if (/^[1-9]$/.test(key) && Number(key) <= modes) return { mode: Number(key) - 1 };
63 return null;
64 },
65 tabIndex(key, index, count) {
66 if (key === 'Home') return 0;
67 if (key === 'End') return count - 1;
68 if (key === 'ArrowRight') return (index + 1) % count;
69 if (key === 'ArrowLeft') return (index + count - 1) % count;
70 return null;
71 },
72 // step moves an index within [0, n).
73 step(i, d, n) {
74 if (n === 0) return -1;
75 if (i < 0) return d > 0 ? 0 : n - 1;
76 return Math.max(0, Math.min(n - 1, i + d));
77 },
78 };
79
80 const $ = (sel, root = document) => root.querySelector(sel);
81 const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];
82 let refreshTouchComments = () => {};
83 let revealGen = 0; // the last reveal wins the scroll
84 const load = (ph) => window.ermiteLazy.load(ph);
85 window.ermiteLazy.onSwap(() => refreshTouchComments());
86
87 // reveal loads the file of an id (a file "f12" or a comment "c3") when it is
88 // a placeholder, then scrolls to it. It returns false when there is nothing
89 // to load.
90 function reveal(id, scroll = true) {
91 // Any navigation, loaded or not, makes the reveals still loading stale.
92 const gen = ++revealGen;
93 const target = () => {
94 // A page with both layouts says which shows in data-diff; a large diff
95 // rendered in one layout only says it in data-view.
96 const diffs = $('#diffs')?.dataset;
97 if (/^c\d+$/.test(id) && !window.matchMedia?.('(max-width: 720px)').matches && (diffs?.diff || diffs?.view) === 'split') {
98 const split = document.getElementById(id + '-s');
99 if (split) return split;
100 }
101 return document.getElementById(id);
102 };
103 let ph = document.getElementById(id)?.querySelector(':scope > .dlazy:not([data-manual])');
104 if (!ph && /^c\d+/.test(id) && !document.getElementById(id)) {
105 const base = id.replace(/-s$/, '');
106 ph = $$('.dlazy[data-notes]').find((p) => p.dataset.notes.split(' ').includes(base));
107 }
108 if (!ph) {
109 const el = target();
110 if (el && el.id !== id) {
111 const d = el.closest('details');
112 if (d) d.open = true;
113 if (scroll) el.scrollIntoView({ block: 'start' });
114 }
115 return false;
116 }
117 load(ph).then(() => {
118 // A later reveal (another file asked meanwhile) owns the view.
119 if (gen !== revealGen) return;
120 const el = target();
121 if (!el) return;
122 const d = el.closest('details');
123 if (d) d.open = true;
124 if (!scroll) return;
125 // The files above may have changed size while it loaded (placeholders,
126 // content-visibility): place it, then again once laid out.
127 el.scrollIntoView({ block: 'start' });
128 requestAnimationFrame(() => requestAnimationFrame(() => {
129 if (gen === revealGen) el.scrollIntoView({ block: 'start' });
130 }));
131 });
132 return true;
133 }
134
135 // The merge menu.
136 const menu = () => $('#merge-menu');
137 function openMerge() {
138 const m = menu();
139 if (!m) return false;
140 for (const d of $$('details.menu[open]')) if (d !== m) d.open = false;
141 m.open = true;
142 $('[data-default]', m)?.focus();
143 return true;
144 }
145 // menuKey handles a key while the merge menu is open; true when it used it.
146 function menuKey(e) {
147 const m = menu();
148 if (!m?.open || e.ctrlKey || e.metaKey || e.altKey) return false;
149 // An open dialog (help, commands) is above the menu: it keeps the keys.
150 if ($('dialog[open]')) return false;
151 // A field outside the menu (a comment being written) keeps its keys.
152 const field = e.target.closest?.('input, textarea, select, [contenteditable]');
153 if (field && !m.contains(field)) return false;
154 const radios = $$('input[name="mode"]', m);
155 const act = core.menuKey(e.key, radios.length);
156 if (!act) return false;
157 e.preventDefault();
158 if (act.toggle) {
159 const box = $('input[name="delete_branch"]', m);
160 if (box) box.checked = !box.checked;
161 } else {
162 const r = radios[act.mode];
163 // A change event lets the live bindings enable the Merge button again.
164 if (!r.disabled && !r.checked) {
165 r.checked = true;
166 r.dispatchEvent(new Event('change', { bubbles: true }));
167 }
168 }
169 $('[data-default]', m)?.focus();
170 return true;
171 }
172 function markRead() {
173 const b = $('button[data-read]');
174 if (!b) return false;
175 b.closest('form').requestSubmit(b);
176 return true;
177 }
178
179 // The list of files by keyboard: g f focuses the current file.
180 const links = () => $$('.r-files .files > li:not([hidden]) > a');
181 function focusFiles() {
182 foldFiles(false);
183 const all = links();
184 if (!all.length) return false;
185 const cur = all.find((a) => a.getAttribute('aria-current') === 'true') || all[0];
186 cur.focus();
187 cur.scrollIntoView({ block: 'nearest' });
188 return true;
189 }
190 // stepFiles moves the focus in the list; false when the focus is not in it.
191 function stepFiles(d) {
192 const all = links();
193 const i = all.indexOf(document.activeElement);
194 if (i < 0) return false;
195 const j = core.step(i, d, all.length);
196 all[j].focus();
197 all[j].scrollIntoView({ block: 'nearest' });
198 return true;
199 }
200 function leaveFiles() {
201 if (!links().includes(document.activeElement)) return false;
202 document.getElementById('main')?.focus({ preventScroll: true });
203 return true;
204 }
205
206 // foldFiles folds the list of files to its header, or opens it again:
207 // toggles without an argument. The choice is kept for the next pages.
208 function foldFiles(fold) {
209 const sec = $('.r-files');
210 const btn = sec && $('button.fold', sec);
211 if (!btn) return;
212 if (fold === undefined) fold = !sec.hasAttribute('data-folded');
213 sec.toggleAttribute('data-folded', fold);
214 btn.setAttribute('aria-expanded', String(!fold));
215 btn.title = fold ? 'open the list of files' : 'fold the list of files';
216 $('.sr', btn).textContent = btn.title;
217 // The list did not follow the review while folded: show its current file,
218 // moving the list only (never the page).
219 const box = !fold && $('.files', sec);
220 const a = box && $('a[aria-current="true"]', box);
221 if (a && (a.offsetTop < box.scrollTop || a.offsetTop + a.offsetHeight > box.scrollTop + box.clientHeight)) {
222 box.scrollTop = a.offsetTop - (box.clientHeight - a.offsetHeight) / 2;
223 }
224 try { localStorage.setItem('mr-files-folded', fold ? '1' : ''); } catch { /* storage refused: holds for this page */ }
225 }
226
227 // openFile opens the file of a link of the list (and loads it first).
228 function openFile(id) {
229 const f = document.getElementById(id);
230 if (f) f.open = true;
231 reveal(id);
232 }
233
234 // Enhance the ordinary anchor navigation only when scripts are available.
235 let disposePanels = () => {};
236 // The tabs are disclosure buttons (aria-expanded + aria-controls), not a
237 // tablist: a tablist always has a selected tab, and here every panel can be
238 // folded. State: the index of the open panel, or -1 for none.
239 function panels(initial = -1) {
240 disposePanels();
241 const footer = $('.mr-footer'), nav = $('[data-mr-tabs]');
242 if (!footer || !nav) return;
243 const tabs = $$('a', nav), panels = $$('[data-mr-panel]', footer);
244 const ids = new Set(['#mr-commits', '#mr-checks', '#mr-checks-panel']);
245 let current = -1;
246 // show applies the state; fromUser also keeps the URL fragment in step.
247 function show(index, fromUser = false) {
248 current = index;
249 tabs.forEach((tab, i) => {
250 tab.setAttribute('aria-controls', panels[i].id);
251 tab.setAttribute('aria-expanded', String(i === index));
252 panels[i].hidden = i !== index;
253 });
254 if (!fromUser) return;
255 if (index >= 0) {
256 if (location.hash !== '#' + panels[index].id) history.replaceState(null, '', '#' + panels[index].id);
257 } else if (ids.has(location.hash)) {
258 history.replaceState(null, '', location.pathname + location.search);
259 }
260 }
261 const toggle = (i) => show(i === current ? -1 : i, true);
262 tabs.forEach((tab, i) => {
263 tab.addEventListener('click', (e) => { e.preventDefault(); toggle(i); });
264 tab.addEventListener('keydown', (e) => {
265 const next = core.tabIndex(e.key, i, tabs.length);
266 if (next === null) return;
267 e.preventDefault(); tabs[next].focus();
268 });
269 });
270 // hash opens the panel of the URL fragment. Its target was hidden when the
271 // browser scrolled, so the panel is brought in; never on a refresh, which
272 // keeps the scroll.
273 function hash() {
274 const h = location.hash;
275 const index = h === '#mr-checks' || h === '#mr-checks-panel' ? 1 : h === '#mr-commits' ? 0 : -1;
276 if (index >= 0) { show(index); panels[index].scrollIntoView?.({ block: 'nearest' }); }
277 }
278 // The checks badge always opens Checks; it never folds it.
279 const checksClick = (e) => {
280 if (e.target.closest?.('#mr-ck')) show(1);
281 };
282 document.addEventListener('click', checksClick);
283 let observer;
284 const summary = $('#mr-ck');
285 if (summary) {
286 // The live stream replaces #mr-ck as a whole: watch only the children of
287 // its parent, and write the label only when it changes. hx-live rewrites
288 // other text in the same bar on every mutation of the document; a write
289 // here on each of them would wake hx-live again, a loop that never yields.
290 const sync = () => {
291 const label = $('[data-checks-label]', nav);
292 const text = $('#mr-ck')?.title || $('#mr-ck')?.textContent.trim() || 'no checks';
293 if (label && label.textContent !== text) label.textContent = text;
294 };
295 observer = new MutationObserver(sync);
296 observer.observe(summary.parentElement, { childList: true });
297 sync();
298 }
299 show(initial);
300 footer.setAttribute('data-panels', '');
301 if (initial < 0) hash();
302 addEventListener('hashchange', hash);
303 disposePanels = () => {
304 document.removeEventListener?.('click', checksClick);
305 window.removeEventListener?.('hashchange', hash);
306 observer?.disconnect?.();
307 };
308 }
309
310 let disposeTouch = () => {};
311 function touchComments(scroll = true) {
312 disposeTouch();
313 const diffs = $('#diffs');
314 const bar = document.createElement('div');
315 bar.className = 'mr-touch-range';
316 const button = document.createElement('button');
317 button.type = 'button';
318 button.className = 'btn';
319 button.textContent = 'Select line range';
320 button.setAttribute('aria-pressed', 'false');
321 const status = document.createElement('span');
322 status.setAttribute('role', 'status');
323 bar.append(button, status);
324 diffs.prepend(bar);
325 refreshTouchComments = () => { bar.hidden = !$('.ln a[href*="on="]', diffs); };
326 refreshTouchComments();
327 const touch = window.matchMedia?.('(pointer: coarse), (hover: none)');
328 let enabled = false, start = null, marker = null;
329 const clear = () => { marker?.removeAttribute('data-range-start'); marker = null; start = null; };
330 button.addEventListener('click', () => {
331 enabled = !enabled;
332 clear();
333 button.setAttribute('aria-pressed', String(enabled));
334 status.textContent = enabled ? 'Tap the first line number, then the last. Tap the same line for one line.' : '';
335 });
336 diffs.addEventListener('click', (e) => {
337 const link = e.target.closest?.('.ln a[href*="on="]');
338 if (!touch?.matches || !enabled || !link || e.shiftKey || e.ctrlKey || e.metaKey || e.altKey) return;
339 e.preventDefault();
340 e.stopPropagation(); // do not alter the desktop shift-click anchor
341 const next = core.touchRange(start, link.href, location.href);
342 clear();
343 if (next.url) { location.assign(next.url); return; }
344 start = next.start;
345 marker = link;
346 marker.setAttribute('data-range-start', '');
347 status.textContent = `Range starts at line ${link.textContent.trim()}. Tap the last line number (same file and side).`;
348 });
349 const changed = () => {
350 if (touch.matches) return;
351 enabled = false;
352 clear();
353 button.setAttribute('aria-pressed', 'false');
354 status.textContent = '';
355 };
356 touch?.addEventListener('change', changed);
357 disposeTouch = () => { touch?.removeEventListener?.('change', changed); bar.remove?.(); };
358 // The server opens the line form. Scroll after layout without stealing
359 // focus or forcing a mobile keyboard to appear.
360 if (scroll && new URL(location.href).searchParams.has('on')) requestAnimationFrame(() => {
361 const form = $$('.fnote .cform', diffs).find((f) => f.getClientRects().length);
362 form?.scrollIntoView({ block: 'center' });
363 });
364 }
365
366 // A refresh scheduler has one request in flight, a trailing debounce, and
367 // a dirty bit for pushes received during that request. Drafts are checked
368 // again after the fetch: typing while the network is slow is safe too.
369 function refresher({ blocked, fetchPage, apply, notice, failed, delay = 300 }) {
370 let timer, busy = false, pending = false;
371 const schedule = () => { clearTimeout(timer); timer = setTimeout(run, delay); };
372 async function run() {
373 if (busy || !pending) return;
374 if (blocked()) { notice(true); return; }
375 busy = true;
376 pending = false;
377 try {
378 const page = await fetchPage();
379 if (blocked()) { pending = true; notice(true); return; }
380 if (await apply(page) === false) { pending = true; notice(true); }
381 else notice(false);
382 } catch { if (blocked()) { pending = true; notice(true); } else failed(); }
383 finally {
384 busy = false;
385 if (pending && !blocked()) schedule();
386 }
387 }
388 return {
389 request() { pending = true; schedule(); },
390 resume() { if (pending) schedule(); },
391 pending() { return pending || busy; },
392 };
393 }
394
395 function hasDraft() {
396 // Only form controls, never diff rows. Inline edits live in .cmt forms; the
397 // merge form (d-acts) holds a chosen mode and the delete-branch box.
398 return $$(':is(form.cform, .cmt form, form.d-acts) :is(textarea, input, select)').some((t) => {
399 if (['hidden', 'submit', 'button', 'reset', 'image'].includes(t.type)) return false;
400 if (document.activeElement === t) return true;
401 if (t.type === 'radio' || t.type === 'checkbox') return t.checked !== t.defaultChecked;
402 if (t.tagName === 'SELECT') return [...t.options].some((o) => o.selected !== o.defaultSelected);
403 return t.value !== t.defaultValue;
404 }) ||
405 !!document.activeElement?.closest?.('.cform');
406 }
407
408 // Path + side + line is stable when files are inserted before this one;
409 // fN is only a positional anchor. Hidden unified/split rows are ignored.
410 function scrollAnchor() {
411 const top = Math.max(0, $('.hdr')?.getBoundingClientRect().bottom || 0,
412 $('.mr-bar')?.getBoundingClientRect().bottom || 0);
413 const diffs = $('#diffs');
414 const bounds = diffs.getBoundingClientRect();
415 const x = Math.max(1, Math.min(innerWidth - 1, bounds.left + Math.min(100, bounds.width / 2)));
416 // A bounded number of probes, independent of the number of diff lines.
417 let y = top + 2, fallback;
418 for (let probe = 0; probe < 6 && y < innerHeight; probe++) {
419 const hit = document.elementFromPoint(x, y);
420 const file = hit?.closest('details.dfile');
421 if (!file || !diffs.contains(file)) { y += 32; continue; }
422 const row = hit.closest('tr');
423 const link = row && $('.ln a[href*="on="]', row);
424 const header = $(':scope > summary', file);
425 const headerOffset = file.getBoundingClientRect().top;
426 fallback = { file: file.dataset.file, offset: headerOffset, headerOffset, y: scrollY };
427 if (link) return { ...fallback,
428 on: new URL(link.href, location.href).searchParams.get('on'),
429 suffix: link.getAttribute('href').split('on=')[1].split('#')[0],
430 offset: row.getBoundingClientRect().top };
431 if (file.open && header) y = Math.max(y + 24, header.getBoundingClientRect().bottom + 2);
432 else return fallback;
433 }
434 if (fallback) return fallback;
435 return { y: scrollY };
436 }
437
438 function restoreAnchor(anchor) {
439 const file = $$('#diffs details.dfile').find((f) => f.dataset.file === anchor.file);
440 let el, offset = anchor.offset;
441 if (file && anchor.on) {
442 const suffix = anchor.suffix && 'on=' + anchor.suffix + '#' + file.id;
443 const layout = $('#diffs').dataset.diff || $('#diffs').dataset.view;
444 const table = $(layout === 'split' && !window.matchMedia?.('(max-width: 720px)').matches ? '.dt.spl' : '.dt.uni', file) || file;
445 if (suffix) el = $('a[href$="' + CSS.escape(suffix) + '"]', table)?.closest('tr');
446 }
447 if (!el && file) { el = file; offset = anchor.headerOffset ?? anchor.offset; }
448 if (el) window.scrollBy({ top: el.getBoundingClientRect().top - offset, behavior: 'instant' });
449 else window.scrollTo({ top: Math.max(0, Math.min(anchor.y, document.documentElement.scrollHeight - innerHeight)), behavior: 'instant' });
450 }
451
452 async function fetchPage(url = location.href, mobileRetry = false) {
453 const res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'text/html' } });
454 if (!res.ok || res.redirected) throw new Error('MR refresh refused');
455 const page = new DOMParser().parseFromString(await res.text(), 'text/html');
456 if (!$('#diffs[data-mr]', page) || !$('.mr-bar', page) || !$('.hint-live', page)) throw new Error('not an MR page');
457 const unified = core.mobileURL(url, $('#diffs', page).dataset.view,
458 !!window.matchMedia?.('(max-width: 720px)').matches);
459 if (unified && !mobileRetry) return fetchPage(unified, true);
460 return page;
461 }
462
463 // htmx 4's public delete swap invokes recursive before:cleanup (including
464 // hx-sse's abort/reader.cancel and hx-live's binding disposal). Only an empty
465 // string is parsed; the fetched nodes themselves are adopted, never serialized.
466 async function replaceRegion(old, fresh) {
467 if (!old || !fresh) throw new Error('missing MR refresh region');
468 for (const el of $$('[autofocus]', fresh)) el.removeAttribute('autofocus');
469 const marker = document.createComment('MR region');
470 old.before(marker);
471 const remove = () => window.htmx.swap({ sourceElement: old, target: old, text: '',
472 swap: 'delete settle:0 transition:false', push: false, replace: false });
473 if (old.matches('.hint-live')) {
474 window.ermiteLive.resumeStream(fresh);
475 await window.ermiteLive.teardown(remove);
476 } else await remove();
477 const node = document.adoptNode(fresh);
478 marker.replaceWith(node);
479 window.htmx.process(node);
480 }
481
482 async function refreshPage(page) {
483 const regions = ['.mr-footer', '#mr-range', '.mr-bar', '#mr-diff-notices', '#diffs', '#mr-comments', '.rail', '.hint-live'];
484 for (const sel of regions) if (!$(sel) || !$(sel, page)) throw new Error('missing MR region');
485 let anchor = scrollAnchor();
486 const nextDiffs = $('#diffs', page);
487 const mobile = !!window.matchMedia?.('(max-width: 720px)').matches;
488 const chosen = mobile ? 'unified' : ($('#diffs').dataset.diff || $('#diffs').dataset.view);
489 if (nextDiffs.dataset.diff) nextDiffs.dataset.diff = chosen;
490 // A one-layout response must use its own contract, never the old page's.
491 if (mobile && nextDiffs.dataset.view === 'split') throw new Error('mobile needs unified');
492 const anchorFile = $$('#diffs details.dfile', page).find((f) => f.dataset.file === anchor.file);
493 const placeholder = anchorFile && $('.dlazy[data-src]', anchorFile);
494 if (placeholder) {
495 const d = nextDiffs.dataset;
496 const url = placeholder.dataset.src + '&view=' + encodeURIComponent(d.diff || d.view || 'unified') + '&layouts=' + (d.diff ? 'both' : 'one');
497 const res = await fetch(url, { credentials: 'same-origin', headers: { Accept: 'text/html' } });
498 if (!res.ok || res.redirected) throw new Error('anchor window changed');
499 let windowPage = new DOMParser().parseFromString(await res.text(), 'text/html');
500 if (hasDraft()) return false;
501 anchor = scrollAnchor();
502 const windowFiles = $$('details.dfile', windowPage);
503 // If the reader moved outside this window, discard it; lazy loading will
504 // fetch the new position rather than committing an unrelated window.
505 if (windowFiles.some((f) => f.dataset.file === anchor.file)) {
506 const byID = new Map($$('#diffs details.dfile', page).map((f) => [f.id, f]));
507 for (const f of windowFiles) byID.get(f.id)?.replaceWith(f);
508 }
509 windowPage = null;
510 }
511 if (hasDraft()) return false;
512 const files = new Map($$('#diffs details.dfile').map((f) => [f.dataset.file, f.open]));
513 const folded = $('.r-files')?.hasAttribute('data-folded');
514 const railY = $('.rail')?.scrollTop, filesY = $('.r-files .files')?.scrollTop;
515 const openPanel = $$('[data-mr-tabs] a').findIndex((t) => t.getAttribute('aria-expanded') === 'true');
516 const active = document.activeElement;
517 const focus = active && { file: active.closest?.('.files a')?.getAttribute('title'), region: regions.find((sel) => $(sel)?.contains(active)), menu: active.closest?.('details.menu')?.id, id: active.id, tag: active.tagName, name: active.getAttribute('name'), href: active.getAttribute('href') };
518 for (const f of $$('#diffs details.dfile', page)) if (files.has(f.dataset.file)) f.open = files.get(f.dataset.file);
519 ++revealGen; window.ermiteLazy.reset();
520 $('#diffs', page).dataset.mrStarted = 'true';
521 // The fresh footer comes in with the panels as they are, so that an open
522 // panel does not fold and open again while the other regions swap.
523 const freshFooter = $('.mr-footer', page);
524 if (freshFooter) {
525 freshFooter.setAttribute('data-panels', '');
526 $$('[data-mr-panel]', freshFooter).forEach((p, i) => { p.hidden = i !== openPanel; });
527 }
528 for (const sel of regions) {
529 const fresh = $(sel, page);
530 await replaceRegion($(sel), fresh);
531 }
532 for (const key of ['ref', 'sha', 'paths', 'blob']) {
533 if (page.body.dataset[key] !== undefined) document.body.dataset[key] = page.body.dataset[key];
534 }
535 const oldSHA = $('.hdr .ref .sha'), newSHA = $('.hdr .ref .sha', page);
536 if (oldSHA && newSHA) oldSHA.textContent = newSHA.textContent;
537 page = null;
538 panels(openPanel);
539 foldFiles(!!folded);
540 if ($('.rail')) $('.rail').scrollTop = railY;
541 if ($('.r-files .files')) $('.r-files .files').scrollTop = filesY;
542 touchComments(false);
543 $('#diffs').dataset.mobile = String(!!window.matchMedia?.('(max-width: 720px)').matches);
544 window.ermite?.refreshFiles?.();
545 window.ermiteLazy.watch();
546 if (focus && active !== document.body) {
547 const region = focus.region ? $(focus.region) : document;
548 const menu = focus.menu && document.getElementById(focus.menu);
549 if (menu) menu.open = true;
550 const el = focus.file ? $('a[title="' + CSS.escape(focus.file) + '"]', region) :
551 focus.id ? document.getElementById(focus.id) :
552 focus.href ? $('a[href="' + CSS.escape(focus.href) + '"]', region) :
553 focus.name ? $('[name="' + CSS.escape(focus.name) + '"]', region) :
554 menu?.querySelector(':scope > summary');
555 el?.focus({ preventScroll: true });
556 }
557 restoreAnchor(anchor);
558 }
559
560 function refreshNotice(deferred) {
561 const slot = $('#mr-refresh-status');
562 if (!slot) return;
563 slot.replaceChildren();
564 if (!deferred) {
565 const text = document.createElement('span'); text.className = 'sr'; text.textContent = 'branch updated'; slot.append(text);
566 return;
567 }
568 slot.append('branch updated — refreshing after your comment. ');
569
570 }
571 const headRefresh = refresher({ blocked: hasDraft, fetchPage, apply: refreshPage, notice: refreshNotice,
572 failed: () => window.ermiteLive?.reload() });
573 function headChanged() { if ($('#diffs[data-mr]')) headRefresh.request(); }
574
575 function start() {
576 if (!$('#diffs[data-mr]')) return;
577 if (window.ermiteLive) window.ermiteLive.canReload = () => {
578 if (!hasDraft()) return true;
579 headRefresh.request(); refreshNotice(true); return false;
580 };
581 // Global delegation is installed once; replacement regions have their own
582 // disposable panel/touch hooks below.
583 if ($('#diffs').dataset.mrStarted) return;
584 $('#diffs').dataset.mrStarted = 'true';
585 for (const type of ['input', 'focusout', 'reset', 'submit']) document.addEventListener?.(type, () => headRefresh.resume());
586 document.addEventListener?.('click', (e) => {
587 const cancel = e.target.closest?.('.cform .f-btns a');
588 if (!cancel || !headRefresh.pending() || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;
589 e.preventDefault();
590 const form = cancel.closest('.cform');
591 form.reset();
592 if (form.contains(document.activeElement)) document.activeElement.blur();
593 headRefresh.resume();
594 });
595 panels();
596 // Large diffs may contain only the split table. Ask the existing server
597 // route for unified rather than writing the saved session preference.
598 const narrow = window.matchMedia?.('(max-width: 720px)');
599 const unify = () => {
600 $('#diffs').dataset.mobile = String(!!narrow?.matches);
601 const url = core.mobileURL(location.href, $('#diffs')?.dataset.view, narrow?.matches);
602 if (url) { location.replace(url); return true; }
603 return false;
604 };
605 if (unify()) return;
606 narrow?.addEventListener('change', unify);
607 addEventListener('click', (e) => {
608 if (narrow?.matches && e.target.closest?.('.vbtn[data-view="split"]')) {
609 e.preventDefault();
610 e.stopImmediatePropagation();
611 }
612 }, true);
613 touchComments();
614 let folded = false;
615 try { folded = localStorage.getItem('mr-files-folded') === '1'; } catch { /* no storage: open */ }
616 if (folded) foldFiles(true);
617 // The page answers a refused action from the address of the action: show
618 // the address of the request, so that a reload does not post again.
619 const canonical = $('#diffs[data-canonical]')?.dataset.canonical;
620 if (canonical && location.pathname !== canonical) history.replaceState(history.state, '', canonical + location.hash);
621 // A link to a file or a comment that is not loaded yet.
622 const hash = () => {
623 const id = decodeURIComponent(location.hash.slice(1));
624 if (id) reveal(id);
625 };
626 addEventListener('hashchange', hash);
627 hash();
628 let lastLine = null;
629 try { lastLine = sessionStorage.getItem('mr-last-line'); } catch { /* storage optional */ }
630 addEventListener('click', (e) => {
631 const quote = e.target.closest?.('[data-quote]');
632 if (quote) { core.quote(quote); return; }
633 const link = e.target.closest?.('a[href*="on="]');
634 if (!link || e.ctrlKey || e.metaKey || e.altKey) return;
635 const next = e.shiftKey && lastLine && core.rangeURL(lastLine, link.href, location.href);
636 lastLine = link.href;
637 try { sessionStorage.setItem('mr-last-line', lastLine); } catch { /* storage optional */ }
638 if (next) { e.preventDefault(); location.assign(next); }
639 });
640 }
641
642 return { core, refresher, hasDraft, fetchPage, scrollAnchor, restoreAnchor, headChanged, panels, start, load, reveal, openMerge, menuKey, markRead, focusFiles, stepFiles, leaveFiles, foldFiles, openFile };
643})();
644
645if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', () => window.ermiteMR.start());
646else window.ermiteMR.start();