gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmaina06fc778Reset virtual-list window when the host changes resetKeyAtlasmain/tests/virtual-list.mjs

10.4 KB

  1. // tests/virtual-list.mjs — THE GATE OF THE VIRTUAL LIST (components/virtual-list): its own server and a real headless Chrome; phone first (390 px), then 1280.
  2. // node tests/virtual-list.mjs env: COMPONENTS_GATE_PORT (server, default 8700), HL_PORT_BASE (Chrome debug ports: base+200 ..+209), COMPONENTS_SHOTS (screenshots dir)
  3. // The demo page /virtual-list has 13,449 generated rows and a page function that loads 50 rows around the viewport. Real wheel scrolling and real taps.
  4. import { spawn } from 'node:child_process';
  5. import { existsSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
  6. import { dirname, join, resolve } from 'node:path';
  7. import { fileURLToPath } from 'node:url';
  8. import { launchBrowser } from './cdp.mjs';
  9. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  10. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  11. const PORT = Number(process.env.COMPONENTS_GATE_PORT || 8700);
  12. const BASE = `http://127.0.0.1:${PORT}`;
  13. const SHOTS = process.env.COMPONENTS_SHOTS || join(APP, '.scratch/vl-shots');
  14. const SESSIONS = join(APP, '.scratch/vl-sessions');
  15. mkdirSync(SHOTS, { recursive: true }); rmSync(SESSIONS, { recursive: true, force: true }); mkdirSync(SESSIONS, { recursive: true });
  16. const OPTION = process.env.VL_OPTIONS;
  17. const demoPath = join(APP, 'components/virtual-list/demo.hl');
  18. const demoOriginal = OPTION ? (await import('node:fs')).readFileSync(demoPath, 'utf8') : null;
  19. if (OPTION) {
  20. let d = demoOriginal.replace('Hybrid chunk = []', 'Hybrid chunk = seedRows()').replace('Number chunkFrom = 0', 'Number chunkFrom = 200');
  21. d = d.replace('View {', `Number saved = 11200
  22. String initialCenter = '${OPTION === 'center' ? 'song-250' : ''}'
  23. Number reported = -1
  24. Number reports = 0
  25. seedRows() { out = [] let n = 200 while (n < 300) { out.push(makeRow(n)) n = n + 1 } return out }
  26. remember = (top) => { reported = top reports = reports + 1 }
  27. View {`);
  28. d = d.replace('selectedId = playingId', 'selectedId = playingId centerId = initialCenter onScroll = remember');
  29. d = d.replace('scrollTop = resetOffset', 'scrollTop = saved');
  30. d = d.replace('h1 { "Virtual list" }', 'h1 { "Virtual list" } output { id = "reported" reported } output { id = "reports" reports } button { id = "change" "Change inputs" on click() { initialCenter = "song-270" saved = 4000 } }');
  31. writeFileSync(demoPath, d);
  32. }
  33. let pass = 0, fail = 0, server = null, browser = null, log = '';
  34. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) pass++; else fail++; };
  35. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  36. async function stop() { if (browser) { try { await browser.close(); } catch {} } if (server) { try { server.kill('SIGTERM'); } catch {} await sleep(500); } }
  37. try {
  38. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, COMPONENTS_PORT: String(PORT), COMPONENTS_SESSIONS: SESSIONS + '/', COMPONENTS_WATCH: '0' }, stdio: ['ignore', 'pipe', 'pipe'] });
  39. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  40. for (const t0 = Date.now(); ; ) { try { if ((await fetch(BASE + '/')).ok) break; } catch {} if (server.exitCode !== null) throw new Error('fixture server exited\n' + log); if (Date.now() - t0 > 150000) throw new Error('server did not come up\n' + log); await sleep(300); }
  41. const home = await (await fetch(BASE + '/')).text();
  42. check('home lists the virtual list', home.includes('id="open-virtual-list"'));
  43. check('README is served', (await fetch(BASE + '/virtual-list/README.md')).ok);
  44. browser = await launchBrowser({ debugPortRange: (process.env.COMPONENTS_GATE_CHROME || '8701-8709').split('-').map(Number) });
  45. const page = await browser.newPage();
  46. const ev = (e) => page.evaluate(e);
  47. const shot = async (n) => writeFileSync(join(SHOTS, n + '.png'), Buffer.from((await page.send('Page.captureScreenshot', { format: 'png' })).data, 'base64'));
  48. let at = { x: 200, y: 300 };
  49. const wheel = (dy) => page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: at.x, y: at.y, deltaX: 0, deltaY: dy });
  50. const rows = () => ev(`document.querySelectorAll('virtual-list .vl-row').length`);
  51. const texts = () => ev(`[...document.querySelectorAll('virtual-list .vl-row')].filter(r => !r.classList.contains('blank')).map(r => r.querySelector('.vl-title').textContent)`);
  52. if (OPTION) {
  53. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  54. await page.goto(BASE + '/virtual-list');
  55. await page.waitForSelector('.vl-scroller'); await sleep(1000);
  56. const top = () => ev(`document.querySelector('.vl-scroller').scrollTop`);
  57. const expected = OPTION === 'center' ? await ev(`250 * 56 + 28 - document.querySelector('.vl-scroller').clientHeight / 2`) : 11200;
  58. check(OPTION + ': initial offset', Math.abs(await top() - expected) <= 1, `${await top()} vs ${expected}`);
  59. await page.click('#change'); await sleep(300);
  60. check(OPTION + ': changing inputs later does not jump', Math.abs(await top() - expected) <= 1);
  61. const b = await page.box('.vl-scroller');
  62. const before = Number(await ev(`document.querySelector('#reports').textContent`));
  63. for (let i = 0; i < 12; i++) { await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: b.x, y: b.y, deltaX: 0, deltaY: 60 }); await sleep(15); }
  64. await sleep(500);
  65. const reported = Number(await ev(`document.querySelector('#reported').textContent`));
  66. const reports = Number(await ev(`document.querySelector('#reports').textContent`)) - before;
  67. check('scroll callback delivers final offset', Math.abs(reported - await top()) <= 1 && await top() > expected, `${reported} vs ${await top()}`);
  68. check('scroll callback is throttled', reports > 0 && reports < 12, String(reports));
  69. await page.goto(BASE + '/virtual-list'); await sleep(1000);
  70. check(OPTION + ': reload applies the supplied initial offset again', Math.abs(await top() - expected) <= 1);
  71. } else for (const [w, h, mobile] of [[390, 800, true], [1280, 900, false]]) {
  72. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile });
  73. await page.goto(BASE + '/virtual-list');
  74. await page.waitForSelector('virtual-list .vl-row');
  75. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  76. await sleep(800);
  77. const tag = `@${w}: `;
  78. const n0 = await rows();
  79. check(tag + 'only the rows near the viewport exist (a few dozen of 13,449)', n0 > 8 && n0 < 100, '' + n0);
  80. check(tag + 'the first row is row 0 and has its text', (await texts())[0] === 'Song number 0', JSON.stringify((await texts()).slice(0, 2)));
  81. const g = await ev(`(() => { const r = [...document.querySelectorAll('virtual-list .vl-row')].map(e => e.getBoundingClientRect()); const r0 = document.querySelector('.vl-row'); const mid = (e) => { const b = e.getBoundingClientRect(); return b.top + b.height / 2 }; return { step: r.slice(1).map((x, i) => Math.round(x.top - r[i].top)), h: r[0].height, thumb: mid(r0.querySelector('.vl-thumb')), text: mid(r0.querySelector('.vl-text')), row: mid(r0), total: document.querySelector('.vl-spacer').getBoundingClientRect().height } })()`);
  82. check(tag + 'rows are exactly 56 px apart (dense: no gaps)', g.step.every(s => s === 56) && g.h === 56, JSON.stringify(g.step.slice(0, 4)));
  83. check(tag + 'thumbnail and text are centred on the row (±1 px)', Math.abs(g.thumb - g.row) <= 1 && Math.abs(g.text - g.row) <= 1, JSON.stringify(g));
  84. check(tag + 'the spacer is as tall as the whole list (13,449 × 56 px)', g.total === 13449 * 56, '' + g.total);
  85. at = await ev(`(() => { const b = document.querySelector('#vl-box').getBoundingClientRect(); return { x: Math.round(b.left + b.width / 2), y: Math.round(b.top + b.height / 2) } })()`);
  86. const fetches0 = Number(await ev(`document.querySelector('#vl-fetches').textContent`));
  87. // a real wheel scroll to the end
  88. for (let i = 0; i < 40; i++) { await wheel(80000); await sleep(40); }
  89. await page.waitFor(`(() => { const s = document.querySelector('.vl-scroller'); return s.scrollTop + s.clientHeight >= s.scrollHeight - 2 })()`, { timeout: 20000, label: 'scrolled to the end' });
  90. await sleep(900);
  91. const t = await texts();
  92. check(tag + 'at the end of 13,449 rows the page holds < 100 rows', (await rows()) < 100, '' + await rows());
  93. check(tag + 'the last row (13,449) arrived with its text, no blank rows left', t[t.length - 1] === 'Song number 13448' && (await ev(`document.querySelectorAll('.vl-row.blank').length`)) === 0, JSON.stringify(t.slice(-2)));
  94. const fetches1 = Number(await ev(`document.querySelector('#vl-fetches').textContent`));
  95. check(tag + 'the page was asked for rows only a few dozen times (not for every row)', fetches1 - fetches0 > 0 && fetches1 < 200, `${fetches0} → ${fetches1}`);
  96. // scroll a bit back up by wheel: rows near row 6000 appear after a jump
  97. await ev(`document.querySelector('.vl-scroller').scrollTop = 56 * 6000`);
  98. await page.waitFor(`[...document.querySelectorAll('.vl-row:not(.blank) .vl-title')].some(e => e.textContent === 'Song number 6003')`, { timeout: 10000, label: 'row 6003 loaded' });
  99. check(tag + 'a jump into the middle loads the rows there', (await rows()) < 100);
  100. // a real tap marks the row and tells the host
  101. await page.click('virtual-list .vl-row:not(.blank)');
  102. await page.waitFor(`document.querySelector('#vl-tapped').textContent.startsWith('song-')`, { timeout: 5000, label: 'host told' });
  103. const tapped = await ev(`document.querySelector('#vl-tapped').textContent`);
  104. check(tag + 'a real tap tells the host which row (id and place)', /^song-\d+ \(row \d+\)$/.test(tapped), tapped);
  105. await sleep(300);
  106. check(tag + 'the tapped row is marked current', (await ev(`document.querySelectorAll('.vl-row.current').length`)) === 1);
  107. await shot('virtual-list-' + w);
  108. // Host-driven reset coverage is in tests/virtual-list-reset.mjs.
  109. check(tag + 'no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  110. }
  111. await page.close();
  112. } catch (e) { fail++; console.log('FAIL stopped: ' + (e && e.stack || e)); if (log) console.log(log.slice(-1500)); }
  113. finally { await stop(); if (OPTION) writeFileSync(demoPath, demoOriginal); }
  114. console.log(`\n${pass} passed, ${fail} failed`);
  115. process.exit(fail ? 1 : 0);

Branches

Latest commits

  • a06fc778Reset virtual-list window when the host changes resetKeyAtlas
  • 3aab598cRe-vendor complete Hybriel day73 set for virtual-list resetAtlas
  • 337ca075MD1 gate check measures frames in the page, not milliseconds from outside, and takes the middle load (components#30)mre
  • f5f131c5Record AP29 autoplay comparisons and passing gatesmre
  • 51c38187Gate media autoplay on first load and after client mountmre
  • a3f2223dRecord successful B44 deployment and live proofmre
  • 06c1e021Record passing B44 browser rerunmre
  • c9861533Record B44 component proof and browser gate blockermre
  • 1b7413beIgnore detached media events and space demo option outputsmre
  • ca3b4959Re-vendor complete Hybriel plugins and runtime to day44mre
  • df9e7df9Last-item checks run in the browser gate (components#26 fixed on day41); media-player loop is a plain Booleanmre
  • 895a5afcRe-vendor complete Hybriel plugins and runtime to day41mre
  • 16006bb3Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 88397fc3Re-vendor complete Hybriel plugins and runtime to day39mre
  • 9b872cedRecord IC28 deployment and live icon verificationmre
  • 46fefaa7Count the icons entry in the offline home-page checkmre
  • c7e14cabRecord IC28 rerun and unchanged-main baseline comparisonmre
  • 5e090ffdRecord IC28 review evidence and gate resultsmre
  • adfe2c4dAdd shuffle, repeat and repeatOne shared iconsmre
  • c96709c8media-player: skip = false and repeat = 'one' options (jukebox#19)mre