detached cab7cdc

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  const label = { textContent: '' };
155  const nav = node('tabs'); nav.querySelectorAll = () => tabs;
156  nav.querySelector = (s) => s === '[data-checks-label]' ? label : null;
157  const summary = { title: '1/2 failed', textContent: ' 1/2 ', parentElement: {} };
158  const listeners = {};
159  let observed = null, callback = null;
160  globalThis.MutationObserver = class { constructor(fn) { callback = fn; } observe(target, opts) { observed = [target, opts]; } };
161  globalThis.document = { querySelector: (s) => s === '#mr-panels' ? footer : s === '[data-mr-tabs]' ? nav : s === '#mr-ck' ? summary : null,
162    addEventListener(k, v) { listeners[k] = v; } };
163  globalThis.location = { hash: '' };
164  globalThis.addEventListener = () => {};
165  globalThis.history = { replaceState() {} };
166  try {
167    window.ermiteMR.panels();
168    assert.equal(label.textContent, '1/2 failed', 'initial label sync');
169    assert.equal(observed[0], summary.parentElement);
170    summary.title = ''; callback();
171    assert.equal(label.textContent, '1/2', 'observer re-syncs from the text');
172    summary.textContent = ' '; callback();
173    assert.equal(label.textContent, 'no checks');
174    listeners.click({ target: { closest: (s) => s === '#mr-ck' ? summary : null } });
175    assert.equal(footer.open, true);
176    assert.equal(panels[1].hidden, false);
177    assert.equal(panels[0].hidden, true);
178    assert.equal(tabs[1].attrs['aria-selected'], 'true');
179  } finally {
180    for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; }
181  }
182});
183
184test('touch range: first tap anchors, second tap opens the sorted range', () => {
185  const base = 'https://forge.test/demo/merge-requests/1';
186  const first = base + '?on=new:24:a.go#f1';
187  const last = base + '?on=new:10:a.go#f1';
188  assert.deepEqual(C.touchRange(null, first, base), { start: first, url: null });
189  const result = C.touchRange(first, last, base);
190  assert.equal(result.start, null);
191  assert.equal(new URL(result.url).searchParams.get('on'), 'new:10-24:a.go');
192  assert.deepEqual(C.touchRange(first, first, base), { start: null, url: first });
193});
194
195test('touch range: a different file, side or request becomes a new anchor', () => {
196  const base = 'https://forge.test/demo/merge-requests/1';
197  const first = base + '?on=new:24:a.go#f1';
198  for (const next of [first.replace('new:', 'old:'), first.replace('a.go', 'b.go'), first.replace('/1?', '/2?')]) {
199    assert.deepEqual(C.touchRange(first, next, base), { start: next, url: null });
200  }
201});
202
203test('mobile unified fallback only redirects single-layout split pages and preserves query/hash', () => {
204  const href = 'https://forge.test/demo/merge-requests/1?view=split&from=25&on=new:3:a.go#f26';
205  assert.equal(C.mobileURL(href, 'split', false), null);
206  assert.equal(C.mobileURL(href, undefined, true), null, 'both layouts are switched by CSS');
207  assert.equal(C.mobileURL(href, 'unified', true), null, 'no redirect loop');
208  const url = new URL(C.mobileURL(href, 'split', true));
209  assert.equal(url.searchParams.get('view'), 'unified');
210  assert.equal(url.searchParams.get('from'), '25');
211  assert.equal(url.searchParams.get('on'), 'new:3:a.go');
212  assert.equal(url.hash, '#f26');
213});
214
215test('touch control: lazy links enable toolbar; ordinary taps pass through; ranges navigate and cancel', async () => {
216  const saved = Object.fromEntries(['document', 'location', 'addEventListener', 'localStorage', 'sessionStorage', 'fetch', 'matchMedia'].map((k) => [k, globalThis[k]]));
217  const make = () => ({
218    attrs: {}, events: {}, children: [], textContent: '',
219    setAttribute(k, v) { this.attrs[k] = v; },
220    removeAttribute(k) { delete this.attrs[k]; },
221    addEventListener(k, fn) { this.events[k] = fn; },
222    append(...nodes) { this.children.push(...nodes); },
223    prepend(node) { this.children.unshift(node); },
224    querySelector() { return null; }, querySelectorAll() { return []; },
225  });
226  const diffs = make();
227  diffs.dataset = { diff: 'split' };
228  const base = 'https://forge.test/demo/merge-requests/1';
229  const line = (n) => Object.assign(make(), { href: `${base}?on=new:${n}:a.go#f1`, textContent: String(n) });
230  const a = line(20), b = line(10);
231  let loaded = false;
232  diffs.querySelector = () => loaded ? a : null;
233  let assigned = null;
234  globalThis.document = {
235    querySelector: (sel) => sel === '#diffs[data-mr]' || sel === '#diffs' ? diffs : null,
236    querySelectorAll: () => [], createElement: (tag) => tag === 'template' ? { content: { querySelectorAll: () => [] } } : make(),
237  };
238  globalThis.location = { href: base, pathname: '/demo/merge-requests/1', hash: '', assign(url) { assigned = url; } };
239  globalThis.addEventListener = () => {};
240  const changes = {};
241  const medias = {};
242  globalThis.matchMedia = (q) => medias[q] ??= { matches: true, addEventListener(type, fn) { changes[q] = fn; } };
243  const media = globalThis.matchMedia('(max-width: 720px)');
244  const touchQuery = '(pointer: coarse), (hover: none)';
245  const resize = () => changes['(max-width: 720px)']();
246  globalThis.fetch = async () => { loaded = true; return { ok: true, status: 200, text: async () => '' }; };
247  globalThis.localStorage = globalThis.sessionStorage = { getItem: () => null };
248  const click = (link, modifiers = {}) => {
249    const e = { target: { closest: () => link }, prevented: false, stopped: false,
250      preventDefault() { this.prevented = true; }, stopPropagation() { this.stopped = true; }, ...modifiers };
251    diffs.events.click(e);
252    return e;
253  };
254  try {
255    window.ermiteMR.start();
256    const bar = diffs.children[0];
257    const [button, status] = bar.children;
258    assert.equal(bar.hidden, true, 'no commentable links in the initial window');
259    assert.equal(typeof diffs.events.click, 'function', 'delegation installed before lazy load');
260    await window.ermiteMR.load({ dataset: { src: '/files?from=25' } });
261    assert.equal(bar.hidden, false, 'lazy window refresh reveals range control');
262    assert.equal(diffs.dataset.mobile, 'true');
263    assert.equal(diffs.dataset.diff, 'split', 'preferred layout is retained');
264    media.matches = false;
265    resize();
266    assert.equal(diffs.dataset.mobile, 'false', 'desktop menu returns to preferred layout');
267    assert.equal(diffs.dataset.diff, 'split');
268    assert.equal(click(a).prevented, false, 'normal single-line navigation is untouched');
269    button.events.click();
270    assert.equal(button.attrs['aria-pressed'], 'true');
271    assert.equal(click(a, { shiftKey: true }).prevented, false, 'desktop range selection is untouched');
272    const event = click(a);
273    assert.equal(event.prevented, true);
274    assert.equal(event.stopped, true);
275    assert.ok('data-range-start' in a.attrs);
276    assert.match(status.textContent, /20/);
277    click(b);
278    assert.equal(new URL(assigned).searchParams.get('on'), 'new:10-20:a.go');
279    assert.equal('data-range-start' in a.attrs, false);
280    click(a);
281    button.events.click();
282    assert.equal(button.attrs['aria-pressed'], 'false');
283    assert.equal(status.textContent, '');
284    assert.equal('data-range-start' in a.attrs, false);
285    assert.equal(click(b).prevented, false);
286    // The touch media query stops matching: range mode is switched off.
287    button.events.click();
288    click(a);
289    assert.equal(button.attrs['aria-pressed'], 'true');
290    assert.ok('data-range-start' in a.attrs);
291    medias[touchQuery].matches = false;
292    changes[touchQuery]();
293    assert.equal(button.attrs['aria-pressed'], 'false');
294    assert.equal(status.textContent, '');
295    assert.equal('data-range-start' in a.attrs, false);
296    assert.equal(click(b).prevented, false, 'clicks pass through once touch stops matching');
297  } finally {
298    for (const [k, v] of Object.entries(saved)) {
299      if (v === undefined) delete globalThis[k]; else globalThis[k] = v;
300    }
301  }
302});
303
304// Deterministic timers: no sleeps, and each test restores every mocked global.
305function clock() {
306  const saved = { setTimeout: globalThis.setTimeout, clearTimeout: globalThis.clearTimeout };
307  const tasks = new Map(); let n = 0, now = 0;
308  globalThis.setTimeout = (fn, delay = 0) => { tasks.set(++n, { fn, at: now + delay }); return n; };
309  globalThis.clearTimeout = (id) => tasks.delete(id);
310  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(); },
311    size: () => tasks.size, restore() { Object.assign(globalThis, saved); } };
312}
313
314test('head refresh defers a real textarea draft, resumes after emptying and blurring', async () => {
315  const saved = globalThis.document, c = clock();
316  const text = { value: 'unsent', defaultValue: '' };
317  let fetched = 0, applied = 0; const notices = [];
318  globalThis.document = { activeElement: text, querySelectorAll: () => [text] };
319  const r = window.ermiteMR.refresher({ blocked: window.ermiteMR.hasDraft,
320    fetchPage: async () => { fetched++; return 'page'; }, apply: () => applied++,
321    notice: (v) => notices.push(v), failed: () => assert.fail('unexpected fallback') });
322  try {
323    r.request(); await c.tick();
324    assert.equal(fetched, 0); assert.deepEqual(notices, [true]);
325    text.value = ''; r.resume(); await c.tick();
326    assert.equal(fetched, 0, 'focus still protects an empty draft');
327    document.activeElement = null; r.resume(); await c.tick();
328    assert.equal(fetched, 1); assert.equal(applied, 1); assert.equal(r.pending(), false);
329  } finally { globalThis.document = saved; c.restore(); }
330});
331
332test('head refresh debounces bursts, serializes requests, and reruns after an in-flight push', async () => {
333  const c = clock(); let fetched = 0, applied = 0, resolve;
334  const r = window.ermiteMR.refresher({ blocked: () => false,
335    fetchPage: () => { fetched++; return new Promise((r) => { resolve = r; }); },
336    apply: () => applied++, notice() {}, failed: () => assert.fail('unexpected failure') });
337  try {
338    r.request(); r.request(); r.request(); assert.equal(c.size(), 1);
339    await c.tick(299); assert.equal(fetched, 0);
340    await c.tick(0); assert.equal(fetched, 0);
341    const first = c.tick(1); assert.equal(fetched, 1);
342    r.request(); await c.tick(); assert.equal(fetched, 1, 'one fetch in flight');
343    resolve('one'); await first; assert.equal(applied, 1); assert.equal(c.size(), 1);
344    const second = c.tick(); assert.equal(fetched, 2); resolve('two'); await second;
345    assert.equal(applied, 2); assert.equal(c.size(), 0);
346  } finally { c.restore(); }
347});
348
349test('typing during fetch defers even manual refresh until the draft ends', { timeout: 2000 }, async () => {
350  const c = clock(); let blocked = false, applied = 0, resolve, fetched = 0; const notices = [];
351  const r = window.ermiteMR.refresher({ blocked: () => blocked,
352    fetchPage: () => { fetched++; return new Promise((r) => { resolve = r; }); }, apply: () => { applied++; },
353    notice: (v) => notices.push(v), failed: () => assert.fail('unexpected failure') });
354  try {
355    r.request(); const first = c.tick(); blocked = true; resolve('page'); await first;
356    assert.equal(applied, 0); assert.deepEqual(notices, [true]);
357    r.request(true); const manual = c.tick();
358    assert.equal(fetched, 1, 'manual refresh must not start a fetch during a draft');
359    await manual; assert.equal(applied, 0);
360    blocked = false; r.resume(); const second = c.tick(); resolve('new page'); await second;
361    assert.equal(applied, 1); assert.equal(notices.at(-1), false);
362  } finally { c.restore(); }
363});
364
365test('fetch failures and non-MR responses take the fallback, never apply', async () => {
366  const saved = { fetch: globalThis.fetch, location: globalThis.location, DOMParser: globalThis.DOMParser };
367  const c = clock(); let fallback = 0;
368  globalThis.location = { href: 'https://forge.test/demo/merge-requests/1?view=split&from=25' };
369  const r = window.ermiteMR.refresher({ blocked: () => false, fetchPage: window.ermiteMR.fetchPage,
370    apply: () => assert.fail('must not swap'), notice() {}, failed: () => fallback++ });
371  try {
372    for (const result of ['network', { ok: false }, { ok: true, redirected: true }, { ok: true, text: async () => '<html>login</html>' }]) {
373      globalThis.fetch = async (url, opts) => {
374        assert.equal(url, location.href); assert.equal(opts.credentials, 'same-origin');
375        if (result === 'network') throw new Error('offline'); return result;
376      };
377      globalThis.DOMParser = class { parseFromString() { return { querySelector: () => null }; } };
378      r.request(); await c.tick();
379    }
380    assert.equal(fallback, 4);
381  } finally {
382    for (const [k,v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; }
383    c.restore();
384  }
385});
386
387test('viewport probe finds a stable path/side/line and restores its offset without line scans', () => {
388  const names = ['document', 'location', 'innerHeight', 'innerWidth', 'scrollY', 'scrollBy', 'scrollTo', 'CSS', 'matchMedia'];
389  const saved = Object.fromEntries(names.map((k) => [k, globalThis[k]]));
390  const rect = (top, bottom = top + 20) => ({ top, bottom, left: 0, width: 900 });
391  let lineTop = 160, headerTop = -200, found = true; const calls = [];
392  const header = { getBoundingClientRect: () => rect(headerTop) };
393  const row = { getBoundingClientRect: () => rect(lineTop), querySelector: () => link };
394  const link = { href: 'https://forge.test/demo/merge-requests/1?on=new:42:a.go#f2', closest: () => row, getAttribute: () => link.href };
395  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 };
396  const hit = { closest: (s) => s === 'tr' ? row : file };
397  const diffs = { dataset: { diff: 'unified' }, getBoundingClientRect: () => rect(120), contains: () => true };
398  globalThis.document = {
399    querySelector: (s) => s === '#diffs' ? diffs : s === '.hdr' ? { getBoundingClientRect: () => rect(0, 100) } : null,
400    querySelectorAll: (s) => { assert.equal(s, '#diffs details.dfile', 'only files, never every line'); return found === 'gone' ? [] : [file]; },
401    elementFromPoint: () => hit, documentElement: { scrollHeight: 10000 },
402  };
403  Object.assign(globalThis, { location: { href: link.href }, innerHeight: 800, innerWidth: 1200, scrollY: 2500,
404    scrollBy: (arg) => calls.push(['by', arg]), scrollTo: (arg) => calls.push(['to', arg]), CSS: { escape: (s) => s }, matchMedia: () => ({ matches: false }) });
405  try {
406    const a = window.ermiteMR.scrollAnchor();
407    assert.equal(a.file, 'a.go'); assert.equal(a.on, 'new:42:a.go'); assert.equal(a.offset, 160);
408    file.id = 'f3'; lineTop = 260; window.ermiteMR.restoreAnchor(a);
409    assert.deepEqual(calls.pop(), ['by', { top: 100, behavior: 'instant' }]);
410    found = false; headerTop = -100; window.ermiteMR.restoreAnchor(a);
411    assert.deepEqual(calls.pop(), ['by', { top: 100, behavior: 'instant' }]);
412    found = 'gone'; window.ermiteMR.restoreAnchor({ ...a, y: 20000 });
413    assert.deepEqual(calls.pop(), ['to', { top: 9200, behavior: 'instant' }]);
414  } finally { for (const [k,v] of Object.entries(saved)) { if (v === undefined) delete globalThis[k]; else globalThis[k] = v; } }
415});
416
417test('empty edited default and focused cform controls protect drafts', () => {
418  const saved = document;
419  try {
420    globalThis.document = { querySelectorAll: () => [{ value: '', defaultValue: 'existing' }], activeElement: null };
421    assert.equal(window.ermiteMR.hasDraft(), true);
422    document.querySelectorAll = () => [];
423    document.activeElement = { closest: (s) => s === '.cform' ? {} : null };
424    assert.equal(window.ermiteMR.hasDraft(), true);
425  } finally { globalThis.document = saved; }
426});
427
428test('failure during a draft keeps pending and resumes after the draft ends', async () => {
429  const c = clock(); let blocked = false, reject, applied = 0, count = 0;
430  const r = window.ermiteMR.refresher({ blocked: () => blocked,
431    fetchPage: () => ++count === 1 ? new Promise((_, no) => { reject = no; }) : Promise.resolve('page'),
432    apply: () => applied++, notice() {}, failed: () => assert.fail('draft must defer fallback') });
433  try {
434    r.request(); const first = c.tick(); blocked = true; reject(new Error('offline')); await first;
435    assert.equal(r.pending(), true); assert.equal(applied, 0);
436    blocked = false; r.resume(); await c.tick(); assert.equal(applied, 1);
437  } finally { c.restore(); }
438});
439
440test('anchor restoration retains the server encoding of tilde and star paths', () => {
441  const saved = { document, CSS: globalThis.CSS, scrollBy: globalThis.scrollBy };
442  try {
443    globalThis.CSS = { escape: (s) => s };
444    globalThis.scrollBy = () => {};
445    for (const path of ['a~.go', 'a*.go']) {
446      const encoded = path.replace('*', '%2A');
447      const row = { getBoundingClientRect: () => ({ top: 5 }) };
448      const file = { id: 'f9', dataset: { file: path }, querySelector: (s) => {
449        if (s === '.dt.uni') return file;
450        assert.equal(s, 'a[href$="on=new:12:' + encoded + '#f9"]');
451        return { closest: () => row };
452      } };
453      globalThis.document = { querySelectorAll: () => [file], querySelector: () => ({ dataset: { diff: 'unified' } }) };
454      window.ermiteMR.restoreAnchor({ file: path, suffix: 'new:12:' + encoded, on: 'new:12:' + path, offset: 5 });
455    }
456  } finally { Object.assign(globalThis, saved); }
457});
458
459for (const control of [
460  { type: 'radio', checked: true, defaultChecked: false },
461  { type: 'checkbox', checked: false, defaultChecked: true },
462  { type: 'number', name: 'start_line', value: '10', defaultValue: '12' },
463  { tagName: 'SELECT', options: [{ selected: true, defaultSelected: false }] },
464]) test(`changed ${control.name || control.type || control.tagName} remains a draft after blur`, () => {
465  const saved = document;
466  try {
467    globalThis.document = { activeElement: null, querySelectorAll(sel) {
468      assert.equal(sel, ':is(form.cform, .cmt form, form.d-acts) :is(textarea, input, select)');
469      return [control];
470    } };
471    assert.equal(window.ermiteMR.hasDraft(), true);
472  } finally { globalThis.document = saved; }
473});
474
475test('intercepted Cancel resets the entire comment form', () => {
476  const saved = Object.fromEntries(['document', 'location', 'addEventListener', 'matchMedia'].map(k => [k, globalThis[k]]));
477  const c = clock(), handlers = {};
478  const diffs = { dataset: { view: 'split' }, querySelector() { return null; }, querySelectorAll() { return []; } };
479  const radio = { type: 'radio', checked: true, defaultChecked: false };
480  const line = { type: 'number', value: '2', defaultValue: '4' };
481  let reset = 0, prevented = false;
482  const form = { reset() { reset++; radio.checked = radio.defaultChecked; line.value = line.defaultValue; }, contains() { return false; } };
483  const cancel = { closest: () => form };
484  globalThis.document = { activeElement: null,
485    querySelector: s => ['#diffs', '#diffs[data-mr]'].includes(s) ? diffs : null,
486    querySelectorAll: s => s.includes('form.cform') ? [radio, line] : [],
487    addEventListener: (type, fn) => { handlers[type] = fn; } };
488  globalThis.location = { pathname: '/demo/merge-requests/1', hash: '', href: 'https://forge.test/demo/merge-requests/1', replace() {} };
489  globalThis.addEventListener = () => {};
490  globalThis.matchMedia = () => ({ matches: true, addEventListener() {} });
491  try {
492    window.ermiteMR.start();
493    window.ermiteMR.headChanged();
494    handlers.click({ target: { closest: () => cancel }, preventDefault() { prevented = true; } });
495    assert.equal(prevented, true);
496    assert.equal(reset, 1);
497    assert.equal(window.ermiteMR.hasDraft(), false);
498  } finally { Object.assign(globalThis, saved); c.restore(); }
499});

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