detached 27e453c

mr.test.mjs RawHistoryFolder

1// Tests of the pure core of the merge request page (static/js/mr.js). Run with
2//   node --test 'internal/adapters/web/jstest/*.test.mjs'
3import assert from 'node:assert/strict';
4import { test } from 'node:test';
5
6globalThis.window = globalThis;
7globalThis.document = { readyState: 'complete', querySelector: () => null, querySelectorAll: () => [] };
8await import('../static/js/mr.js');
9const C = window.ermiteMR.core;
10
11test('windowOf: the start of the window of a file', () => {
12  assert.equal(C.windowOf('f1', 25), 0);
13  assert.equal(C.windowOf('f25', 25), 0);
14  assert.equal(C.windowOf('f26', 25), 25);
15  assert.equal(C.windowOf('f84', 25), 75);
16  assert.equal(C.windowOf('c3', 25), -1, 'not a file');
17  assert.equal(C.windowOf('f0', 25), -1);
18});
19
20test('menuKey: modes by number, D toggles the deletion, nothing else', () => {
21  assert.deepEqual(C.menuKey('1', 2), { mode: 0 });
22  assert.deepEqual(C.menuKey('2', 2), { mode: 1 });
23  assert.equal(C.menuKey('3', 2), null, 'no third mode');
24  assert.equal(C.menuKey('0', 2), null);
25  assert.deepEqual(C.menuKey('D', 2), { toggle: true });
26  assert.equal(C.menuKey('d', 2), null, 'd is the split layout');
27  assert.equal(C.menuKey('Enter', 2), null, 'the browser submits: the focus is on the button');
28  assert.equal(C.menuKey('M', 2), null);
29});
30
31test('step: stays in the list', () => {
32  assert.equal(C.step(0, 1, 3), 1);
33  assert.equal(C.step(2, 1, 3), 2);
34  assert.equal(C.step(0, -1, 3), 0);
35  assert.equal(C.step(-1, 1, 3), 0);
36  assert.equal(C.step(-1, -1, 3), 2);
37  assert.equal(C.step(0, 1, 0), -1);
38});
39
40test('rangeURL requires the same file, side and MR and sorts endpoints', () => {
41 const base = 'https://forge.test/demo/merge-requests/1';
42 const a = base+'?on=new:24:dir%2Fa.go#f1';
43 const b = base+'?from=25&on=new:10:dir%2Fa.go#f1';
44 const u = new URL(C.rangeURL(a,b,base));
45 assert.equal(u.searchParams.get('on'),'new:10-24:dir/a.go');
46 assert.equal(u.searchParams.get('from'),'25');
47 assert.equal(u.hash,'#f1');
48 assert.equal(C.rangeURL(a,a,base),null);
49 assert.equal(C.rangeURL(a,b.replace('new:','old:'),base),null);
50 assert.equal(C.rangeURL(a,b.replace('a.go','b.go'),base),null);
51 assert.equal(C.rangeURL(a,b.replace('/1?','/2?'),base),null);
52});
53
54test('quote opens the thread reply and prefills and focuses its textarea', () => {
55 let focused=false;
56 const field={value:'',focus(){focused=true;}};
57 const details={open:false,querySelector(){return field;}};
58 const thread={querySelector(){return details;}};
59 const button={dataset:{quote:'> source\n\n^2 '},closest(){return {closest(){return thread;}};}};
60 assert.equal(C.quote(button),true);
61 assert.equal(details.open,true);
62 assert.equal(field.value,'> source\n\n^2 ');
63 assert.equal(focused,true);
64});
65
66for (const dataset of [{diff:'split'}, {view:'split'}]) test(`reveal selects the split note (${JSON.stringify(dataset)}), including after lazy loading`, async () => {
67 const saved = globalThis.document;
68 const savedRAF = globalThis.requestAnimationFrame;
69 let scrolled = '';
70 const details = {open:false};
71 const node = id => ({id, querySelector(){return null;}, closest(){return details;}, scrollIntoView(){scrolled=id;}});
72 const nodes = new Map([['c12',node('c12')],['c12-s',node('c12-s')]]);
73 const ph = {dataset:{notes:'c12'}};
74 globalThis.document = {
75   querySelector: sel => sel === '#diffs' ? {dataset} : null,
76   querySelectorAll: () => [ph],
77   getElementById: id => nodes.get(id),
78 };
79 globalThis.requestAnimationFrame = fn => fn();
80 try {
81   assert.equal(window.ermiteMR.reveal('c12'),false);
82   assert.equal(scrolled,'c12-s');
83   assert.equal(details.open,true);
84   nodes.clear(); scrolled=''; details.open=false;
85   assert.equal(window.ermiteMR.reveal('c12'),true);
86   nodes.set('c12',node('c12')); nodes.set('c12-s',node('c12-s'));
87   await Promise.resolve();
88   assert.equal(scrolled,'c12-s');
89   assert.equal(details.open,true);
90 } finally {
91   globalThis.document=saved;
92   globalThis.requestAnimationFrame=savedRAF;
93 }
94});
95
96test('footer tabs switch panels, support arrows, and open on checks hash', () => {
97  const oldDocument = globalThis.document;
98  const oldLocation = globalThis.location;
99  const oldAdd = globalThis.addEventListener;
100  const oldHistory = globalThis.history;
101  const listeners = {};
102  const replaced = [];
103  globalThis.history = { replaceState: (...args) => replaced.push(args) };
104  const node = (id) => ({ id, attrs: {}, events: {}, hidden: false,
105    setAttribute(k,v) { this.attrs[k]=v; },
106    addEventListener(k,v) { this.events[k]=v; }, focus() { this.focused=true; } });
107  const tabs = [node('mr-tab-commits'), node('mr-tab-checks')];
108  const panels = [node('mr-commits'), node('mr-checks-panel')];
109  const footer = node('mr-panels'); footer.open=false;
110  const nav = node('tabs'); nav.querySelectorAll=()=>tabs;
111  footer.querySelectorAll=()=>panels;
112  globalThis.document = {querySelector: (s) => s === '#mr-panels' ? footer : s === '[data-mr-tabs]' ? nav : null,
113    addEventListener(k,v) {listeners[k]=v;} };
114  globalThis.location = {hash:''};
115  globalThis.addEventListener = (k,v) => {listeners[k]=v;};
116  try {
117    window.ermiteMR.panels();
118    assert.equal(footer.open,false);
119    assert.equal(panels[0].hidden,false);
120    assert.equal(panels[1].hidden,true);
121    assert.deepEqual(replaced, [], 'initial selection leaves the URL alone');
122    tabs[1].events.click({preventDefault(){}});
123    assert.deepEqual(replaced, [[null, '', '#mr-checks-panel']]);
124    assert.equal(panels[0].hidden,true);
125    assert.equal(tabs[1].attrs['aria-selected'],'true');
126    tabs[1].events.keydown({key:'ArrowRight',preventDefault(){}});
127    assert.equal(tabs[0].focused,true);
128    assert.equal(panels[0].hidden,false);
129    assert.deepEqual(replaced.at(-1), [null, '', '#mr-commits']);
130    location.hash='#mr-checks'; replaced.length = 0; listeners.hashchange();
131    assert.deepEqual(replaced, [], 'hash navigation does not rewrite the URL');
132    assert.equal(footer.open,true);
133    assert.equal(panels[1].hidden,false);
134    footer.open=false;
135    listeners.click({target:{closest:()=>true}});
136    assert.equal(footer.open,true);
137    assert.equal(C.tabIndex('Home',1,2),0);
138    assert.equal(C.tabIndex('End',0,2),1);
139    assert.equal(C.tabIndex('ArrowLeft',0,2),1);
140    assert.equal(C.tabIndex('Escape',0,2),null);
141  } finally {
142    globalThis.document=oldDocument; globalThis.location=oldLocation; globalThis.addEventListener=oldAdd;
143    if (oldHistory === undefined) delete globalThis.history; else globalThis.history = oldHistory;
144  }
145});
146
147test('footer: #mr-ck syncs the checks label and a click opens the footer on Checks', () => {
148  const saved = Object.fromEntries(['document', 'location', 'addEventListener', 'history', 'MutationObserver'].map((k) => [k, globalThis[k]]));
149  const node = (id) => ({ id, attrs: {}, events: {}, hidden: false,
150    setAttribute(k, v) { this.attrs[k] = v; }, addEventListener(k, v) { this.events[k] = v; }, focus() {} });
151  const tabs = [node('t0'), node('t1')];
152  const panels = [node('mr-commits'), node('mr-checks-panel')];
153  const footer = node('mr-panels'); footer.open = false; footer.querySelectorAll = () => panels;
154  let writes = 0, text = '';
155  const label = { get textContent() { return text; }, set textContent(v) { writes++; text = v; } };
156  const nav = node('tabs'); nav.querySelectorAll = () => tabs;
157  nav.querySelector = (s) => s === '[data-checks-label]' ? label : null;
158  const summary = { title: '1/2 failed', textContent: ' 1/2 ', parentElement: {} };
159  const listeners = {};
160  let observed = null, callback = null;
161  globalThis.MutationObserver = class { constructor(fn) { callback = fn; } observe(target, opts) { observed = [target, opts]; } };
162  globalThis.document = { querySelector: (s) => s === '#mr-panels' ? footer : s === '[data-mr-tabs]' ? nav : s === '#mr-ck' ? summary : null,
163    addEventListener(k, v) { listeners[k] = v; } };
164  globalThis.location = { hash: '' };
165  globalThis.addEventListener = () => {};
166  globalThis.history = { replaceState() {} };
167  try {
168    window.ermiteMR.panels();
169    assert.equal(label.textContent, '1/2 failed', 'initial label sync');
170    assert.equal(observed[0], summary.parentElement);
171    // A mutation elsewhere in the bar (hx-live rewriting a label) must not
172    // write the label again, or hx-live wakes up on its own write forever.
173    assert.deepEqual(observed[1], { childList: true }, 'only #mr-ck replacements wake the observer');
174    const before = writes; callback(); callback();
175    assert.equal(writes, before, 'an unchanged label is not written');
176    summary.title = ''; callback();
177    assert.equal(label.textContent, '1/2', 'observer re-syncs from the text');
178    summary.textContent = ' '; callback();
179    assert.equal(label.textContent, 'no checks');
180    listeners.click({ target: { closest: (s) => s === '#mr-ck' ? summary : null } });
181    assert.equal(footer.open, true);
182    assert.equal(panels[1].hidden, false);
183    assert.equal(panels[0].hidden, true);
184    assert.equal(tabs[1].attrs['aria-selected'], 'true');
185  } finally {
186    for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; }
187  }
188});
189
190test('touch range: first tap anchors, second tap opens the sorted range', () => {
191  const base = 'https://forge.test/demo/merge-requests/1';
192  const first = base + '?on=new:24:a.go#f1';
193  const last = base + '?on=new:10:a.go#f1';
194  assert.deepEqual(C.touchRange(null, first, base), { start: first, url: null });
195  const result = C.touchRange(first, last, base);
196  assert.equal(result.start, null);
197  assert.equal(new URL(result.url).searchParams.get('on'), 'new:10-24:a.go');
198  assert.deepEqual(C.touchRange(first, first, base), { start: null, url: first });
199});
200
201test('touch range: a different file, side or request becomes a new anchor', () => {
202  const base = 'https://forge.test/demo/merge-requests/1';
203  const first = base + '?on=new:24:a.go#f1';
204  for (const next of [first.replace('new:', 'old:'), first.replace('a.go', 'b.go'), first.replace('/1?', '/2?')]) {
205    assert.deepEqual(C.touchRange(first, next, base), { start: next, url: null });
206  }
207});
208
209test('mobile unified fallback only redirects single-layout split pages and preserves query/hash', () => {
210  const href = 'https://forge.test/demo/merge-requests/1?view=split&from=25&on=new:3:a.go#f26';
211  assert.equal(C.mobileURL(href, 'split', false), null);
212  assert.equal(C.mobileURL(href, undefined, true), null, 'both layouts are switched by CSS');
213  assert.equal(C.mobileURL(href, 'unified', true), null, 'no redirect loop');
214  const url = new URL(C.mobileURL(href, 'split', true));
215  assert.equal(url.searchParams.get('view'), 'unified');
216  assert.equal(url.searchParams.get('from'), '25');
217  assert.equal(url.searchParams.get('on'), 'new:3:a.go');
218  assert.equal(url.hash, '#f26');
219});
220
221test('touch control: lazy links enable toolbar; ordinary taps pass through; ranges navigate and cancel', async () => {
222  const saved = Object.fromEntries(['document', 'location', 'addEventListener', 'localStorage', 'sessionStorage', 'fetch', 'matchMedia'].map((k) => [k, globalThis[k]]));
223  const make = () => ({
224    attrs: {}, events: {}, children: [], textContent: '',
225    setAttribute(k, v) { this.attrs[k] = v; },
226    removeAttribute(k) { delete this.attrs[k]; },
227    addEventListener(k, fn) { this.events[k] = fn; },
228    append(...nodes) { this.children.push(...nodes); },
229    prepend(node) { this.children.unshift(node); },
230    querySelector() { return null; }, querySelectorAll() { return []; },
231  });
232  const diffs = make();
233  diffs.dataset = { diff: 'split' };
234  const base = 'https://forge.test/demo/merge-requests/1';
235  const line = (n) => Object.assign(make(), { href: `${base}?on=new:${n}:a.go#f1`, textContent: String(n) });
236  const a = line(20), b = line(10);
237  let loaded = false;
238  diffs.querySelector = () => loaded ? a : null;
239  let assigned = null;
240  globalThis.document = {
241    querySelector: (sel) => sel === '#diffs[data-mr]' || sel === '#diffs' ? diffs : null,
242    querySelectorAll: () => [], createElement: (tag) => tag === 'template' ? { content: { querySelectorAll: () => [] } } : make(),
243  };
244  globalThis.location = { href: base, pathname: '/demo/merge-requests/1', hash: '', assign(url) { assigned = url; } };
245  globalThis.addEventListener = () => {};
246  const changes = {};
247  const medias = {};
248  globalThis.matchMedia = (q) => medias[q] ??= { matches: true, addEventListener(type, fn) { changes[q] = fn; } };
249  const media = globalThis.matchMedia('(max-width: 720px)');
250  const touchQuery = '(pointer: coarse), (hover: none)';
251  const resize = () => changes['(max-width: 720px)']();
252  globalThis.fetch = async () => { loaded = true; return { ok: true, status: 200, text: async () => '' }; };
253  globalThis.localStorage = globalThis.sessionStorage = { getItem: () => null };
254  const click = (link, modifiers = {}) => {
255    const e = { target: { closest: () => link }, prevented: false, stopped: false,
256      preventDefault() { this.prevented = true; }, stopPropagation() { this.stopped = true; }, ...modifiers };
257    diffs.events.click(e);
258    return e;
259  };
260  try {
261    window.ermiteMR.start();
262    const bar = diffs.children[0];
263    const [button, status] = bar.children;
264    assert.equal(bar.hidden, true, 'no commentable links in the initial window');
265    assert.equal(typeof diffs.events.click, 'function', 'delegation installed before lazy load');
266    await window.ermiteMR.load({ dataset: { src: '/files?from=25' } });
267    assert.equal(bar.hidden, false, 'lazy window refresh reveals range control');
268    assert.equal(diffs.dataset.mobile, 'true');
269    assert.equal(diffs.dataset.diff, 'split', 'preferred layout is retained');
270    media.matches = false;
271    resize();
272    assert.equal(diffs.dataset.mobile, 'false', 'desktop menu returns to preferred layout');
273    assert.equal(diffs.dataset.diff, 'split');
274    assert.equal(click(a).prevented, false, 'normal single-line navigation is untouched');
275    button.events.click();
276    assert.equal(button.attrs['aria-pressed'], 'true');
277    assert.equal(click(a, { shiftKey: true }).prevented, false, 'desktop range selection is untouched');
278    const event = click(a);
279    assert.equal(event.prevented, true);
280    assert.equal(event.stopped, true);
281    assert.ok('data-range-start' in a.attrs);
282    assert.match(status.textContent, /20/);
283    click(b);
284    assert.equal(new URL(assigned).searchParams.get('on'), 'new:10-20:a.go');
285    assert.equal('data-range-start' in a.attrs, false);
286    click(a);
287    button.events.click();
288    assert.equal(button.attrs['aria-pressed'], 'false');
289    assert.equal(status.textContent, '');
290    assert.equal('data-range-start' in a.attrs, false);
291    assert.equal(click(b).prevented, false);
292    // The touch media query stops matching: range mode is switched off.
293    button.events.click();
294    click(a);
295    assert.equal(button.attrs['aria-pressed'], 'true');
296    assert.ok('data-range-start' in a.attrs);
297    medias[touchQuery].matches = false;
298    changes[touchQuery]();
299    assert.equal(button.attrs['aria-pressed'], 'false');
300    assert.equal(status.textContent, '');
301    assert.equal('data-range-start' in a.attrs, false);
302    assert.equal(click(b).prevented, false, 'clicks pass through once touch stops matching');
303  } finally {
304    for (const [k, v] of Object.entries(saved)) {
305      if (v === undefined) delete globalThis[k]; else globalThis[k] = v;
306    }
307  }
308});
309
310// Deterministic timers: no sleeps, and each test restores every mocked global.
311function clock() {
312  const saved = { setTimeout: globalThis.setTimeout, clearTimeout: globalThis.clearTimeout };
313  const tasks = new Map(); let n = 0, now = 0;
314  globalThis.setTimeout = (fn, delay = 0) => { tasks.set(++n, { fn, at: now + delay }); return n; };
315  globalThis.clearTimeout = (id) => tasks.delete(id);
316  return { async tick(ms = 300) { now += ms; const batch = [...tasks].filter(([, t]) => t.at <= now); for (const [id] of batch) tasks.delete(id); for (const [, t] of batch) await t.fn(); },
317    size: () => tasks.size, restore() { Object.assign(globalThis, saved); } };
318}
319
320test('head refresh defers a real textarea draft, resumes after emptying and blurring', async () => {
321  const saved = globalThis.document, c = clock();
322  const text = { value: 'unsent', defaultValue: '' };
323  let fetched = 0, applied = 0; const notices = [];
324  globalThis.document = { activeElement: text, querySelectorAll: () => [text] };
325  const r = window.ermiteMR.refresher({ blocked: window.ermiteMR.hasDraft,
326    fetchPage: async () => { fetched++; return 'page'; }, apply: () => applied++,
327    notice: (v) => notices.push(v), failed: () => assert.fail('unexpected fallback') });
328  try {
329    r.request(); await c.tick();
330    assert.equal(fetched, 0); assert.deepEqual(notices, [true]);
331    text.value = ''; r.resume(); await c.tick();
332    assert.equal(fetched, 0, 'focus still protects an empty draft');
333    document.activeElement = null; r.resume(); await c.tick();
334    assert.equal(fetched, 1); assert.equal(applied, 1); assert.equal(r.pending(), false);
335  } finally { globalThis.document = saved; c.restore(); }
336});
337
338test('head refresh debounces bursts, serializes requests, and reruns after an in-flight push', async () => {
339  const c = clock(); let fetched = 0, applied = 0, resolve;
340  const r = window.ermiteMR.refresher({ blocked: () => false,
341    fetchPage: () => { fetched++; return new Promise((r) => { resolve = r; }); },
342    apply: () => applied++, notice() {}, failed: () => assert.fail('unexpected failure') });
343  try {
344    r.request(); r.request(); r.request(); assert.equal(c.size(), 1);
345    await c.tick(299); assert.equal(fetched, 0);
346    await c.tick(0); assert.equal(fetched, 0);
347    const first = c.tick(1); assert.equal(fetched, 1);
348    r.request(); await c.tick(); assert.equal(fetched, 1, 'one fetch in flight');
349    resolve('one'); await first; assert.equal(applied, 1); assert.equal(c.size(), 1);
350    const second = c.tick(); assert.equal(fetched, 2); resolve('two'); await second;
351    assert.equal(applied, 2); assert.equal(c.size(), 0);
352  } finally { c.restore(); }
353});
354
355test('typing during fetch defers even manual refresh until the draft ends', { timeout: 2000 }, async () => {
356  const c = clock(); let blocked = false, applied = 0, resolve, fetched = 0; const notices = [];
357  const r = window.ermiteMR.refresher({ blocked: () => blocked,
358    fetchPage: () => { fetched++; return new Promise((r) => { resolve = r; }); }, apply: () => { applied++; },
359    notice: (v) => notices.push(v), failed: () => assert.fail('unexpected failure') });
360  try {
361    r.request(); const first = c.tick(); blocked = true; resolve('page'); await first;
362    assert.equal(applied, 0); assert.deepEqual(notices, [true]);
363    r.request(true); const manual = c.tick();
364    assert.equal(fetched, 1, 'manual refresh must not start a fetch during a draft');
365    await manual; assert.equal(applied, 0);
366    blocked = false; r.resume(); const second = c.tick(); resolve('new page'); await second;
367    assert.equal(applied, 1); assert.equal(notices.at(-1), false);
368  } finally { c.restore(); }
369});
370
371test('fetch failures and non-MR responses take the fallback, never apply', async () => {
372  const saved = { fetch: globalThis.fetch, location: globalThis.location, DOMParser: globalThis.DOMParser };
373  const c = clock(); let fallback = 0;
374  globalThis.location = { href: 'https://forge.test/demo/merge-requests/1?view=split&from=25' };
375  const r = window.ermiteMR.refresher({ blocked: () => false, fetchPage: window.ermiteMR.fetchPage,
376    apply: () => assert.fail('must not swap'), notice() {}, failed: () => fallback++ });
377  try {
378    for (const result of ['network', { ok: false }, { ok: true, redirected: true }, { ok: true, text: async () => '<html>login</html>' }]) {
379      globalThis.fetch = async (url, opts) => {
380        assert.equal(url, location.href); assert.equal(opts.credentials, 'same-origin');
381        if (result === 'network') throw new Error('offline'); return result;
382      };
383      globalThis.DOMParser = class { parseFromString() { return { querySelector: () => null }; } };
384      r.request(); await c.tick();
385    }
386    assert.equal(fallback, 4);
387  } finally {
388    for (const [k,v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; }
389    c.restore();
390  }
391});
392
393test('viewport probe finds a stable path/side/line and restores its offset without line scans', () => {
394  const names = ['document', 'location', 'innerHeight', 'innerWidth', 'scrollY', 'scrollBy', 'scrollTo', 'CSS', 'matchMedia'];
395  const saved = Object.fromEntries(names.map((k) => [k, globalThis[k]]));
396  const rect = (top, bottom = top + 20) => ({ top, bottom, left: 0, width: 900 });
397  let lineTop = 160, headerTop = -200, found = true; const calls = [];
398  const header = { getBoundingClientRect: () => rect(headerTop) };
399  const row = { getBoundingClientRect: () => rect(lineTop), querySelector: () => link };
400  const link = { href: 'https://forge.test/demo/merge-requests/1?on=new:42:a.go#f2', closest: () => row, getAttribute: () => link.href };
401  const file = { getBoundingClientRect: () => rect(headerTop), id: 'f2', dataset: { file: 'a.go' }, querySelector: (s) => s.includes('summary') ? header : s.includes('href$') ? (assert.ok(s.includes('on=new:42:a.go#f3')), found ? link : null) : null };
402  const hit = { closest: (s) => s === 'tr' ? row : file };
403  const diffs = { dataset: { diff: 'unified' }, getBoundingClientRect: () => rect(120), contains: () => true };
404  globalThis.document = {
405    querySelector: (s) => s === '#diffs' ? diffs : s === '.hdr' ? { getBoundingClientRect: () => rect(0, 100) } : null,
406    querySelectorAll: (s) => { assert.equal(s, '#diffs details.dfile', 'only files, never every line'); return found === 'gone' ? [] : [file]; },
407    elementFromPoint: () => hit, documentElement: { scrollHeight: 10000 },
408  };
409  Object.assign(globalThis, { location: { href: link.href }, innerHeight: 800, innerWidth: 1200, scrollY: 2500,
410    scrollBy: (arg) => calls.push(['by', arg]), scrollTo: (arg) => calls.push(['to', arg]), CSS: { escape: (s) => s }, matchMedia: () => ({ matches: false }) });
411  try {
412    const a = window.ermiteMR.scrollAnchor();
413    assert.equal(a.file, 'a.go'); assert.equal(a.on, 'new:42:a.go'); assert.equal(a.offset, 160);
414    file.id = 'f3'; lineTop = 260; window.ermiteMR.restoreAnchor(a);
415    assert.deepEqual(calls.pop(), ['by', { top: 100, behavior: 'instant' }]);
416    found = false; headerTop = -100; window.ermiteMR.restoreAnchor(a);
417    assert.deepEqual(calls.pop(), ['by', { top: 100, behavior: 'instant' }]);
418    found = 'gone'; window.ermiteMR.restoreAnchor({ ...a, y: 20000 });
419    assert.deepEqual(calls.pop(), ['to', { top: 9200, behavior: 'instant' }]);
420  } finally { for (const [k,v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; } }
421});
422
423test('empty edited default and focused cform controls protect drafts', () => {
424  const saved = document;
425  try {
426    globalThis.document = { querySelectorAll: () => [{ value: '', defaultValue: 'existing' }], activeElement: null };
427    assert.equal(window.ermiteMR.hasDraft(), true);
428    document.querySelectorAll = () => [];
429    document.activeElement = { closest: (s) => s === '.cform' ? {} : null };
430    assert.equal(window.ermiteMR.hasDraft(), true);
431  } finally { globalThis.document = saved; }
432});
433
434test('failure during a draft keeps pending and resumes after the draft ends', async () => {
435  const c = clock(); let blocked = false, reject, applied = 0, count = 0;
436  const r = window.ermiteMR.refresher({ blocked: () => blocked,
437    fetchPage: () => ++count === 1 ? new Promise((_, no) => { reject = no; }) : Promise.resolve('page'),
438    apply: () => applied++, notice() {}, failed: () => assert.fail('draft must defer fallback') });
439  try {
440    r.request(); const first = c.tick(); blocked = true; reject(new Error('offline')); await first;
441    assert.equal(r.pending(), true); assert.equal(applied, 0);
442    blocked = false; r.resume(); await c.tick(); assert.equal(applied, 1);
443  } finally { c.restore(); }
444});
445
446test('anchor restoration retains the server encoding of tilde and star paths', () => {
447  const saved = { document, CSS: globalThis.CSS, scrollBy: globalThis.scrollBy };
448  try {
449    globalThis.CSS = { escape: (s) => s };
450    globalThis.scrollBy = () => {};
451    for (const path of ['a~.go', 'a*.go']) {
452      const encoded = path.replace('*', '%2A');
453      const row = { getBoundingClientRect: () => ({ top: 5 }) };
454      const file = { id: 'f9', dataset: { file: path }, querySelector: (s) => {
455        if (s === '.dt.uni') return file;
456        assert.equal(s, 'a[href$="on=new:12:' + encoded + '#f9"]');
457        return { closest: () => row };
458      } };
459      globalThis.document = { querySelectorAll: () => [file], querySelector: () => ({ dataset: { diff: 'unified' } }) };
460      window.ermiteMR.restoreAnchor({ file: path, suffix: 'new:12:' + encoded, on: 'new:12:' + path, offset: 5 });
461    }
462  } finally { Object.assign(globalThis, saved); }
463});
464
465for (const control of [
466  { type: 'radio', checked: true, defaultChecked: false },
467  { type: 'checkbox', checked: false, defaultChecked: true },
468  { type: 'number', name: 'start_line', value: '10', defaultValue: '12' },
469  { tagName: 'SELECT', options: [{ selected: true, defaultSelected: false }] },
470]) test(`changed ${control.name || control.type || control.tagName} remains a draft after blur`, () => {
471  const saved = document;
472  try {
473    globalThis.document = { activeElement: null, querySelectorAll(sel) {
474      assert.equal(sel, ':is(form.cform, .cmt form, form.d-acts) :is(textarea, input, select)');
475      return [control];
476    } };
477    assert.equal(window.ermiteMR.hasDraft(), true);
478  } finally { globalThis.document = saved; }
479});
480
481test('intercepted Cancel resets the entire comment form', () => {
482  const saved = Object.fromEntries(['document', 'location', 'addEventListener', 'matchMedia'].map(k => [k, globalThis[k]]));
483  const c = clock(), handlers = {};
484  const diffs = { dataset: { view: 'split' }, querySelector() { return null; }, querySelectorAll() { return []; } };
485  const radio = { type: 'radio', checked: true, defaultChecked: false };
486  const line = { type: 'number', value: '2', defaultValue: '4' };
487  let reset = 0, prevented = false;
488  const form = { reset() { reset++; radio.checked = radio.defaultChecked; line.value = line.defaultValue; }, contains() { return false; } };
489  const cancel = { closest: () => form };
490  globalThis.document = { activeElement: null,
491    querySelector: s => ['#diffs', '#diffs[data-mr]'].includes(s) ? diffs : null,
492    querySelectorAll: s => s.includes('form.cform') ? [radio, line] : [],
493    addEventListener: (type, fn) => { handlers[type] = fn; } };
494  globalThis.location = { pathname: '/demo/merge-requests/1', hash: '', href: 'https://forge.test/demo/merge-requests/1', replace() {} };
495  globalThis.addEventListener = () => {};
496  globalThis.matchMedia = () => ({ matches: true, addEventListener() {} });
497  try {
498    window.ermiteMR.start();
499    window.ermiteMR.headChanged();
500    handlers.click({ target: { closest: () => cancel }, preventDefault() { prevented = true; } });
501    assert.equal(prevented, true);
502    assert.equal(reset, 1);
503    assert.equal(window.ermiteMR.hasDraft(), false);
504  } finally { Object.assign(globalThis, saved); c.restore(); }
505});

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