gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5e090ffd5e090ffdRecord IC28 review evidence and gate resultsmre5e090ffd/tests/browser.mjs

210.8 KB

  1. // tests/browser.mjs — THE GATE of components.hybriel.worldapi.org: its own server, real headless Chrome.
  2. // node tests/browser.mjs (COMPONENTS_GATE_PORT server, default 8700; COMPONENTS_GATE_CHROME "8701-8709" = Chrome debug ports)
  3. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  4. import { spawn, execSync } from 'node:child_process';
  5. import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
  6. import { dirname, join, resolve } from 'node:path';
  7. import { fileURLToPath } from 'node:url';
  8. import zlib from 'node:zlib';
  9. import { launchBrowser } from './cdp.mjs';
  10. import { iconChecks } from './icons.mjs';
  11. import { mediaOptions } from './media-options.mjs';
  12. import { mdKeys } from './md-keys.mjs';
  13. import { mdPaste } from './md-paste.mjs';
  14. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  15. const HERE = dirname(fileURLToPath(import.meta.url));
  16. const APP = resolve(HERE, '..');
  17. const PORT = Number(process.env.COMPONENTS_GATE_PORT || 8700);
  18. const [CH_FROM, CH_TO] = (process.env.COMPONENTS_GATE_CHROME || '8701-8709').split('-').map(Number);
  19. const BASE = `http://127.0.0.1:${PORT}`;
  20. const SCRATCH = join(APP, '.scratch');
  21. const SESSIONS = join(SCRATCH, 'gate-sessions');
  22. // a re-vendored Hybriel compiles the app at its first start (cold 18–41 s, hybriel#148; then ~1 s from its build cache):
  23. // every server start waits up to COLD_MS (COMPONENTS_COLD_MS, default 120 s)
  24. const COLD_MS = Number(process.env.COMPONENTS_COLD_MS || 120000);
  25. rmSync(SESSIONS, { recursive: true, force: true });
  26. mkdirSync(SESSIONS, { recursive: true });
  27. let failures = 0, passes = 0;
  28. function check(label, ok, detail = '') {
  29. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  30. if (ok) passes++; else failures++;
  31. }
  32. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  33. let log = '', server = null, browser = null;
  34. async function stop() {
  35. if (browser) { try { await browser.close(); } catch {} browser = null; }
  36. await stopServer();
  37. }
  38. // the server alone goes down and up again in the offline checks (mission 046)
  39. async function stopServer() {
  40. if (server) {
  41. try { server.kill('SIGTERM'); } catch {}
  42. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  43. server = null;
  44. }
  45. }
  46. async function startServer() {
  47. 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'] });
  48. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  49. for (const t0 = Date.now(); ; ) {
  50. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  51. if (Date.now() - t0 > COLD_MS) throw new Error('server did not come up\n' + log);
  52. await sleep(250);
  53. }
  54. }
  55. async function main() {
  56. await startServer();
  57. // the home lists the component; its README is served
  58. const home = await (await fetch(BASE + '/')).text();
  59. check('no month-view.js served', (await fetch(BASE + '/month-view/month-view.js')).status === 404 && !existsSync(join(APP, 'components/month-view/month-view.js')));
  60. check('home lists the month view', home.includes('id="open-month-view"'));
  61. check('home shows only the list, no component embedded (creator 2026-09-25)', !home.includes('<month-view'));
  62. const readme = await fetch(BASE + '/month-view/README.md');
  63. check('README is served as Markdown', readme.ok && /markdown/.test(readme.headers.get('content-type')) && (await readme.text()).includes('Month view'));
  64. // first render on the server: 6 weeks of 7 days, one today
  65. const demo = await (await fetch(BASE + '/month-view')).text();
  66. check('server renders 42 days and one today', (demo.match(/<li class=/g) || []).length === 42 && (demo.match(/class="today"/g) || []).length === 1);
  67. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  68. const page = await browser.newPage();
  69. const SLOW = 3;
  70. const goto = page.goto.bind(page);
  71. page.goto = (u, o = {}) => goto(u, { ...o, timeout: 15000 * SLOW });
  72. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  73. await iconChecks(page, BASE, check);
  74. // a zone already on the next day (UTC+14) compared with the server's UTC date: the visitor's today must win (ticket #11)
  75. await page.send('Emulation.setTimezoneOverride', { timezoneId: 'Pacific/Kiritimati' });
  76. await page.goto(BASE + '/month-view');
  77. // the month view's own demo page (the home only lists the components)
  78. await page.waitForSelector('#month-title');
  79. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  80. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  81. const ev = (e) => page.evaluate(e);
  82. const title = () => ev('document.querySelector("#month-title").textContent');
  83. const localToday = await ev(`(() => { const n = new Date(), p = x => String(x).padStart(2, '0'); return n.getFullYear() + '-' + p(n.getMonth() + 1) + '-' + p(n.getDate()); })()`);
  84. const expectTitle = (y, m) => ev(`new Intl.DateTimeFormat(document.documentElement.lang || 'en', { month: 'long' }).format(new Date(Date.UTC(${y}, ${m - 1}, 15, 12))) + ' ${y}'`);
  85. const [ty, tm] = localToday.split('-').map(Number);
  86. // the browser's today and language arrive at load, with no pointer needed (the language is the PAGE's, mission MC)
  87. await page.waitFor(`!!document.querySelector('li.today time') && document.querySelector('li.today time').getAttribute('datetime') === ${JSON.stringify(localToday)}`, { label: 'browser today marked at load' });
  88. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 300, y: 200 });
  89. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === (${JSON.stringify(await expectTitle(ty, tm))}).toLowerCase()`, { label: 'title in the page language (English: the page declares none)' });
  90. check('title is the current month and year in the page language (English when the page declares none)', true);
  91. check('today is marked (browser date)', (await ev(`document.querySelector('li.today time').getAttribute('datetime')`)) === localToday, localToday);
  92. check('42 days, 6 weeks', (await ev('document.querySelectorAll("#month-days li").length')) === 42);
  93. const t0 = await title();
  94. // next / prev
  95. await page.click('#month-next');
  96. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(t0)}`, { label: 'next month' });
  97. const nm = tm === 12 ? 1 : tm + 1, ny = tm === 12 ? ty + 1 : ty;
  98. await page.waitFor(`document.querySelector('#month-title').textContent.toLowerCase() === ${JSON.stringify((await expectTitle(ny, nm)).toLowerCase())}`, { label: 'next month in the page language' });
  99. check('next shows the next month', true);
  100. await page.click('#month-prev');
  101. await page.waitFor(`document.querySelector("#month-title").textContent === ${JSON.stringify(t0)}`, { label: 'prev month' });
  102. check('prev returns to the month, today marked again', (await ev('document.querySelectorAll("li.today").length')) === 1);
  103. // walk to February 2028 (leap year) and check its days and its first weekday (Tuesday)
  104. let guard = 0;
  105. const feb28 = (await expectTitle(2028, 2)).toLowerCase();
  106. while ((await title()).toLowerCase() !== feb28 && guard++ < 40) {
  107. const before = await title();
  108. await page.click('#month-next');
  109. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging' });
  110. }
  111. const feb = await ev(`(() => { const inM = [...document.querySelectorAll('month-view #month-days li:not(.outside) time')]; const first = document.querySelector('#month-days li:not(.outside)'); return { n: inM.length, col: [...first.parentNode.children].indexOf(first) % 7 }; })()`);
  112. check('Feb 2028: 29 days, the 1st is a Tuesday (column 2)', feb.n === 29 && feb.col === 1, JSON.stringify(feb));
  113. // year rollover: go back to December 2027 and January 2028 by prev
  114. await page.click('#month-prev');
  115. await page.click('#month-prev');
  116. const dec27 = (await expectTitle(2027, 12)).toLowerCase();
  117. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify(dec27)}`, { label: 'back to December' });
  118. const dec = await ev(`(() => ({ n: document.querySelectorAll('#month-days li:not(.outside)').length, col: [...document.querySelectorAll('#month-days li')].indexOf(document.querySelector('#month-days li:not(.outside)')) % 7 }))()`);
  119. check('Dec 2027: 31 days, the 1st is a Wednesday', dec.n === 31 && dec.col === 2, JSON.stringify(dec));
  120. check('no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  121. // the date picker: click the field, pick a day, the value is YYYY-MM-DD; typing works
  122. check('home lists the date picker', home.includes('id="open-date-picker"'));
  123. check('date picker README is served', (await fetch(BASE + '/date-picker/README.md')).ok);
  124. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  125. await page.goto(BASE + '/date-picker');
  126. await page.waitForSelector('date-picker input');
  127. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  128. await sleep(1500);
  129. check('the date picker page loads no script file of its own', (await ev(`[...document.scripts].filter(s => s.src && !s.src.includes('__hl')).length`)) === 0);
  130. const pop = (n) => `getComputedStyle(document.querySelectorAll('date-picker picker-popup')[${n}]).display !== 'none'`;
  131. const val = (n) => ev(`document.querySelectorAll('date-picker input')[${n}].value`);
  132. const realClick = async (sel) => {
  133. const r = await ev(`(() => { const b = document.querySelector(${JSON.stringify(sel)}).getBoundingClientRect(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; })()`);
  134. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: r.x, y: r.y, button: 'none' });
  135. await sleep(120);
  136. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  137. await sleep(100);
  138. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  139. await sleep(700);
  140. };
  141. const typeInto = async (n, text) => {
  142. await ev(`document.querySelectorAll('date-picker input')[${n}].focus()`);
  143. await ev(`document.querySelectorAll('date-picker input')[${n}].select()`);
  144. await page.send('Input.insertText', { text });
  145. await sleep(400);
  146. };
  147. check('two fields with their names', (await ev(`[...document.querySelectorAll('date-picker input')].map(i => i.name).join()`)) === 'arrival,departure');
  148. check('the month is closed at first', !(await ev(pop(0))) && !(await ev(pop(1))));
  149. await realClick('date-picker input[name=arrival]');
  150. await page.waitFor(pop(0), { label: 'popup open' });
  151. check('click on the field opens the month under it', (await ev(pop(0))) && !(await ev(pop(1))));
  152. const pos = await ev(`(() => { const f = document.querySelectorAll('date-picker input')[0].getBoundingClientRect(), p = document.querySelectorAll('date-picker picker-popup')[0].getBoundingClientRect(); return { dx: Math.abs(p.left - f.left), dy: p.top - f.bottom }; })()`);
  153. check('the month sits right under the field', pos.dx < 2 && pos.dy >= 0 && pos.dy < 12, JSON.stringify(pos));
  154. await ev(`document.querySelector('date-picker input[name=arrival]').__mark = 1`);
  155. await realClick('date-picker date-field:nth-child(1) ol.days li:not(.outside) time[datetime$="-15"]');
  156. const picked = await val(0);
  157. check('the field element is the same one after picking (not re-created)', (await ev(`document.querySelector('date-picker input[name=arrival]').__mark`)) === 1);
  158. check('a picked day is in the field as YYYY-MM-DD', /^\d{4}-\d{2}-15$/.test(picked), picked);
  159. check('the month closes after picking', !(await ev(pop(0))));
  160. // the month arrows page
  161. await realClick('date-picker input[name=departure]');
  162. await page.waitFor(pop(1), { label: 'popup open 2' });
  163. const dt0 = await ev(`document.querySelectorAll('date-picker h2')[1].textContent`);
  164. await realClick('date-picker date-field:nth-child(2) button.next');
  165. check('the next-month arrow changes the month', (await ev(`document.querySelectorAll('date-picker h2')[1].textContent`)) !== dt0);
  166. await realClick('date-picker date-field:nth-child(2) ol.days li:not(.outside) time[datetime$="-20"]');
  167. check('the second field gets its own day, the first keeps its', /^\d{4}-\d{2}-20$/.test(await val(1)) && (await val(0)) === picked, await val(1));
  168. // typing: a date in another month opens on that month and is marked
  169. await typeInto(0, '2028-02-29');
  170. check('typing works: the field holds the typed date', (await val(0)) === '2028-02-29', await val(0));
  171. check('a typed date shows its month and is marked', (await ev(`document.querySelectorAll('date-picker date-field')[0].querySelector('li.selected time').getAttribute('datetime')`)) === '2028-02-29');
  172. await typeInto(0, '2027-02-30');
  173. check('an impossible date marks the field invalid', (await ev(`document.querySelectorAll('date-picker input')[0].getAttribute('aria-invalid')`)) === 'true');
  174. await typeInto(0, '2028-02-29');
  175. await sleep(300); await shot('picker');
  176. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
  177. await sleep(300);
  178. check('Escape closes the month', !(await ev(pop(0))));
  179. await realClick('h1'); await sleep(200);
  180. // the form posts both fields by name
  181. await ev(`document.querySelector('date-picker-demo form button[type=submit]').click()`);
  182. await page.waitFor(`location.search.includes('arrival=2028-02-29')`, { label: 'form posted' });
  183. check('the form posts both fields by name', /arrival=2028-02-29&departure=\d{4}-\d{2}-20/.test(await ev('location.search')), await ev('location.search'));
  184. check('no console errors on the date picker page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  185. // the date range picker: a start click, an end click, both in the field, the days between highlighted
  186. check('home lists the range picker', home.includes('id="open-range-picker"'));
  187. check('range picker README is served', (await fetch(BASE + '/range-picker/README.md')).ok);
  188. await page.goto(BASE + '/range-picker');
  189. await page.waitForSelector('#range-picker-input');
  190. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  191. await sleep(1500);
  192. const rvis = () => ev(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`);
  193. const rval = () => ev(`document.getElementById('range-picker-input').value`);
  194. const day = (n) => ev(`document.querySelector('range-picker ol.days li:not(.outside) time[datetime$="-${n}"]').closest('li').click()`);
  195. check('range: month is closed at first', !(await rvis()));
  196. await page.click('#range-picker-input');
  197. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup open' });
  198. await day('20');
  199. check('range: the first click is the start, the month stays open', /^\d{4}-\d{2}-20 – $/.test(await rval()) && await rvis(), await rval());
  200. await day('10');
  201. const rv = await rval();
  202. check('range: second (earlier) click swaps: start – end in the field', /^\d{4}-\d{2}-10 – \d{4}-\d{2}-20$/.test(rv), rv);
  203. await sleep(500);
  204. check('range: the month closes after the end', !(await rvis()));
  205. await page.click('#range-picker-input');
  206. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup reopen' });
  207. const hl = await ev(`(() => ({ sel: [...document.querySelectorAll('range-picker li.selected time')].map(t => t.textContent), between: [...document.querySelectorAll('range-picker li.between time')].map(t => t.textContent) }))()`);
  208. check('range: start and end marked, the 9 days between highlighted', hl.sel.join() === '10,20' && hl.between.length === 9, JSON.stringify(hl));
  209. await shot('range');
  210. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.focus(); f.value = '2028-02-01 – 2028-02-29'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  211. await page.waitFor(`document.querySelectorAll('range-picker li.between').length === 27`, { label: 'typed range marked' });
  212. check('range: a typed range shows its month, 27 days between', true);
  213. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-30'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  214. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'true'`, { label: 'impossible range marked' });
  215. check('range: an impossible range marks the field invalid', true);
  216. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-29'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  217. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'false'`, { label: 'valid again' });
  218. await ev(`document.querySelector('form button[type=submit]').click()`);
  219. await page.waitFor(`location.search.length > 0`, { label: 'form posted' });
  220. const q = decodeURIComponent(await ev(`location.search`)).replace(/\+/g, ' ');
  221. check('range: the form posts the period by the field name', q.includes('range=2028-02-01 – 2028-02-29'), q);
  222. check('range picker has no .js file', !existsSync(join(APP, 'components/range-picker/range-picker.js')));
  223. check('no console errors on the range picker page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  224. // ticket #4: the one-file upload (pure Hybriel): choose / drop -> name, size, progress -> listed; the app stores it
  225. {
  226. check('home lists the file upload', home.includes('id="open-file-upload"'));
  227. check('file upload README is served', (await fetch(BASE + '/file-upload/README.md')).ok);
  228. check('file upload has no .js file', !existsSync(join(APP, 'components/file-upload/file-upload.js')));
  229. check('no component file uses XMLHttpRequest or fetch(', !execSync(`grep -rlE "XMLHttpRequest|fetch\\(" ${join(APP, 'components')} || true`).toString().trim(), execSync(`grep -rnE "XMLHttpRequest|fetch\\(" ${join(APP, 'components')} || true`).toString());
  230. await page.goto(BASE + '/file-upload');
  231. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  232. await sleep(600);
  233. const FU = (s) => `document.querySelector('file-upload ${s}')`;
  234. const mk = (name, n) => `const dt = new DataTransfer(); dt.items.add(new File([new Uint8Array(${n}).fill(66)], '${name}', { type: 'text/plain' }));`;
  235. await ev(`(() => { window.__max = 0; const bar = ${FU('progress')}; new MutationObserver(() => { if (bar.max > 1) window.__max = Math.max(window.__max, bar.value / bar.max) }).observe(bar, { attributes: true }); ${mk('report.txt', 3145728)} ${FU('drop-zone')}.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true })); })()`);
  236. await page.waitFor(`${FU('.state')}.textContent === 'Uploaded'`, { timeout: 30000, label: 'uploaded' });
  237. check('upload: name and size shown', (await ev(FU('.name') + '.textContent')) === 'report.txt' && (await ev(FU('.size') + '.textContent')) === '3.0 MB');
  238. check('upload: progress bar reaches 100%', (await ev(FU('progress') + '.value')) === 100 && (await ev('window.__max')) >= 1);
  239. check('upload: listed under Uploaded', (await ev(FU('ul.uploaded li') + '.textContent')) === 'report.txt — 3.0 MB');
  240. const stored = execSync(`ls -l ${join(APP, 'storage/uploads')} | grep -c ' 3145728 '`).toString().trim();
  241. check('upload: the app stored all bytes', Number(stored) >= 1, stored);
  242. // choosing a second file (input) adds a second row
  243. const { root } = await page.send('DOM.getDocument');
  244. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'file-upload input[type=file]' });
  245. writeFileSync(join(SCRATCH, 'pick.txt'), 'hello');
  246. await page.send('DOM.setFileInputFiles', { files: [join(SCRATCH, 'pick.txt')], nodeId });
  247. await page.waitFor(`document.querySelectorAll('file-upload ul.uploaded li').length === 2`, { timeout: 30000, label: 'chosen file listed' });
  248. check('choose: second file shown and listed', (await ev(FU('.name') + '.textContent')) === 'pick.txt' && (await ev(FU('ul.uploaded li:nth-child(2)') + '.textContent')) === 'pick.txt — 5 B');
  249. check('upload: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  250. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  251. await sleep(300); await shot('file-upload-narrow');
  252. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  253. await sleep(200); await shot('file-upload');
  254. }
  255. // ticket #5 (mission 005): the upload for several files, pure Hybriel (emit server uploadFile per file, hybriel#94): REAL drops of files
  256. // from disk (Chrome's drag and drop, Input.dispatchDragEvent), the multiple file input, a row per file with live progress, one file at a
  257. // time in order, a file over uploadMax fails in its own row, a drop during an upload waits and follows. Uploads throttled to 2 MiB/s so
  258. // the waiting is seen. Screenshots .scratch/gate-files-upload-{1280,390}.png.
  259. {
  260. check('home lists the upload for several files', home.includes('id="open-files-upload"'));
  261. check('files upload README is served', (await fetch(BASE + '/files-upload/README.md')).ok);
  262. check('files upload has no .js file', existsSync(join(APP, 'components/files-upload/files-upload.hl')) && !execSync(`find ${join(APP, 'components/files-upload')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  263. const FD = join(SCRATCH, 'gate-files');
  264. mkdirSync(FD, { recursive: true });
  265. for (const [n, size, byte] of [['photo.jpg', 3145728, 66], ['notes.txt', 1200, 110], ['slides.pdf', 204800, 7], ['a.txt', 5, 97], ['b.txt', 2048, 98], ['huge.bin', 6291456, 1], ['big.bin', 4194304, 2], ['late.txt', 40, 108]]) writeFileSync(join(FD, n), Buffer.alloc(size, byte));
  266. const F = (n) => join(FD, n);
  267. // its own tab: the over-limit file's expected 413 stays out of the main tab's console checks
  268. const page = await browser.newPage();
  269. const ev = (e) => page.evaluate(e);
  270. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  271. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  272. await page.goto(BASE + '/files-upload');
  273. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  274. await sleep(600);
  275. const rows = () => ev(`[...document.querySelectorAll('files-upload ul.files li')].map(li => [li.querySelector('.name').textContent, li.querySelector('.size').textContent, li.querySelector('.state').textContent, li.querySelector('progress').value / li.querySelector('progress').max].join('|'))`);
  276. const summary = () => ev(`(document.querySelector('files-upload output.summary') || {}).textContent`);
  277. // a REAL drop of files (Chrome's own drag and drop through the Input domain, files from disk)
  278. const dropFiles = async (names) => {
  279. const b = await page.box('files-upload drop-zone');
  280. if (!b) return;
  281. const data = { items: [], files: names.map(F), dragOperationsMask: 1 };
  282. for (const type of ['dragEnter', 'dragOver', 'drop']) await page.send('Input.dispatchDragEvent', { type, x: Math.round(b.x), y: Math.round(b.y), data });
  283. };
  284. await page.send('Network.enable');
  285. const slow = (on) => page.send('Network.emulateNetworkConditions', { offline: false, latency: on ? 20 : 0, downloadThroughput: -1, uploadThroughput: on ? 2 * 1024 * 1024 : -1 });
  286. await slow(true);
  287. await ev(`(() => { window.__snaps = []; new MutationObserver(() => { const s = [...document.querySelectorAll('files-upload ul.files li')].map(li => li.querySelector('.name').textContent + '=' + li.querySelector('.state').textContent).join(','); if (window.__snaps[window.__snaps.length - 1] !== s) window.__snaps.push(s); }).observe(document.querySelector('files-upload ul.files') || document.createElement('i'), { characterData: true, subtree: true, childList: true }); })()`);
  288. await ev(`(() => { window.__fr = []; new MutationObserver(() => { for (const li of document.querySelectorAll('files-upload li.busy')) { const p = li.querySelector('progress'); if (p.max > 1) window.__fr.push(li.querySelector('.name').textContent + ':' + (p.value / p.max).toFixed(2)); } }).observe(document.querySelector('files-upload ul.files') || document.createElement('i'), { attributes: true, subtree: true, childList: true }); })()`);
  289. await dropFiles(['photo.jpg', 'notes.txt', 'slides.pdf']);
  290. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 3`, { timeout: 10000, label: 'three rows' }).catch(() => {});
  291. const r0 = await rows();
  292. check('#5: a drop of three files makes three rows (name, size, progress) in drop order', r0.length === 3 && r0[0].startsWith('photo.jpg|3.0 MB|') && r0[1].startsWith('notes.txt|1.2 KB|') && r0[2].startsWith('slides.pdf|200.0 KB|'), JSON.stringify(r0));
  293. check('#5: while the first is sent, the others wait', (r0[0] || '').split('|')[2] === 'Uploading…' && (r0[1] || '').split('|')[2] === 'Waiting' && (r0[2] || '').split('|')[2] === 'Waiting', JSON.stringify(r0));
  294. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 3`, { timeout: 60000, label: 'three uploaded' }).catch(() => {});
  295. const r1 = await rows();
  296. const sn = await ev('window.__snaps');
  297. check('#5: one file at a time, in order: never two rows Uploading, a row starts only after the one before ended', sn.every(x => (x.match(/=Uploading…/g) || []).length <= 1) && sn.every(x => !/=(Waiting)[^]*=(Uploading…|Uploaded)/.test(x)), JSON.stringify(sn));
  298. check('#5: all three end Uploaded with a full bar', r1.length === 3 && r1.every(r => r.endsWith('|Uploaded|1')), JSON.stringify(r1));
  299. check('#5: the line under them says 3 of 3 uploaded', (await summary()) === '3 of 3 uploaded', await summary());
  300. const sizes = execSync(`ls -l ${join(APP, 'storage/uploads')}`).toString();
  301. check('#5: the app stored all bytes of the three files (3145728, 1200, 204800)', [3145728, 1200, 204800].every(n => new RegExp(' ' + n + ' ').test(sizes)), sizes);
  302. const fr = await ev('window.__fr');
  303. check('#5: the 3 MB file showed live progress (a part between 0 and 100 %)', fr.some(x => /^photo\.jpg:0\.(?!00)\d\d$/.test(x)), JSON.stringify(fr.slice(0, 20)));
  304. check('#5: the progress of one file never shows on another row', !fr.some(x => /^notes|^slides/.test(x) && Number(x.split(':')[1]) > 1), JSON.stringify(fr));
  305. // choosing several files (the input takes more than one)
  306. const { root } = await page.send('DOM.getDocument');
  307. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload input[type=file]' });
  308. check('#5: the file input takes several files', await ev(`!!document.querySelector('files-upload input[type=file]') && document.querySelector('files-upload input[type=file]').multiple === true`));
  309. try { await page.send('DOM.setFileInputFiles', { files: [F('a.txt'), F('b.txt')], nodeId }); } catch {}
  310. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 5`, { timeout: 30000, label: 'five uploaded' }).catch(() => {});
  311. const r2 = await rows();
  312. check('#5: choosing two more adds two rows, both Uploaded: 5 of 5', r2.length === 5 && r2[3] === 'a.txt|5 B|Uploaded|1' && r2[4] === 'b.txt|2.0 KB|Uploaded|1' && (await summary()) === '5 of 5 uploaded', JSON.stringify([r2, await summary()]));
  313. // a file over the app's limit fails in its own row; the next file still goes
  314. await dropFiles(['huge.bin', 'a.txt']);
  315. await page.waitFor(`document.querySelectorAll('files-upload li.done, files-upload li.failed').length === 7`, { timeout: 60000, label: 'seven ended' }).catch(() => {});
  316. const r3 = await rows();
  317. check('#5: a file over uploadMax shows Failed, the next one still uploads; 6 of 7 uploaded, 1 failed', (r3[5] || '').startsWith('huge.bin|6.0 MB|Failed') && r3[6] === 'a.txt|5 B|Uploaded|1' && (await summary()) === '6 of 7 uploaded, 1 failed', JSON.stringify([r3, await summary()]));
  318. // a drop during an upload waits in its row and follows
  319. await dropFiles(['big.bin']);
  320. await page.waitFor(`!!document.querySelector('files-upload li.busy')`, { timeout: 10000, label: 'big busy' }).catch(() => {});
  321. await dropFiles(['late.txt']);
  322. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 9`, { timeout: 10000, label: 'late row' }).catch(() => {});
  323. const r4 = await rows();
  324. check('#5: a file dropped during an upload waits (its row says Waiting)', (r4[7] || '').startsWith('big.bin|4.0 MB|Uploading') && (r4[8] || '').startsWith('late.txt|40 B|Waiting'), JSON.stringify(r4.slice(7)));
  325. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 8`, { timeout: 60000, label: 'all ended' }).catch(() => {});
  326. const r5 = await rows();
  327. check('#5: ...and follows: both Uploaded, 8 of 9 uploaded, 1 failed', r5[7] === 'big.bin|4.0 MB|Uploaded|1' && r5[8] === 'late.txt|40 B|Uploaded|1' && (await summary()) === '8 of 9 uploaded, 1 failed', JSON.stringify([r5.slice(7), await summary()]));
  328. await slow(false);
  329. await page.send('Network.disable');
  330. check('#5: no console errors (but the over-limit file\'s 413 and hl:web\'s note that it refused it)', page.problems().filter(m => !/favicon|status of 413 \(Payload Too Large\)|the upload of huge\.bin was refused/.test(m.text)).length === 0, page.dumpConsole());
  331. await ev('scrollTo(0, 0)'); await sleep(200); await shot('files-upload-1280');
  332. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  333. await ev('scrollTo(0, 0)'); await sleep(300); await shot('files-upload-390');
  334. await page.close();
  335. }
  336. // ==== #18 START — ticket #18 (mission 008): FilesUpload PICK FIRST, SEND LATER (for HyperConductor's chat attachments, hycon#46), pure
  337. // Hybriel. The demo `/files-upload/pick` is a chat input: the page owns the list (`files = attached`, `onChange`), the text field + Send
  338. // sit inside the component. REAL input only: Chrome's own drag and drop of files from disk, the file input (DOM.setFileInputFiles), a
  339. // real Ctrl+V (an image put on Chrome's clipboard, then the key press with the paste command), real clicks on ✕ and Send, real typing.
  340. // Checked: nothing is uploaded while picking; thumbnails drawn (naturalWidth > 0), other files as name + size + kind; a file over maxSize
  341. // refused in its own row; ✕ removes; Send gives text + every byte of the files to the page's face, then the list is empty; a text paste
  342. // stays text; the upload-at-once mode takes a paste too and its button is 44 px now; 390 px phone (touch): every target ≥ 44 × 44,
  343. // the Camera button (accept image/*, capture), no horizontal overflow. Screenshots .scratch/gate-files-pick-{1280,390}.png.
  344. {
  345. const crc = (buf) => { let c, t = []; for (let n = 0; n < 256; n++) { c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } let x = 0xffffffff; for (const b of buf) x = t[(x ^ b) & 0xff] ^ (x >>> 8); return (x ^ 0xffffffff) >>> 0; };
  346. const png = (w, h, rgb) => {
  347. const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  348. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  349. const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([(rgb[0] + x) & 255, (rgb[1] + y) & 255, rgb[2]], y * (w * 3 + 1) + 1 + x * 3);
  350. return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  351. };
  352. const PD = join(SCRATCH, 'gate-pick');
  353. mkdirSync(PD, { recursive: true });
  354. writeFileSync(join(PD, 'photo.png'), png(320, 200, [180, 40, 40]));
  355. writeFileSync(join(PD, 'notes.txt'), Buffer.alloc(1200, 110));
  356. writeFileSync(join(PD, 'a.txt'), 'hello');
  357. writeFileSync(join(PD, 'huge.bin'), Buffer.alloc(3 * 1048576, 1));
  358. const longName = 'a-very-long-file-name-without-any-break-that-a-phone-must-wrap-somewhere-2026-10-20.txt';
  359. writeFileSync(join(PD, longName), 'x'.repeat(300));
  360. const P = (n) => join(PD, n);
  361. const sizeOf = (n) => readFileSync(P(n)).length;
  362. check('#18: the home links the pick-first demo', home.includes('id="open-files-upload-pick"') && home.includes('href="/files-upload/pick"'));
  363. const page = await browser.newPage();
  364. const ev = (e) => page.evaluate(e);
  365. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  366. // null-safe reads and actions: on the old code the elements are missing, every check must FAIL, not end the gate
  367. const val = (sel, prop) => ev(`(document.querySelector(${JSON.stringify(sel)}) || {})[${JSON.stringify(prop)}]`);
  368. const tryDo = async (f) => { try { await f(); } catch {} };
  369. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  370. await browser.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  371. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  372. await page.goto(BASE + '/files-upload/pick');
  373. await hydrated();
  374. await sleep(600);
  375. const prows = () => ev(`[...document.querySelectorAll('files-upload ul.files li.picked')].map(li => [li.querySelector('.name').textContent, li.querySelector('.size').textContent, li.querySelector('img.thumb') ? 'img:' + li.querySelector('img.thumb').naturalWidth : 'kind:' + (li.querySelector('.kind') || {}).textContent].join('|'))`);
  376. const refusedRows = () => ev(`[...document.querySelectorAll('files-upload ul.files li.refused')].map(li => li.querySelector('.name').textContent + '|' + li.querySelector('.state').textContent)`);
  377. const uploadsSeen = () => ev(`performance.getEntriesByType('resource').filter(r => r.name.includes('/__hl/upload')).length`);
  378. const storedCount = () => existsSync(join(APP, 'storage/uploads')) ? execSync(`ls ${join(APP, 'storage/uploads')} | wc -l`).toString().trim() : '0';
  379. const stored0 = storedCount();
  380. const dropOn = async (sel, names) => {
  381. const b = await page.box(sel);
  382. if (!b) return;
  383. const data = { items: [], files: names.map(P), dragOperationsMask: 1 };
  384. for (const type of ['dragEnter', 'dragOver', 'drop']) await page.send('Input.dispatchDragEvent', { type, x: Math.round(b.x), y: Math.round(b.y), data });
  385. };
  386. // pick mode is one box (ux-tickets): there is no drop zone any more, the whole box takes the drop and holds the Choose files button
  387. check('#18: pick mode is one box: no drop zone, the Choose files button and the host\'s field and Send sit inside the box', await ev(`(() => { const b = document.querySelector('files-upload pick-area'); return !!b && !document.querySelector('files-upload drop-zone') && !!b.querySelector('label.choose input[type=file]') && !!b.querySelector('#chat-text') && !!b.querySelector('#chat-send'); })()`));
  388. // a real drop: anywhere in the box (here on its middle)
  389. await dropOn('files-upload pick-area', ['photo.png', 'notes.txt']);
  390. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 2 && [...document.querySelectorAll('files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'two picked' }).catch(() => {});
  391. const q1 = await prows();
  392. check('#18: a real drop of an image and a text file makes two rows: the image as a drawn thumbnail (320 px wide), the other as name + size + kind', q1.length === 2 && q1[0] === 'photo.png|' + (sizeOf('photo.png') < 1024 ? sizeOf('photo.png') + ' B' : (sizeOf('photo.png') / 1024).toFixed(1) + ' KB') + '|img:320' && q1[1] === 'notes.txt|1.2 KB|kind:TXT', JSON.stringify(q1));
  393. check('#18: the page holds the list it was told (summary "2 files · …")', /^2 files · /.test(await val('files-upload output.summary', 'textContent')), await val('files-upload output.summary', 'textContent'));
  394. // choose: the "Choose files" input (several at once)
  395. {
  396. const { root } = await page.send('DOM.getDocument');
  397. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload label.choose input[type=file]' });
  398. try { await page.send('DOM.setFileInputFiles', { files: [P('a.txt')], nodeId }); } catch {}
  399. }
  400. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 3`, { timeout: 10000, label: 'three picked' }).catch(() => {});
  401. const q2 = await prows();
  402. check('#18: choosing a file adds its row after the others', q2.length === 3 && q2[2] === 'a.txt|5 B|kind:TXT', JSON.stringify(q2));
  403. // a REAL Ctrl+V of an image: Chrome's clipboard holds a PNG, the text field has the focus, the key press runs the paste command
  404. await page.send('Page.bringToFront');
  405. await tryDo(() => page.focus('#chat-text'));
  406. const putImage = await ev(`(async () => { try { const c = document.createElement('canvas'); c.width = 120; c.height = 60; const x = c.getContext('2d'); x.fillStyle = '#333'; x.fillRect(0, 0, 120, 60); x.fillStyle = '#ccc'; x.fillRect(10, 10, 40, 20); const b = await new Promise(r => c.toBlob(r, 'image/png')); await navigator.clipboard.write([new ClipboardItem({ 'image/png': b })]); return 'ok'; } catch (e) { return 'ERR ' + e.message; } })()`);
  407. const ctrlV = async () => {
  408. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  409. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  410. };
  411. await ctrlV();
  412. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 4 && [...document.querySelectorAll('files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'pasted' }).catch(() => {});
  413. const q3 = await prows();
  414. check('#18: a real Ctrl+V of an image in the host\'s text field adds it with a drawn thumbnail (120 px), the field stays empty', putImage === 'ok' && q3.length === 4 && /^image\.png\|\d+ B\|img:120$/.test(q3[3]) && (await val('#chat-text', 'value')) === '', putImage + ' ' + JSON.stringify(q3));
  415. // a text paste is left to the field
  416. await ev(`navigator.clipboard.writeText('pasted words')`);
  417. await ctrlV();
  418. await sleep(500);
  419. check('#18: a Ctrl+V of text goes into the field as text, no row', (await val('#chat-text', 'value')) === 'pasted words' && (await ev(`document.querySelectorAll('files-upload li.picked').length`)) === 4, await val('#chat-text', 'value'));
  420. // a file over the page's maxSize (2 MB): refused in its own row, not collected; a drop on the text field is caught too
  421. await dropOn('#chat-text', ['huge.bin']);
  422. await page.waitFor(`document.querySelectorAll('files-upload li.refused').length === 1`, { timeout: 10000, label: 'refused' }).catch(() => {});
  423. check('#18: a 3 MB file dropped on the text field is refused in its row ("Too big — at most 2.0 MB") and not collected', JSON.stringify(await refusedRows()) === JSON.stringify(['huge.bin|Too big — at most 2.0 MB']) && (await ev(`document.querySelectorAll('files-upload li.picked').length`)) === 4 && /^4 files · /.test(await val('files-upload output.summary', 'textContent')), JSON.stringify([await refusedRows(), await prows()]));
  424. check('#18: picking sent nothing: four files collected, no request to /__hl/upload, nothing stored', (await prows()).length === 4 && (await uploadsSeen()) === 0 && storedCount() === stored0, `${await uploadsSeen()} uploads, stored ${stored0} → ${storedCount()}`);
  425. // ✕ removes one (a real click), the thumbnails stay drawn
  426. await tryDo(() => page.click('files-upload li.picked[data-i="1"] button.remove', { timeout: 3000 }));
  427. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 3`, { timeout: 10000, label: 'removed' }).catch(() => {});
  428. await sleep(400);
  429. const q4 = await prows();
  430. check('#18: ✕ removes that file (notes.txt); the others stay, thumbnails still drawn', q4.length === 3 && q4[0].startsWith('photo.png|') && q4[0].endsWith('|img:320') && q4[1] === 'a.txt|5 B|kind:TXT' && /^image\.png\|.*\|img:120$/.test(q4[2]), JSON.stringify(q4));
  431. check('#18: the ✕ says what it removes (aria-label "Remove photo.png")', (await ev(`(document.querySelector('files-upload li.picked button.remove') || { getAttribute: () => null }).getAttribute('aria-label')`)) === 'Remove photo.png');
  432. await shot('files-pick-1280');
  433. // Send: real typing, a real click; the page's face gets the text and every byte, the list is emptied
  434. await tryDo(() => page.type('#chat-text', ' and three files', {}));
  435. const stored1 = Number(storedCount());
  436. await tryDo(() => page.click('#chat-send', { timeout: 3000 }));
  437. await page.waitFor(`document.querySelectorAll('#sent li').length === 1`, { timeout: 30000, label: 'sent' }).catch(() => {});
  438. const pastedSize = Number(((q4[2] || '').match(/\|(\d+) B\|/) || [])[1]); // the pasted File's size (Chrome's clipboard encodes its own PNG)
  439. const sentFiles = await ev(`(document.querySelector('#sent li .sent-files') || {}).textContent`);
  440. check('#18: Send hands the page text + files; its face got every byte (photo.png, a.txt, image.png)', (await ev(`(document.querySelector('#sent li .sent-text') || {}).textContent`)) === 'pasted words and three files'
  441. && sentFiles === `photo.png (${sizeOf('photo.png')} B), a.txt (5 B), image.png (${pastedSize} B)` && Number(storedCount()) === stored1 + 3, sentFiles + ' stored ' + storedCount());
  442. check('#18: after Send the page emptied the list: no rows, no refused row, no summary, the field empty', (await ev(`document.querySelectorAll('files-upload ul.files li').length`)) === 0 && (await val('files-upload output.summary', 'textContent')) === '' && (await val('#chat-text', 'value')) === '');
  443. // the 390 px phone, touch: targets, the camera, no overflow (with a long file name and a refused row)
  444. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  445. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  446. await page.goto(BASE + '/files-upload/pick');
  447. await hydrated();
  448. await sleep(600);
  449. {
  450. const { root } = await page.send('DOM.getDocument');
  451. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload label.choose input[type=file]' });
  452. try { await page.send('DOM.setFileInputFiles', { files: [P('photo.png'), P(longName), P('huge.bin')], nodeId }); } catch {}
  453. }
  454. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 2 && document.querySelectorAll('files-upload li.refused').length === 1 && [...document.querySelectorAll('files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'phone picked' }).catch(() => {});
  455. const targets = await ev(`[...document.querySelectorAll('files-upload button, files-upload label.choose, files-upload label.camera, #chat-send')].map(el => { const r = el.getBoundingClientRect(); return (el.className || el.id) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);
  456. check('#18 390px: every target is at least 44 × 44 px (✕ of each row, Choose files, Camera, Send)', targets.length === 6 && targets.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), JSON.stringify(targets));
  457. check('#18 390px: on a touch screen the Camera button shows: an image input with capture; Choose files takes several', await ev(`(() => { const c = document.querySelector('files-upload label.camera'); const i = c && c.querySelector('input'); const m = document.querySelector('files-upload label.choose input'); return !!c && !!m && getComputedStyle(c).display !== 'none' && i.accept === 'image/*' && i.getAttribute('capture') === 'environment' && m.multiple === true; })()`));
  458. check('#18 390px: no horizontal overflow (a long file name wraps, the refused row fits)', await ev(`document.querySelectorAll('files-upload li').length === 3 && document.documentElement.scrollWidth <= window.innerWidth && [...document.querySelectorAll('files-upload li')].every(li => li.getBoundingClientRect().right <= window.innerWidth)`), await ev(`document.documentElement.scrollWidth + ' > ' + window.innerWidth`));
  459. await shot('files-pick-390');
  460. // the upload-at-once mode (the page /files-upload) at 390: its Choose files button is a 44 px target too, and it takes a pasted image
  461. await page.goto(BASE + '/files-upload');
  462. await hydrated();
  463. await sleep(600);
  464. const ub = await ev(`(() => { const e = document.querySelector('files-upload label.choose'); if (!e) return [0, 0]; const r = e.getBoundingClientRect(); return [Math.round(r.width), Math.round(r.height)]; })()`);
  465. check('#18 390px: the upload-at-once Choose files button is at least 44 × 44 px', ub[0] >= 44 && ub[1] >= 44, JSON.stringify(ub));
  466. check('#18: the upload-at-once mode shows no Camera button and no pick rows', await ev(`!document.querySelector('files-upload label.camera') && !document.querySelector('files-upload pick-area')`));
  467. await page.send('Page.bringToFront');
  468. await tryDo(() => page.focus('files-upload drop-zone'));
  469. await ev(`(async () => { const c = document.createElement('canvas'); c.width = 30; c.height = 30; const b = await new Promise(r => c.toBlob(r, 'image/png')); await navigator.clipboard.write([new ClipboardItem({ 'image/png': b })]); })()`);
  470. await ctrlV();
  471. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 1`, { timeout: 20000, label: 'pasted upload' }).catch(() => {});
  472. check('#18: the upload-at-once mode uploads a pasted image at once (Ctrl+V on the focused drop zone): 1 of 1 uploaded', (await val('files-upload output.summary', 'textContent')) === '1 of 1 uploaded' && (await val('files-upload li .name', 'textContent')) === 'image.png');
  473. check('#18: no console errors', page.problems().filter(m => !/favicon/.test(m.text)).length === 0, page.dumpConsole());
  474. await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  475. await page.close();
  476. }
  477. // ==== #18 END
  478. // layouts#2 (mission 006): THE COMMENTS BLOCK, pure Hybriel — the host passes the list + the current user and hears post / edit /
  479. // delete / like through the four functions it hands (hybriel#87); the demo's page makes a new list each time (lib/comments.hl).
  480. // REAL clicks and keys only: a comment typed into the Markdown editor and posted (button and Ctrl+Enter), an edit typed and saved
  481. // shows "edited" + the earlier version, Edit / Delete only on the user's own comments (alice, bob, nobody), Delete asks first,
  482. // the like toggles and counts, "1 comment" / "n comments". Own tab. Screenshots .scratch/gate-comments-{1280,390}.png.
  483. {
  484. check('home lists the comments block', home.includes('id="open-comments"'));
  485. check('comments README is served', (await fetch(BASE + '/comments/README.md')).ok);
  486. check('comments has no .js file', existsSync(join(APP, 'components/comments/comments.hl')) && !execSync(`find ${join(APP, 'components/comments')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  487. const ssr = await (await fetch(BASE + '/comments')).text();
  488. check('comments: the server renders the counter and the three comments', ssr.includes('<h2 class="comments-count">3 comments</h2>') && (ssr.match(/<li class="comment" data-id=/g) || []).length === 3);
  489. const page = await browser.newPage();
  490. const ev = (e) => page.evaluate(e);
  491. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  492. const key = async (k, code, vk, text, modifiers = 0) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, text, modifiers }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, modifiers }); await sleep(15); };
  493. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  494. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  495. await page.goto(BASE + '/comments');
  496. // MD1: the server-rendered comments hold MdEditors. The moment the page is claimed (the surface has its listeners) every editor must
  497. // already show its text: measured on 5 fresh loads, the longest wait from the claim to the text is at most 30 ms (the old 100 ms
  498. // animation made it up to 100 ms, an empty editor on screen). No wait for mdMounted.
  499. {
  500. const p2 = await browser.newPage();
  501. const waits = [];
  502. try {
  503. for (let run = 0; run < 5; run++) {
  504. p2.send('Page.navigate', { url: BASE + '/comments?md1=' + run });
  505. let claimedAt = 0, textAt = 0;
  506. for (const t0 = Date.now(); Date.now() - t0 < 10000; ) {
  507. try {
  508. const r = await p2.send('Runtime.evaluate', { expression: "document.querySelector('md-editor[data-readonly=\"true\"] article')" });
  509. if (!r.result || r.result.subtype !== 'node') { await sleep(2); continue; }
  510. const l = await p2.send('DOMDebugger.getEventListeners', { objectId: r.result.objectId });
  511. if (!claimedAt && l.listeners.length) claimedAt = Date.now();
  512. const tx = await p2.send('Runtime.evaluate', { expression: "(() => { const a = [...document.querySelectorAll('md-editor[data-readonly=\"true\"] article')]; return a.length === 3 && a.every(x => x.textContent.trim().length > 0); })()", returnByValue: true });
  513. if (tx.result.value) { textAt = Date.now(); break; }
  514. } catch { /* the page is still navigating: its old context is gone */ }
  515. await sleep(1);
  516. }
  517. waits.push(claimedAt && textAt ? textAt - claimedAt : 9999);
  518. }
  519. } finally { try { await p2.close(); } catch {} }
  520. check('MD1: from the claim of server HTML until its text is drawn, every comment editor waits at most 30 ms (5 loads)', Math.max(...waits) <= 30, JSON.stringify(waits));
  521. }
  522. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  523. const R = (id) => `document.querySelector('comments-block li.comment[data-id="${id}"]')`;
  524. const art = (id) => ev(`(() => { const li = ${R(id)}; const a = li && li.querySelector('md-editor[data-readonly="true"] article'); return a ? a.innerHTML : null; })()`);
  525. const btns = (id) => ev(`[...${R(id)}.querySelectorAll('comment-actions button')].map(b => b.textContent).join('|')`);
  526. const ids = () => ev(`[...document.querySelectorAll('comments-block li.comment')].map(li => li.dataset.id).join(',')`);
  527. const count = () => ev(`document.querySelector('comments-block .comments-count').textContent`);
  528. const told = () => ev(`document.querySelector('#comments-told').textContent`);
  529. const newValue = () => ev(`(document.querySelector('comments-block form.comment-form md-editor input.value') || {}).value`);
  530. await page.waitFor(`!!${R('c1')}.querySelector('md-editor article ul')`, { label: 'comment Markdown drawn' }).catch(() => {});
  531. check('comments: each text shows as formatted Markdown (bold, italic, code, link, list) by MdEditor readonly',
  532. (await art('c1')) === '<p>The block takes <strong>Markdown</strong>: <em>emphasis</em>, <code>code</code>, links like <a href="/comments/README.md">the README</a> and lists:</p><ul><li>one</li><li>two</li></ul>', await art('c1'));
  533. check('comments: a shown text is not editable, and shows no toolbar, no source switch',
  534. await ev(`(() => { const m = ${R('c1')}.querySelector('md-editor'); return m.querySelector('article').isContentEditable === false && getComputedStyle(m.querySelector('nav')).display === 'none' && getComputedStyle(m.querySelector('footer')).display === 'none' && m.querySelector('article').tabIndex === -1; })()`));
  535. check('comments: avatar initial, name, time in each bubble', await ev(`(() => { const li = ${R('c2')}; return li.querySelector('comment-avatar').textContent === 'B' && li.querySelector('.comment-author').textContent === 'bob' && li.querySelector('time').textContent === 'Oct 17, 10:40'; })()`));
  536. // POST, typed in the Markdown editor with real keys: **x** and `x` format while typing; the Comment button sends it
  537. await page.click('comments-block form.comment-form md-editor article');
  538. await typeText('Hello **world** and `code` here'); await sleep(200);
  539. check('comments: the form is the Markdown editor — typed **x** / `x` format while typing', /<strong>world<\/strong>/.test(await ev(`document.querySelector('comments-block form.comment-form article').innerHTML`)) && (await newValue()) === 'Hello **world** and `code` here', await newValue());
  540. await page.click('comments-block button.comment-post');
  541. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 4 && !!${R('n1')}.querySelector('md-editor article p')`, { label: 'posted' }).catch(() => {});
  542. await sleep(300);
  543. check('comments: post — the host is told, the new comment is last, by the user, its text formatted', (await told()) === 'post' && (await ids()) === 'c1,c2,c3,n1'
  544. && (await ev(`${R('n1')}.querySelector('.comment-author').textContent`)) === 'alice' && (await art('n1')) === '<p>Hello <strong>world</strong> and <code>code</code> here</p>', [await told(), await ids(), await art('n1')].join(' / '));
  545. check('comments: counter "4 comments"; the form starts empty again', (await count()) === '4 comments' && (await newValue()) === '' && (await ev(`document.querySelector('comments-block form.comment-form article').textContent`)) === '', [await count(), JSON.stringify(await newValue())].join(' '));
  546. // Ctrl+Enter in the editor sends it too
  547. await page.click('comments-block form.comment-form md-editor article');
  548. await typeText('Second, by keyboard'); await key('Enter', 'Enter', 13, '\r', 2);
  549. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 5 && !!${R('n2')}.querySelector('md-editor article p')`, { label: 'posted by Ctrl+Enter' }).catch(() => {});
  550. check('comments: Ctrl+Enter in the editor posts too', (await ids()) === 'c1,c2,c3,n1,n2' && (await art('n2')) === '<p>Second, by keyboard</p>' && (await count()) === '5 comments', (await ids()) + ' ' + (await art('n2')));
  551. // an empty editor sends nothing
  552. await page.click('comments-block button.comment-post'); await sleep(400);
  553. check('comments: an empty form sends nothing', (await ids()) === 'c1,c2,c3,n1,n2');
  554. // LIKE: toggles and counts
  555. check('comments: like shows the count, pressed when the user likes it', (await ev(`${R('c1')}.querySelector('.comment-like').textContent`)) === '♡ 2' && (await ev(`${R('c2')}.querySelector('.comment-like').getAttribute('aria-pressed')`)) === 'true');
  556. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`);
  557. await page.waitFor(`${R('c1')}.querySelector('.comment-like').textContent === '♥ 3' && document.querySelector('#comments-told').textContent === 'like c1'`, { label: 'liked' }).catch(() => {});
  558. await sleep(300);
  559. check('comments: like — ♥ 3, pressed, the host told "like c1"', (await ev(`${R('c1')}.querySelector('.comment-like').textContent`)) === '♥ 3' && (await ev(`${R('c1')}.querySelector('.comment-like').getAttribute('aria-pressed')`)) === 'true' && (await told()) === 'like c1', [await ev(`${R('c1')}.querySelector('.comment-like').outerHTML`), await told(), await ev(`${R('c2')}.querySelector('.comment-like').textContent`)].join(' / '));
  560. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`);
  561. await page.waitFor(`${R('c1')}.querySelector('.comment-like').textContent === '♡ 2'`, { label: 'unliked' }).catch(() => {});
  562. await sleep(300);
  563. check('comments: like again — back to ♡ 2, not pressed', (await ev(`${R('c1')}.querySelector('.comment-like').textContent`)) === '♡ 2' && (await ev(`${R('c1')}.querySelector('.comment-like').getAttribute('aria-pressed')`)) === 'false', [await ev(`${R('c1')}.querySelector('.comment-like').outerHTML`), await told(), await ev(`${R('c2')}.querySelector('.comment-like').textContent`)].join(' / '));
  564. // a text changed from outside (in an app: a push after another user's edit) is drawn anew, nothing pressed in the block
  565. // F5 (hybriel#211): the push builds the row anew; a new editor holds its text before the first frame it is in, never an empty surface for 100 ms+
  566. await ev(`(() => { window.__emptyRows = []; window.__newRows = 0; new MutationObserver((rs) => { for (const r of rs) for (const n of r.addedNodes) { if (n.nodeType !== 1) continue; const ms = n.matches('md-editor[data-readonly="true"]') ? [n] : [...n.querySelectorAll('md-editor[data-readonly="true"]')]; for (const m of ms) { window.__newRows++; requestAnimationFrame(() => { if (m.getAttribute('data-value') && !m.querySelector('article').innerHTML) window.__emptyRows.push(m.getAttribute('data-value')); }); } } }).observe(document.body, { childList: true, subtree: true }); })()`);
  567. await page.click('#elsewhere');
  568. await page.waitFor(`window.__newRows >= 1 && /Edited 3 times/.test(${R('c2')}.textContent) && /elsewhere/.test(${R('c2')}.querySelector('md-editor[data-readonly="true"] article').innerHTML)`, { label: 'pushed edit' }).catch(() => {});
  569. check('comments: the push builds a new editor, and it is never empty in a frame (hybriel#211)', (await ev(`window.__newRows`)) > 0 && (await ev(`window.__emptyRows.length`)) === 0, JSON.stringify(await ev(`[window.__newRows, window.__emptyRows]`)));
  570. check('comments: a text changed by the host from outside (a push) is drawn anew, "Edited 3 times"', (await art('c2')) === '<p>Changed <strong>elsewhere</strong>: bob edited it in another tab.</p>' && (await ev(`${R('c2')}.querySelector('.comment-history-title').textContent`)) === 'Edited 3 times', await art('c2'));
  571. // a surface the framework puts anew under a built editor is drawn at once, not left empty (hybriel#211, forced)
  572. check('comments: a surface replaced under a built editor is drawn again from its value', await (async () => {
  573. const before = await art('c3');
  574. await ev(`(() => { const m = ${R('c3')}.querySelector('md-editor[data-readonly="true"]'); m.querySelector('article').replaceWith(document.createElement('article')); })()`);
  575. await sleep(400);
  576. return !!before && (await art('c3')) === before;
  577. })(), await art('c3'));
  578. // EDIT: the editor opens with the text, typed keys, Save → the new text, "edited" with the earlier version
  579. check('comments: "edited" only on an edited comment', (await ev(`!!${R('c2')}.querySelector('details.comment-history')`)) && !(await ev(`!!${R('c3')}.querySelector('details.comment-history')`)));
  580. await page.click(`comments-block li.comment[data-id="c3"] .comment-edit-start`);
  581. await page.waitFor(`!!${R('c3')}.querySelector('form.comment-edit article p')`, { label: 'edit form' }).catch(() => {});
  582. check('comments: Edit opens the Markdown editor with the comment\'s text', (await ev(`${R('c3')}.querySelector('form.comment-edit input.value').value`)).startsWith('A long word wraps') && (await ev(`${R('c3')}.querySelector('form.comment-edit article').isContentEditable`)));
  583. await page.click(`comments-block li.comment[data-id="c3"] form.comment-edit article`);
  584. await key('End', 'End', 35, undefined, 2);
  585. await typeText(' Now **edited**.'); await sleep(200);
  586. await page.click(`comments-block li.comment[data-id="c3"] .comment-save`);
  587. await page.waitFor(`!!${R('c3')}.querySelector('details.comment-history')`, { label: 'edited' }).catch(() => {});
  588. await sleep(300);
  589. check('comments: Save — the host told "edit c3", the new text drawn formatted, the editor closed', (await told()) === 'edit c3' && /Now <strong>edited<\/strong>\.<\/p>$/.test(await art('c3') || '') && !(await ev(`!!${R('c3')}.querySelector('form.comment-edit')`)), [await told(), await art('c3')].join(' / '));
  590. await page.click(`comments-block li.comment[data-id="c3"] details.comment-history summary`); await sleep(200);
  591. check('comments: "edited" opens the history — "Edited once" and the earlier text', (await ev(`${R('c3')}.querySelector('details.comment-history').open`))
  592. && (await ev(`${R('c3')}.querySelector('.comment-history-title').textContent`)) === 'Edited once'
  593. && (await ev(`${R('c3')}.querySelector('details.comment-history li pre').textContent`)) === 'A long word wraps on a phone: Donaudampfschifffahrtsgesellschaftskapitänswitwenrentenversicherung.'
  594. && (await ev(`${R('c3')}.querySelector('details.comment-history li pre').getBoundingClientRect().height > 0`)));
  595. check('comments: the history lists the earlier versions oldest first', (await ev(`[...${R('c2')}.querySelectorAll('details.comment-history li pre')].map(p => p.textContent).join('|')`)) === 'First try.|First try, fixed.|Edited twice — the earlier versions fold out under **edited**.');
  596. // Cancel keeps the text
  597. await page.click(`comments-block li.comment[data-id="n2"] .comment-edit-start`);
  598. await page.waitFor(`!!${R('n2')}.querySelector('form.comment-edit article p')`, { label: 'edit form n2' }).catch(() => {});
  599. await page.click(`comments-block li.comment[data-id="n2"] form.comment-edit article`);
  600. await typeText(' not this'); await sleep(150);
  601. await page.click(`comments-block li.comment[data-id="n2"] .comment-cancel`); await sleep(400);
  602. check('comments: Cancel closes the editor, the text and the host stay as they were', (await art('n2')) === '<p>Second, by keyboard</p>' && (await told()) === 'edit c3' && !(await ev(`!!${R('n2')}.querySelector('details.comment-history')`)));
  603. // EDIT / DELETE ONLY FOR THE AUTHOR
  604. check('comments: as alice — Edit / Delete on her comments, none on bob\'s', (await btns('c1')) === '♡ 2|Edit|Delete' && (await btns('c2')) === '♥ 1', (await btns('c1')) + ' / ' + (await btns('c2')));
  605. await page.click('#as-bob');
  606. await page.waitFor(`${R('c2')}.querySelectorAll('comment-actions button').length === 3`, { label: 'as bob' }).catch(() => {});
  607. check('comments: as bob — Edit / Delete on his comment only', (await btns('c2')) === '♥ 1|Edit|Delete' && (await btns('c1')) === '♡ 2' && (await btns('n1')) === '♡ 0', [await btns('c1'), await btns('c2'), await btns('n1')].join(' / '));
  608. await page.click('#as-nobody');
  609. await page.waitFor(`!document.querySelector('comments-block form.comment-form')`, { label: 'as nobody' }).catch(() => {});
  610. check('comments: as nobody — no Edit / Delete anywhere, no form, the sign-in text', (await ev(`document.querySelectorAll('comments-block .comment-edit-start, comments-block .comment-delete').length`)) === 0 && !(await ev(`!!document.querySelector('comments-block form.comment-form')`)) && (await ev(`document.querySelector('comments-block .comments-sign-in').textContent`)) === 'Choose a user above to comment.');
  611. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`); await sleep(400);
  612. check('comments: as nobody the like does nothing', (await ev(`${R('c1')}.querySelector('.comment-like').textContent`)) === '♡ 2' && (await told()) === 'edit c3');
  613. // DELETE asks first; Keep keeps; the counter says 1 comment / n comments
  614. await page.click('#as-alice');
  615. await page.waitFor(`!!document.querySelector('comments-block form.comment-form')`, { label: 'as alice' }).catch(() => {});
  616. await page.click(`comments-block li.comment[data-id="c1"] .comment-delete`);
  617. await page.waitFor(`!!${R('c1')}.querySelector('comment-ask')`, { label: 'ask' }).catch(() => {});
  618. check('comments: Delete asks first ("Delete this comment?" Delete / Keep), nothing gone yet', (await ev(`${R('c1')}.querySelector('comment-ask span').textContent`)) === 'Delete this comment?' && (await ids()) === 'c1,c2,c3,n1,n2');
  619. await page.click(`comments-block li.comment[data-id="c1"] .comment-delete-keep`); await sleep(300);
  620. check('comments: Keep — the comment stays, the question goes', (await ids()) === 'c1,c2,c3,n1,n2' && !(await ev(`!!${R('c1')}.querySelector('comment-ask')`)));
  621. for (const id of ['c1', 'c3', 'n1', 'n2']) {
  622. await page.click(`comments-block li.comment[data-id="${id}"] .comment-delete`);
  623. await page.waitFor(`!!${R(id)}.querySelector('.comment-delete-yes')`, { label: 'ask ' + id }).catch(() => {});
  624. await page.click(`comments-block li.comment[data-id="${id}"] .comment-delete-yes`);
  625. await page.waitFor(`!${R(id)}`, { label: 'gone ' + id }).catch(() => {});
  626. if (id === 'c1') check('comments: Delete — the host told "delete c1", the row gone, the next row keeps its own text', (await told()) === 'delete c1' && (await ids()) === 'c2,c3,n1,n2' && (await art('c2')) === '<p>Changed <strong>elsewhere</strong>: bob edited it in another tab.</p>' && (await count()) === '4 comments', [await told(), await ids(), await art('c2'), await count()].join(' / '));
  627. }
  628. check('comments: counter "1 comment" for one', (await ids()) === 'c2' && (await count()) === '1 comment', (await ids()) + ' ' + (await count()));
  629. await page.click('#as-bob');
  630. await page.waitFor(`!!${R('c2')}.querySelector('.comment-delete')`, { label: 'bob delete' }).catch(() => {});
  631. await page.click(`comments-block li.comment[data-id="c2"] .comment-delete`);
  632. await page.waitFor(`!!${R('c2')}.querySelector('.comment-delete-yes')`, { label: 'ask c2' }).catch(() => {});
  633. await page.click(`comments-block li.comment[data-id="c2"] .comment-delete-yes`);
  634. await page.waitFor(`!${R('c2')}`, { label: 'gone c2' }).catch(() => {});
  635. check('comments: none left — "0 comments" and "No comments yet."', (await count()) === '0 comments' && (await ev(`(document.querySelector('comments-block .comments-empty') || {}).textContent`)) === 'No comments yet.');
  636. await page.click('comments-block form.comment-form md-editor article');
  637. await typeText('Back again'); await key('Enter', 'Enter', 13, '\r', 2);
  638. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 1`, { label: 'one again' }).catch(() => {});
  639. check('comments: a post into the empty thread — "1 comment", the empty text gone', (await count()) === '1 comment' && !(await ev(`!!document.querySelector('comments-block .comments-empty')`)) && (await ev(`document.querySelector('comments-block li.comment .comment-author').textContent`)) === 'bob');
  640. check('comments: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  641. // the look: a fresh thread at 1280 and 390 px; on the phone nothing is wider than the screen
  642. await page.goto(BASE + '/comments');
  643. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  644. await page.waitFor(`!!${R('c1')}.querySelector('md-editor article ul')`, { label: 'drawn' }).catch(() => {});
  645. await page.click(`comments-block li.comment[data-id="c2"] details.comment-history summary`); await sleep(300);
  646. await ev('scrollTo(0, 0)'); await shot('comments-1280');
  647. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  648. await sleep(400);
  649. check('comments: no horizontal overflow at 390 px (the long word wraps)', await ev('document.documentElement.scrollWidth <= window.innerWidth') && (await ev(`${R('c3')}.querySelector('comment-bubble').getBoundingClientRect().right <= window.innerWidth`)));
  650. // K1: the bubble hugs its content (the readonly editor kept an inline min-height of rows x 1.5em = 9em, so every comment had ~250 px of
  651. // empty bubble at 390), and the "edited" marker is a quiet label beside the time, not a framed foldable box
  652. const hug = await ev(`[...document.querySelectorAll('comments-block li.comment')].map(li => { const b = li.querySelector('comment-bubble'); const bb = b.getBoundingClientRect(); const last = [...b.children].filter(c => c.getBoundingClientRect().height > 0).pop().getBoundingClientRect(); const a = b.querySelector('md-editor article'); return { id: li.dataset.id, slack: Math.round(bb.bottom - last.bottom - parseFloat(getComputedStyle(b).paddingBottom)), inline: a ? a.style.minHeight : '' }; })`);
  653. check('comments: at 390 px every bubble hugs its content (no empty area under the last line) and the readonly text has no inline min-height', hug.length >= 3 && hug.every(h => h.slack <= 3 && h.inline === ''), JSON.stringify(hug));
  654. const quiet = await ev(`(() => { const d = ${R('c2')}.querySelector('details.comment-history'); const s = d.querySelector('summary'); const t = ${R('c2')}.querySelector('comment-meta time').getBoundingClientRect(); const sr = s.getBoundingClientRect(); const cs = getComputedStyle(d), ss = getComputedStyle(s); return { box: cs.borderTopStyle + '/' + cs.borderTopWidth, bg: ss.backgroundColor, sb: ss.borderBottomStyle + '/' + ss.borderBottomWidth, pad: ss.paddingTop, sameLine: Math.abs(sr.top - t.top) < 14 && sr.left > t.right - 1, h: Math.round(sr.height) }; })()`);
  655. check('comments: "edited" is a quiet label on the time\'s line — no frame, no header strip, its padding only the 44 px hit area (mission MC)', /^(none|hidden)\/|\/0px$/.test(quiet.box) && quiet.bg === 'rgba(0, 0, 0, 0)' && /^(none|hidden)\/|\/0px$/.test(quiet.sb) && parseFloat(quiet.pad) <= 14 && quiet.sameLine && quiet.h <= 48, JSON.stringify(quiet));
  656. await ev('scrollTo(0, 0)'); await shot('comments-390');
  657. await page.close();
  658. }
  659. // ==== m009 START — tickets#27 (mission 009): ATTACHMENTS IN THE COMMENTS BLOCK. `attach = "true"` puts the block's form inside the
  660. // shared FilesUpload (pick mode); the editor in it has files = "off" (no File button; pasted / dropped files go on to FilesUpload);
  661. // `onPost(text, files)`; a comment record's `files` ([{ name, url, image, size }]) show as thumbnails (open the full picture) or rows
  662. // (kind, name, size; no url = no link). REAL input: the chooser's file input (DOM.setFileInputFiles), a real Ctrl+V of an image into
  663. // the editor, real clicks / keys; the demo's face stores the files (lib/uploads.hl) and the page shows the new comment's files.
  664. // Null-safe reads: on the old code every check FAILS instead of ending the gate. Screenshots .scratch/gate-comments-attach-{1280,390}.png.
  665. {
  666. const crc = (buf) => { let c, t = []; for (let n = 0; n < 256; n++) { c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } let x = 0xffffffff; for (const b of buf) x = t[(x ^ b) & 0xff] ^ (x >>> 8); return (x ^ 0xffffffff) >>> 0; };
  667. const png = (w, h, rgb) => {
  668. const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };
  669. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  670. const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([(rgb[0] + x) & 255, (rgb[1] + y) & 255, rgb[2]], y * (w * 3 + 1) + 1 + x * 3);
  671. return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);
  672. };
  673. const AD = join(SCRATCH, 'gate-attach');
  674. mkdirSync(AD, { recursive: true });
  675. writeFileSync(join(AD, 'shot-390.png'), png(390, 300, [20, 120, 200]));
  676. writeFileSync(join(AD, 'shot-1280.png'), png(640, 400, [200, 80, 20]));
  677. writeFileSync(join(AD, 'big.bin'), Buffer.alloc(3 * 1048576, 7));
  678. writeFileSync(join(AD, 'log.txt'), 'line one\nline two\n');
  679. const A = (n) => join(AD, n);
  680. const ssr = (await (await fetch(BASE + '/comments')).text()).replace(/<!--[\[\]]-->/g, '');
  681. check('m009: the server draws a comment\'s files: the picture as a thumbnail link to the full picture, the README as a row (MD, 5.3 KB), the file without url as a row without link',
  682. /<ul class="comment-files"[^>]*><li><a class="comment-thumb" href="\/icons\/icon-512.png" target="_blank" rel="noopener" title="icon-512.png"><img src="\/icons\/icon-512.png" alt="icon-512.png" loading="lazy"/.test(ssr)
  683. && /<a class="comment-file" href="\/comments\/README.md"[^>]*><span class="kind" aria-hidden="true">MD<\/span><file-info><strong class="name">README.md<\/strong><span class="size">5.3 KB<\/span>/.test(ssr)
  684. && /<span class="comment-file"><span class="kind" aria-hidden="true">PDF<\/span><file-info><strong class="name">members-only-report-with-a-long-name-2026-10-20.pdf<\/strong><span class="size">47.1 KB<\/span>/.test(ssr), (ssr.match(/<ul class="comment-files".{0,600}/) || ['none'])[0]);
  685. const page = await browser.newPage();
  686. const ev = (e) => page.evaluate(e);
  687. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  688. const tryDo = async (f) => { try { await f(); } catch {} };
  689. const key = async (k, code, vk, text, modifiers = 0) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, text, modifiers }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, modifiers }); await sleep(15); };
  690. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  691. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  692. const R = (id) => `document.querySelector('comments-block li.comment[data-id="${id}"]')`;
  693. const filesOf = (id) => ev(`(() => { const li = ${R(id)}; return li ? [...li.querySelectorAll('ul.comment-files li')].map(x => { const i = x.querySelector('img'); return i ? 'img:' + (i.complete ? i.naturalWidth : 0) + ':' + x.querySelector('a').getAttribute('href') : (x.querySelector('a') ? 'link:' : 'row:') + x.querySelector('.kind').textContent + ':' + x.querySelector('.name').textContent + ':' + x.querySelector('.size').textContent; }) : null; })()`);
  694. const picked = () => ev(`[...document.querySelectorAll('comments-block files-upload li.picked')].map(li => li.querySelector('.name').textContent + ':' + (li.querySelector('img.thumb') ? 'img' + li.querySelector('img.thumb').naturalWidth : 'kind'))`);
  695. const told = () => ev(`(document.querySelector('#comments-told') || {}).textContent`);
  696. const chooseFiles = async (names) => {
  697. const { root } = await page.send('DOM.getDocument');
  698. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'comments-block files-upload label.choose input[type=file]' });
  699. try { await page.send('DOM.setFileInputFiles', { files: names.map(A), nodeId }); } catch {}
  700. };
  701. await browser.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  702. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  703. await page.goto(BASE + '/comments');
  704. await hydrated();
  705. await page.waitFor(`!!${R('c2')} && [...${R('c2')}.querySelectorAll('ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'thumbs' }).catch(() => {});
  706. const c2 = await filesOf('c2');
  707. check('m009: in the browser the thumbnail is drawn (512 px picture) and the README row links it', JSON.stringify(c2) === JSON.stringify(['img:512:/icons/icon-512.png', 'link:MD:README.md:5.3 KB']), JSON.stringify(c2));
  708. check('m009: the form sits inside the FilesUpload (pick mode); the editor in it has no File button (files = "off")',
  709. await ev(`(() => { const f = document.querySelector('comments-block files-upload form.comment-form md-editor[data-files="off"]'); const b = f && f.querySelector('nav button.file'); return !!b && getComputedStyle(b).display === 'none' && !!document.querySelector('comments-block files-upload pick-area label.choose input[type=file]') && !document.querySelector('comments-block files-upload drop-zone'); })()`));
  710. // choose two pictures, then a REAL Ctrl+V of a third into the editor
  711. await chooseFiles(['shot-390.png', 'shot-1280.png']);
  712. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 2 && [...document.querySelectorAll('comments-block files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'two chosen' }).catch(() => {});
  713. await sleep(400);
  714. await tryDo(() => page.click('comments-block form.comment-form md-editor article'));
  715. await page.waitFor(`!!document.querySelector('comments-block form.comment-form md-editor article') && document.querySelector('comments-block form.comment-form md-editor article').contains(document.activeElement)`, { timeout: 5000, label: 'editor focused' }).catch(() => {});
  716. await typeText('Two shots and a paste'); await sleep(200);
  717. const put = await ev(`(async () => { try { const c = document.createElement('canvas'); c.width = 150; c.height = 90; const x = c.getContext('2d'); x.fillStyle = '#264'; x.fillRect(0, 0, 150, 90); const b = await new Promise(r => c.toBlob(r, 'image/png')); await navigator.clipboard.write([new ClipboardItem({ 'image/png': b })]); return 'ok'; } catch (e) { return 'ERR ' + e.message; } })()`);
  718. await page.send('Page.bringToFront');
  719. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  720. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  721. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 3 && [...document.querySelectorAll('comments-block files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'pasted' }).catch(() => {});
  722. const pk = await picked();
  723. check('m009: two chosen pictures + a real Ctrl+V into the editor wait as three drawn thumbnails; the editor keeps only the text (no upload of its own)',
  724. put === 'ok' && JSON.stringify(pk) === JSON.stringify(['shot-390.png:img390', 'shot-1280.png:img640', 'image.png:img150']) && (await ev(`(document.querySelector('comments-block form.comment-form md-editor input.value') || {}).value`)) === 'Two shots and a paste'
  725. && (await ev(`performance.getEntriesByType('resource').filter(r => r.name.includes('/__hl/upload')).length`)) === 0, put + ' ' + JSON.stringify(pk) + ' ' + JSON.stringify(await ev(`(document.querySelector('comments-block form.comment-form md-editor input.value') || {}).value`)) + ' uploads ' + (await ev(`performance.getEntriesByType('resource').filter(r => r.name.includes('/__hl/upload')).length`)));
  726. // a file over the block's maxFileSize (2 MB): refused in its row, not added
  727. await chooseFiles(['big.bin']);
  728. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.refused').length === 1`, { timeout: 10000, label: 'refused' }).catch(() => {});
  729. check('m009: a 3 MB file is refused in its own row ("Too big — at most 2.0 MB"), the three pictures stay', (await ev(`[...document.querySelectorAll('comments-block files-upload li.refused .state')].map(s => s.textContent).join()`)) === 'Too big — at most 2.0 MB' && (await picked()).length === 3);
  730. // send with Ctrl+Enter: the host gets text + the three files, its face stores them, the new comment shows three drawn thumbnails
  731. await tryDo(() => page.click('comments-block form.comment-form md-editor article'));
  732. await key('Enter', 'Enter', 13, '\r', 2);
  733. await page.waitFor(`!!${R('n1')} && ${R('n1')}.querySelectorAll('ul.comment-files img').length === 3 && [...${R('n1')}.querySelectorAll('ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 30000, label: 'posted with files' }).catch(() => {});
  734. const n1 = await filesOf('n1') || [];
  735. check('m009: Ctrl+Enter posts — the host told "post with 3 files", the new comment shows the three pictures drawn (390, 640, 150 px) in order',
  736. (await told()) === 'post with 3 files' && n1.length === 3 && /^img:390:\/md-editor\/files\/.*\.png$/.test(n1[0]) && /^img:640:/.test(n1[1]) && /^img:150:/.test(n1[2]), (await told()) + ' ' + JSON.stringify(n1));
  737. const first = (n1[0] || '').split(':').slice(2).join(':');
  738. const full = first ? await fetch(BASE + first) : null;
  739. const fullBuf = full ? Buffer.from(await full.arrayBuffer()) : Buffer.alloc(0);
  740. check('m009: the thumbnail\'s link is the stored picture, byte for byte', !!full && full.ok && fullBuf.equals(readFileSync(A('shot-390.png'))), first);
  741. check('m009: after the post the form is empty: no picked file, no refused row, an empty editor', (await ev(`document.querySelectorAll('comments-block files-upload ul.files li').length`)) === 0 && (await ev(`(document.querySelector('comments-block form.comment-form md-editor input.value') || {}).value`)) === '');
  742. // a REAL click on a thumbnail opens the full picture in a new tab
  743. const tabs0 = (await browser.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length;
  744. await tryDo(() => page.click(`comments-block li.comment[data-id="n1"] a.comment-thumb`, { timeout: 3000 }));
  745. let opened = null;
  746. for (let i = 0; i < 20 && !opened; i++) { await sleep(250); opened = (await browser.conn.send('Target.getTargets')).targetInfos.find(t => t.type === 'page' && t.url.endsWith(first) && first); }
  747. check('m009: a click on a thumbnail opens the full picture (a new tab with its address)', !!opened && (await browser.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length === tabs0 + 1, JSON.stringify(opened));
  748. if (opened) await browser.conn.send('Target.closeTarget', { targetId: opened.targetId }).catch(() => {});
  749. // files only, no text: a post of one text file is a row with its kind, name and size, linked
  750. await chooseFiles(['log.txt']);
  751. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 1`, { timeout: 10000, label: 'txt' }).catch(() => {});
  752. await tryDo(() => page.click('comments-block button.comment-post', { timeout: 3000 }));
  753. await page.waitFor(`!!${R('n2')}`, { timeout: 30000, label: 'files only' }).catch(() => {});
  754. check('m009: a post with a file and no text works: the comment shows the row "TXT log.txt 18 B" as a link', JSON.stringify(await filesOf('n2')) === JSON.stringify(['link:TXT:log.txt:18 B']) && (await told()) === 'post with 1 files', JSON.stringify(await filesOf('n2')));
  755. await tryDo(() => page.click('comments-block button.comment-post', { timeout: 3000 })); await sleep(400);
  756. check('m009: an empty form (no text, no file) still sends nothing', !(await ev(`!!${R('n3')}`)));
  757. check('m009: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  758. await ev('scrollTo(0, 0)'); await shot('comments-attach-1280');
  759. // the 390 px phone, touch: targets ≥ 44 × 44 (thumbnails, file rows, Choose files, Camera, Comment, ✕), nothing wider than the screen
  760. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  761. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  762. await page.goto(BASE + '/comments');
  763. await hydrated();
  764. await page.click('#as-alice').catch(() => {});
  765. await chooseFiles(['shot-390.png', 'log.txt']);
  766. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 2`, { timeout: 10000, label: 'phone picked' }).catch(() => {});
  767. await sleep(500);
  768. const targets = await ev(`[...document.querySelectorAll('comments-block a.comment-thumb, comments-block .comment-file, comments-block files-upload label.choose, comments-block files-upload label.camera, comments-block files-upload button.remove, comments-block button.comment-post')].map(el => { const r = el.getBoundingClientRect(); return el.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);
  769. check('m009 390px: every attachment target is at least 44 × 44 px (thumbnail, file rows, Choose files, Camera, ✕, Comment)', targets.length === 8 && targets.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), JSON.stringify(targets));
  770. check('m009 390px: no horizontal overflow (the long file name wraps)', await ev(`document.documentElement.scrollWidth <= window.innerWidth && [...document.querySelectorAll('comments-block ul.comment-files li, comments-block files-upload li')].every(li => li.getBoundingClientRect().right <= window.innerWidth)`), await ev(`document.documentElement.scrollWidth + ' > ' + window.innerWidth`));
  771. await ev('scrollTo(0, 0)'); await shot('comments-attach-390');
  772. await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  773. await page.close();
  774. }
  775. // ==== m009 END
  776. // the pagination: 89 pages; the ticket's three shapes
  777. check('home lists the pagination', home.includes('id="open-pagination"'));
  778. check('pagination README is served', (await fetch(BASE + '/pagination/README.md')).ok);
  779. await page.goto(BASE + '/pagination');
  780. await page.waitForSelector('#pagination-items');
  781. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  782. await sleep(500);
  783. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  784. const clickPg = (t) => ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === ${JSON.stringify(t)}).click()`);
  785. const waitPg = (t) => page.waitFor(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ') === ${JSON.stringify(t)}`, { label: 'pagination ' + t });
  786. check('pagination: first page shows 1 2 3 4 … 89 Next', (await pg()) === '1 2 3 4 … 89 Next', await pg());
  787. await clickPg('4'); await waitPg('Previous 1 2 3 4 5 … 89 Next');
  788. check('pagination: page 4 fills a one-page gap: Previous 1 2 3 4 5 … 89 Next', true);
  789. await clickPg('5'); await waitPg('Previous 1 … 4 5 6 … 89 Next'); await clickPg('6'); await waitPg('Previous 1 … 5 6 7 … 89 Next'); await clickPg('7');
  790. await waitPg('Previous 1 … 6 7 8 … 89 Next');
  791. check('pagination: middle shows first, last, current ± 1', true);
  792. check('pagination: current page is marked', (await ev(`document.querySelector('#pagination-items li.current button').textContent`)) === '7');
  793. await ev(`document.querySelector('#pagination-items li.gap button').click()`); await sleep(300);
  794. check('pagination: a click on … does nothing', (await pg()) === 'Previous 1 … 6 7 8 … 89 Next');
  795. await clickPg('Previous'); await waitPg('Previous 1 … 5 6 7 … 89 Next');
  796. check('pagination: Previous goes back one page', true);
  797. await clickPg('89'); await waitPg('Previous 1 … 86 87 88 89');
  798. check('pagination: last page shows Previous 1 … 86 87 88 89, no Next', true);
  799. await clickPg('1'); await waitPg('1 2 3 4 … 89 Next');
  800. check('pagination: back on page 1 no Previous', true);
  801. // ticket #16 (mission 005): the host is told the target page on every click — real pointer clicks, keyboard Enter / Space, a script's
  802. // click(); Previous / Next / numbers / the first and last page; nothing for … or the current page. The demo hands `onPage = heardPage`.
  803. {
  804. await page.goto(BASE + '/pagination');
  805. await page.waitForSelector('#pagination-items');
  806. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  807. await sleep(500);
  808. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  809. const heard = () => ev(`(document.getElementById('pagination-heard') || {}).textContent`);
  810. const sel = async (label) => { const k = await ev(`[...document.querySelectorAll('#pagination-items button')].findIndex(b => b.textContent === ${JSON.stringify(label)})`); return k < 0 ? '#no-such-button' : `#pagination-items li:nth-child(${k + 1}) button`; };
  811. const told = (want) => page.waitFor(`(document.getElementById('pagination-heard') || {}).textContent === ${JSON.stringify(want)}`, { label: 'host told ' + want, timeout: 3000 }).then(() => true, () => false);
  812. const realClick = async (label, want, list) => { const s = await sel(label); try { await page.click(s, { timeout: 2000 }); } catch {} const ok = await told(want); await sleep(150); return ok && (list == null || (await pg()) === list); };
  813. const pressOn = async (label, key, want) => { const s = await sel(label); try { await page.focus(s); } catch {} const code = key === ' ' ? 'Space' : 'Enter'; await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key, code, windowsVirtualKeyCode: key === ' ' ? 32 : 13, text: key === ' ' ? ' ' : '\r' }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code, windowsVirtualKeyCode: key === ' ' ? 32 : 13 }); return told(want); };
  814. check('#16: the host has heard nothing before a click', (await heard()) === 'none yet', await heard());
  815. check('#16: real click on Next (page 1) tells the host page 2', await realClick('Next', 'page 2', 'Previous 1 2 3 4 … 89 Next'), JSON.stringify([await heard(), await pg()]));
  816. check('#16: real click on 4 tells page 4', await realClick('4', 'page 4', 'Previous 1 2 3 4 5 … 89 Next'), JSON.stringify([await heard(), await pg()]));
  817. check('#16: real click on the last page (89) tells page 89', await realClick('89', 'page 89', 'Previous 1 … 86 87 88 89'), JSON.stringify([await heard(), await pg()]));
  818. check('#16: real click on Previous (page 89) tells page 88', await realClick('Previous', 'page 88', 'Previous 1 … 86 87 88 89 Next'), JSON.stringify([await heard(), await pg()]));
  819. check('#16: real click on Next (page 88, the last Next) tells page 89', await realClick('Next', 'page 89', 'Previous 1 … 86 87 88 89'), JSON.stringify([await heard(), await pg()]));
  820. check('#16: real click on the first page (1) tells page 1', await realClick('1', 'page 1', '1 2 3 4 … 89 Next'), JSON.stringify([await heard(), await pg()]));
  821. const g = await sel('…'); try { await page.click(g, { timeout: 2000 }); } catch {} await sleep(400);
  822. check('#16: a real click on … tells nothing and moves nothing', (await heard()) === 'page 1' && (await pg()) === '1 2 3 4 … 89 Next', JSON.stringify([await heard(), await pg()]));
  823. const c = await sel('1'); try { await page.click(c, { timeout: 2000 }); } catch {} await sleep(400);
  824. check('#16: a click on the current page tells nothing', (await heard()) === 'page 1', await heard());
  825. check('#16: keyboard Enter on 3 tells page 3', await pressOn('3', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  826. check('#16: keyboard Space on Next tells page 4', await pressOn('Next', ' ', 'page 4'), JSON.stringify([await heard(), await pg()]));
  827. check('#16: keyboard Enter on Previous tells page 3', await pressOn('Previous', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  828. check('#16: the keyboard focus ring is the component\'s own solid grey (Chrome\'s `auto` ring paints orange but reports a grey)', await ev(`(() => { const cs = getComputedStyle(document.activeElement); return document.activeElement.tagName === 'BUTTON' && cs.outlineStyle === 'solid' && /^rgb\\((\\d+), \\1, \\1\\)$/.test(cs.outlineColor); })()`), await ev(`document.activeElement.tagName + ' ' + getComputedStyle(document.activeElement).outlineStyle + ' ' + getComputedStyle(document.activeElement).outlineColor`));
  829. await ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === '89').click()`);
  830. check('#16: a script click() on 89 tells page 89', await told('page 89'), await heard());
  831. check('#16: every button carries its target page (data-page) after the rebuilds', await ev(`[...document.querySelectorAll('#pagination-items li')].every(li => { const b = li.querySelector('button'), t = b.textContent, d = b.getAttribute('data-page'); return li.classList.contains('gap') ? d === '0' : t === 'Previous' ? d === '88' : t === 'Next' ? false : d === t; })`), await ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent + '=' + b.getAttribute('data-page')).join(' ')`));
  832. check('#16: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  833. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  834. await sleep(300); await shot('pagination-390');
  835. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  836. await sleep(200);
  837. }
  838. await shot('pagination');
  839. check('no console errors on the pagination page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  840. // the Markdown editor: two on one page, real typing and real clicks
  841. check('home lists the Markdown editor', home.includes('id="open-md-editor"'));
  842. const mdr = await fetch(BASE + '/md-editor/README.md');
  843. check('Markdown editor README is served as Markdown', mdr.ok && /markdown/.test(mdr.headers.get('content-type')) && (await mdr.text()).includes('Markdown editor'));
  844. check('no .js of its own in components/md-editor', !existsSync(join(APP, 'components/md-editor')) || !execSync(`find ${join(APP, 'components/md-editor')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  845. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  846. await page.goto(BASE + '/md-editor');
  847. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  848. const ED = 'md-editor:nth-of-type(1)';
  849. const md1 = (q) => `document.querySelectorAll('md-editor')[0].${q}`;
  850. const md2 = (q) => `document.querySelectorAll('md-editor')[1].${q}`;
  851. const val1 = () => ev(md1(`querySelector('input.value').value`));
  852. const val2 = () => ev(md2(`querySelector('input.value').value`));
  853. const art1 = () => ev(md1(`querySelector('article').innerHTML`));
  854. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  855. check('a value shows formatted: heading, bold, italic, code, link, list', (await art1()) === '<h1>Hello</h1><p>Some <strong>bold</strong> and <em>italic</em> text with <code>code</code> and a <a href="https://example.com">link</a>.</p><ul><li>first</li><li>second</li></ul>', await art1());
  856. check('an untouched value is the same Markdown', (await val1()) === '# Hello\n\nSome **bold** and *italic* text with `code` and a [link](https://example.com).\n\n- first\n- second', await val1());
  857. check('the canonical form of the value equals it (round trip)', await ev(md1(`mdCanon`) + ` === ` + md1(`querySelector('input.value').value`)));
  858. check('the second editor is empty and shows its placeholder', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('.placeholder')).display`)) === 'block');
  859. // ==== m010 START — tickets#29 (mission 010): the editor's LOOK: no class that a host's `.empty` rule can hit, `rows` is the height, one toolbar row on a phone with 44 px targets
  860. check('m010: an empty editor carries no class `empty` (a host rule for "no tickets" paragraphs hit it: dashed frame, 16 px padding) and its root has no border / padding', await ev(`(() => { const m = document.querySelectorAll('md-editor')[1]; const c = getComputedStyle(m); return !m.classList.contains('empty') && m.classList.contains('md-empty') && c.borderTopWidth === '0px' && c.paddingTop === '0px'; })()`));
  861. check('m010: `rows` sets the surface height (default 6 = 6 lines of 1.5 em = 144 px, not a fixed 128 px)', await ev(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = getComputedStyle(a); return Math.abs(parseFloat(c.minHeight) - 6 * 1.5 * parseFloat(c.fontSize)) < 0.5; })()`), await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('article')).minHeight`));
  862. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  863. await sleep(300);
  864. // E2: at 390 px every toolbar button is inside the editor box (nothing clipped, no sideways swipe), two even rows, each a 44 px target; the footer label is >= 14 px and a 44 px target; nothing wider than the screen
  865. const bar390 = await ev(`(() => { const m = document.querySelectorAll('md-editor')[0]; const n = m.querySelector('nav'); const box = m.getBoundingClientRect(); const bs = [...n.querySelectorAll('button')].filter(b => getComputedStyle(b).display !== 'none').map(b => b.getBoundingClientRect()); const tops = [...new Set(bs.map(r => Math.round(r.top)))].sort((a, b) => a - b); const per = tops.map(t => bs.filter(r => Math.round(r.top) === t).length); const f = m.querySelector('footer button.source-switch'); const fr = f.getBoundingClientRect(); return { rows: tops.length, per, outside: bs.filter(r => r.left < box.left - 0.5 || r.right > box.right + 0.5).length, scrolls: n.scrollWidth > n.clientWidth + 1, minW: Math.min(...bs.map(r => r.width)), minH: Math.min(...bs.map(r => r.height)), n: bs.length, labelPx: parseFloat(getComputedStyle(f).fontSize), labelH: fr.height, docW: document.documentElement.scrollWidth }; })()`);
  866. check('E2: at 390 px the toolbar is two even rows (6 + 6), no button outside the editor box, no sideways scroll in the toolbar, every button at least 44 x 44 px; the page does not scroll sideways', bar390.rows === 2 && bar390.per[0] - bar390.per[1] <= 1 && bar390.n === 12 && bar390.outside === 0 && !bar390.scrolls && bar390.minW >= 43.9 && bar390.minH >= 43.9 && bar390.docW <= 390, JSON.stringify(bar390));
  867. check('E2: at 390 px the "Markdown source" label is at least 14 px and a 44 px target (quiet: muted colour kept)', bar390.labelPx >= 14 && bar390.labelH >= 43.9 && (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[0].querySelector('footer button.source-switch')).color`)) !== (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[0]).color`)), JSON.stringify(bar390));
  868. const bar1000 = await ev(`(() => { const bs = [...document.querySelectorAll('md-editor')[0].querySelectorAll('nav button')].filter(b => getComputedStyle(b).display !== 'none').map(b => b.getBoundingClientRect()); return new Set(bs.map(r => Math.round(r.top))).size; })()`);
  869. // desktop width keeps ONE row (checked below, after the viewport is wide again)
  870. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  871. await sleep(300);
  872. const row1000 = await ev(`(() => { const bs = [...document.querySelectorAll('md-editor')[0].querySelectorAll('nav button')].filter(b => getComputedStyle(b).display !== 'none').map(b => b.getBoundingClientRect()); return { rows: new Set(bs.map(r => Math.round(r.top))).size, h: Math.round(bs[0].height), w: Math.round(bs[0].width), labelPx: parseFloat(getComputedStyle(document.querySelector('md-editor footer button.source-switch')).fontSize) }; })()`);
  873. check('E2: on a desktop width the toolbar stays ONE row of 32 px buttons and the label keeps 13.6 px', row1000.rows === 1 && row1000.h === 32 && Math.abs(row1000.labelPx - 13.6) < 0.1, JSON.stringify(row1000));
  874. // ==== m010 END
  875. // ==== F4 START — the editor's own focus ring is the only one (no second rectangle inside it, even under an app theme with `:focus-visible` / `textarea:focus`), and the toolbar buttons hold SVG icons from components/icons
  876. await ev(`(() => { const st = document.createElement('style'); st.id = 'f4-theme'; st.textContent = ':focus-visible { outline: 2px solid rgb(255, 0, 0); outline-offset: 2px } input:focus, select:focus, textarea:focus { outline: 2px solid rgb(255, 0, 0); outline-offset: 0 }'; document.head.appendChild(st); })()`);
  877. await page.click('md-editor:nth-of-type(2) article'); await sleep(200);
  878. const f4a = await ev(`(() => { const m = document.querySelectorAll('md-editor')[1]; const a = m.querySelector('article'); const ca = getComputedStyle(a); const cm = getComputedStyle(m); return { focused: document.activeElement === a, vis: a.matches(':focus-visible'), art: ca.outlineStyle + '/' + ca.outlineWidth, root: cm.outlineStyle + '/' + cm.outlineWidth }; })()`);
  879. check('F4: the focused surface has NO outline of its own, even under a theme `:focus-visible` rule; the editor frame keeps its single 2 px ring', f4a.focused && f4a.art.startsWith('none/') && f4a.root === 'solid/2px', JSON.stringify(f4a));
  880. await page.click('md-editor:nth-of-type(2) footer button.source-switch'); await sleep(300);
  881. await page.click('md-editor:nth-of-type(2) textarea'); await sleep(200);
  882. const f4b = await ev(`(() => { const m = document.querySelectorAll('md-editor')[1]; const t = m.querySelector('textarea'); const ct = getComputedStyle(t); const cm = getComputedStyle(m); return { focused: document.activeElement === t, ta: ct.outlineStyle + '/' + ct.outlineWidth, root: cm.outlineStyle + '/' + cm.outlineWidth }; })()`);
  883. check('F4: the focused source textarea has NO outline of its own under a theme `textarea:focus` rule; the editor frame keeps its single ring', f4b.focused && f4b.ta.startsWith('none/') && f4b.root === 'solid/2px', JSON.stringify(f4b));
  884. await page.click('md-editor:nth-of-type(2) footer button.source-switch'); await sleep(300);
  885. await ev(`document.getElementById('f4-theme').remove()`);
  886. const f4c = await ev(`(() => { const bs = [...document.querySelectorAll('md-editor')[0].querySelectorAll('nav button')]; const cls = bs.map(b => b.className.split(' ')[0]); const svg = bs.every(b => { const s = b.querySelector('svg'); return s && s.getAttribute('aria-hidden') === 'true' && s.querySelector('path') && s.querySelector('path').getAttribute('d').length > 8 && getComputedStyle(s).stroke !== 'none'; }); const named = bs.every(b => b.title && b.getAttribute('aria-label') === b.title); const noText = bs.every(b => b.textContent.trim() === ''); return { cls: cls.join(','), svg, named, noText, n: bs.length, linkTitle: (bs.find(b => b.classList.contains('link')) || {}).title }; })()`);
  887. check('F4: every toolbar button (bold italic code link heading ul ol pre table file undo redo) holds an SVG icon, no text, and keeps title + aria-label with the shortcut', f4c.n === 12 && f4c.svg && f4c.named && f4c.noText && f4c.linkTitle === 'Link (Ctrl+K)', JSON.stringify(f4c));
  888. check('F4: components/icons/icons.hl is the one source: each icon\'s drawing is in it once, none of the other components carries an <svg> path of its own', (() => { const own = ['md-editor/md-editor.hl', 'comments/comments.hl', 'files-upload/files-upload.hl'].map(f => readFileSync(join(APP, 'components', f), 'utf8')); return own.every(t => !/M10 14a4 4|viewBox/.test(t) && /import Icon from '..\/icons\/icons\.hl'/.test(t) === (t.includes('Icon {'))); })());
  889. const f4d = await ev(`(() => { const u = performance.getEntriesByType('resource').map(r => r.name.split('?')[0]).filter(n => n.endsWith('/components/icons/icons.hl')); return u.length; })()`);
  890. check('F4: the page fetches the icons module once however many components import it', f4d <= 1, String(f4d));
  891. // ==== F4 END
  892. const key = async (k, code, vk, text) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, text }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk }); };
  893. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  894. const enter = () => key('Enter', 'Enter', 13, '\r');
  895. // type into the second editor: heading, bold, code, list
  896. await page.click('md-editor:nth-of-type(2) article');
  897. check('the placeholder goes away when it has text', true);
  898. await typeText('# Title'); await typeText(' '); await typeText('here'); await enter();
  899. await typeText('a **bold** and `code` x'); await enter();
  900. check('typing "# " makes a heading while you type', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  901. const html2 = await ev(md2(`querySelector('article').innerHTML`));
  902. check('typing **x** and `x` formats them', /<strong>bold<\/strong>/.test(html2) && /<code>code<\/code>/.test(html2), html2);
  903. await typeText('- '); await sleep(100);
  904. check('typing "- " makes a list', (await ev(md2(`querySelector('article ul')`) + ' !== null')));
  905. await typeText('item one'); await enter(); await typeText('item two');
  906. await sleep(400);
  907. const v2 = await val2();
  908. check('the value is plain Markdown of what you typed', v2.startsWith('# Title here\n\na **bold** and `code` x\n\n') && /- item one\n- item two$/.test(v2), JSON.stringify(v2));
  909. check('the demo shows that value below the editor', (await ev(`document.getElementById('md-value-summary').textContent`)) === v2);
  910. check('the first editor was not touched by typing in the second', (await val1()).startsWith('# Hello'));
  911. check('the editor content survives re-renders of the page (same article element)', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  912. // toolbar: select the first list item in the first editor, Bold, then Undo
  913. const selectIn = (i, css) => ev(`(()=>{const e=document.querySelectorAll('md-editor')[${i}].querySelector(${JSON.stringify('article ' + css)});const r=document.createRange();r.selectNodeContents(e);const s=getSelection();s.removeAllRanges();s.addRange(r)})()`);
  914. await selectIn(0, 'li:nth-child(1)');
  915. await page.click('md-editor:nth-of-type(1) nav button.bold'); await sleep(250);
  916. check('toolbar Bold: the selection is **bold** in the value', (await val1()).endsWith('- **first**\n- second'), await val1());
  917. await page.click('md-editor:nth-of-type(1) nav button.undo'); await sleep(250);
  918. check('toolbar Undo takes it back', (await val1()).endsWith('- first\n- second'), await val1());
  919. await selectIn(0, 'h1');
  920. await page.click('md-editor:nth-of-type(1) nav button.heading'); await sleep(250);
  921. check('toolbar heading button: H1 becomes H2', (await val1()).startsWith('## Hello'), await val1());
  922. await selectIn(0, 'ul');
  923. await page.click('md-editor:nth-of-type(1) nav button.ol'); await sleep(250);
  924. check('toolbar numbered list: the bullets become 1. 2.', (await val1()).endsWith('1. first\n2. second'), await val1());
  925. await selectIn(0, 'p');
  926. await page.click('md-editor:nth-of-type(1) nav button.pre'); await sleep(250);
  927. check('toolbar code block: the paragraph becomes a fenced block', /```\nSome .*\n```/.test(await val1()), await val1());
  928. // link: Ctrl+K opens the small form, Apply
  929. await ev(`(()=>{const a=document.querySelectorAll('md-editor')[1].querySelector('article');const e=a.querySelector('h1');const r=document.createRange();r.selectNodeContents(e);const s=getSelection();s.removeAllRanges();s.addRange(r);a.focus()})()`);
  930. await page.click('md-editor:nth-of-type(2) nav button.link'); await sleep(250);
  931. check('the link form opens', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('link-form')).display`)) === 'flex');
  932. await ev(md2(`querySelector('link-form input').focus()`));
  933. await typeText('https://example.org/x'); await enter(); await sleep(300);
  934. check('a link is added: [text](url) in the value', (await val2()).includes('# [Title here](https://example.org/x)'), await val2());
  935. check('a javascript: link is refused', await (async () => { await selectIn(1, 'li:nth-child(1)'); await page.click('md-editor:nth-of-type(2) nav button.link'); await ev(md2(`querySelector('link-form input').focus()`)); await typeText('javascript:alert(1)'); await enter(); await sleep(250); return !(await val2()).includes('javascript:'); })());
  936. // paste Markdown in: formatted, plain text; html in it stays text
  937. await ev(`(()=>{const a=document.querySelectorAll('md-editor')[0].querySelector('article');a.focus();const s=getSelection();s.selectAllChildren(a);s.collapseToEnd();const dt=new DataTransfer();dt.setData('text/plain','## Pasted\\n\\nhello **there** <b>x</b>');a.dispatchEvent(new ClipboardEvent('paste',{clipboardData:dt,bubbles:true,cancelable:true}))})()`);
  938. await sleep(300);
  939. const a1 = await art1();
  940. check('pasted Markdown shows formatted', /<h2>Pasted<\/h2><p>hello <strong>there<\/strong> /.test(a1), a1);
  941. check('pasted HTML stays text (no element made from it)', !/<b>x<\/b>/.test(a1) && (await val1()).includes('\\<b>x\\</b>'), a1);
  942. // the Markdown source switch
  943. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  944. check('the source switch shows a textarea with the Markdown, hides the visual editor', (await ev(md1(`querySelector('textarea').value`))) === (await val1()) && (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[0].querySelector('article')).display`)) === 'none');
  945. await ev(md1(`querySelector('textarea')`) + `.value = '# From source\\n\\n1. a\\n2. b\\n\\n~~~\\nx < y\\n~~~'; ` + md1(`querySelector('textarea')`) + `.dispatchEvent(new Event('input', { bubbles: true }))`);
  946. await sleep(200);
  947. check('typing in the source is the value (and shown below)', (await val1()) === '# From source\n\n1. a\n2. b\n\n~~~\nx < y\n~~~' && (await ev(`document.getElementById('md-value').textContent`)) === (await val1()));
  948. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  949. check('back to the visual editor: the source text is formatted', (await art1()) === '<h1>From source</h1><ol><li>a</li><li>b</li></ol><pre>x &lt; y</pre>', await art1());
  950. // the form posts both editors by name
  951. await page.click('#md-form button[type=submit]'); await sleep(800);
  952. const url = new URL(await ev('location.href'));
  953. check('the form posts both values by their names', url.searchParams.get('note').replaceAll('\r\n', '\n') === '# From source\n\n1. a\n2. b\n\n~~~\nx < y\n~~~' && url.searchParams.get('summary') != null && url.searchParams.get('summary').startsWith('# [Title here]'), url.search);
  954. await shot('md-editor');
  955. check('no console errors on the Markdown editor page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  956. // typed Markdown shortcuts are CONSUMED: the marker disappears, only the formatting stays (real keys, one character at a time)
  957. await page.goto(BASE + '/md-editor');
  958. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  959. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  960. const keyR = async (k, code, vk, text, modifiers) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, text, modifiers }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, modifiers }); await sleep(20); };
  961. const typeR = async (t) => { for (const ch of t) await keyR(ch, ch === ' ' ? 'Space' : '', ch === ' ' ? 32 : undefined, ch); };
  962. const enterR = () => keyR('Enter', 'Enter', 13, '\r');
  963. // ticket #17 (mission 005): backslash + r in loaded Markdown stays — it is text (C:\root), not a carriage return; typed in the source
  964. // view with real keys, loaded back into the visual editor, written as Markdown and loaded once more. A REAL carriage return (a Windows
  965. // clipboard's CR LF) goes.
  966. {
  967. const S2 = 'md-editor:nth-of-type(2)';
  968. const text2 = () => ev(md2(`querySelector('article').textContent`));
  969. await page.click(S2 + ' footer button'); await sleep(300);
  970. await page.focus(S2 + ' textarea');
  971. await typeR('Path C:\\root\\new and \\r\\n stay'); await sleep(200);
  972. await page.click(S2 + ' footer button'); await sleep(400);
  973. check('#17: loaded Markdown keeps backslash + r (C:\\root, \\r\\n as text)', (await text2()) === 'Path C:\\root\\new and \\r\\n stay', JSON.stringify(await text2()));
  974. const v17 = await val2();
  975. check('#17: the value is the Markdown as typed (unchanged text is kept byte for byte)', v17 === 'Path C:\\root\\new and \\r\\n stay', JSON.stringify(v17));
  976. await page.click(S2 + ' footer button'); await sleep(300);
  977. await page.click(S2 + ' footer button'); await sleep(400);
  978. check('#17: that Markdown loaded again shows the same text', (await text2()) === 'Path C:\\root\\new and \\r\\n stay' && (await val2()) === v17, JSON.stringify([await text2(), await val2()]));
  979. await ev(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.collapseToEnd(); const dt = new DataTransfer(); dt.setData('text/plain', 'x\\r\\n\\r\\nfrom windows\\r\\nsecond line\\r\\n\\r\\n- C:\\\\root'); a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  980. await sleep(400);
  981. const v17b = await val2();
  982. check('#17: a pasted Windows text (CR LF) leaves no carriage return, its backslash + r stays', !v17b.includes('\r') && v17b.includes('from windows\nsecond line') && (await text2()).includes('C:\\root'), JSON.stringify(v17b));
  983. check('#17: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  984. await page.goto(BASE + '/md-editor');
  985. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  986. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  987. }
  988. // f3 (components): a value that changes from OUTSIDE after the editor was built (hl:web's rehydrate of kept state at an offline boot, a push from
  989. // another device) is shown by the editor, and the first key typed after it starts from the new text — not from the old surface
  990. {
  991. const S2 = 'md-editor:nth-of-type(2)';
  992. const valR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('input.value').value`);
  993. const artR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('article').innerHTML`);
  994. // an OLDER text of this very editor handed back (a note being saved answers with the server's version while the user has typed on) is not news
  995. await page.click(S2 + ' article'); await typeR('abc'); await sleep(300);
  996. await page.click('#md-stale'); await sleep(600);
  997. check('f3: an older text of the editor handed back keeps what was typed (surface and field), no key lost', (await artR(1)) === '<p>abc</p>' && (await valR(1)) === 'abc', JSON.stringify([await artR(1), await valR(1)]));
  998. await page.click(S2 + ' article p'); await keyR('End', 'End', 35); await typeR('d'); await sleep(300);
  999. check('f3: and typing goes on from it', (await valR(1)) === 'abcd', JSON.stringify(await valR(1)));
  1000. await page.click('#md-outside'); await sleep(600);
  1001. check('f3: a value set from outside is shown in the editor surface (formatted)', (await artR(1)) === '<h1>Outside 1</h1><p>set by <strong>the page</strong></p>', JSON.stringify(await artR(1)));
  1002. check('f3: and the field and the source view hold it too', (await valR(1)) === '# Outside 1\n\nset by **the page**' && (await ev(md2(`querySelector('textarea').value`))) === '# Outside 1\n\nset by **the page**');
  1003. await page.click(S2 + ' article h1'); await keyR('End', 'End', 35); await typeR('XY'); await sleep(300);
  1004. check('f3: the first keys after an outside change start from the new text', (await valR(1)) === '# Outside 1XY\n\nset by **the page**', JSON.stringify(await valR(1)));
  1005. check('f3: typing is not clobbered by the editor\'s own echo (every key kept)', (await artR(1)).startsWith('<h1>Outside 1XY</h1>'), JSON.stringify(await artR(1)));
  1006. await typeR('abcdefghijklmnopqrstuvwxyz0123456789'); await sleep(600);
  1007. check('f3: 36 fast keys after it all arrive, in order', (await valR(1)).startsWith('# Outside 1XYabcdefghijklmnopqrstuvwxyz0123456789'), JSON.stringify(await valR(1)));
  1008. await page.click('#md-outside'); await sleep(600);
  1009. check('f3: a second outside change replaces what was typed', (await artR(1)) === '<h1>Outside 2</h1><p>set by <strong>the page</strong></p>' && (await valR(1)) === '# Outside 2\n\nset by **the page**', JSON.stringify([await artR(1), await valR(1)]));
  1010. await page.click(S2 + ' footer button'); await sleep(300);
  1011. check('f3: the source view shows the outside value', (await ev(md2(`querySelector('textarea').value`))) === '# Outside 2\n\nset by **the page**');
  1012. await page.click('#md-outside'); await sleep(600);
  1013. check('f3: an outside change while the source view is open updates it', (await ev(md2(`querySelector('textarea').value`))) === '# Outside 3\n\nset by **the page**' && (await valR(1)) === '# Outside 3\n\nset by **the page**');
  1014. await page.click(S2 + ' footer button'); await sleep(300);
  1015. check('f3: back in the visual editor it shows the outside value', (await artR(1)) === '<h1>Outside 3</h1><p>set by <strong>the page</strong></p>', JSON.stringify(await artR(1)));
  1016. check('f3: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1017. await page.goto(BASE + '/md-editor');
  1018. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1019. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  1020. }
  1021. const wipe = async (i) => { await ev(`document.querySelectorAll('md-editor')[${i}].querySelector('article').focus()`); await keyR('a', 'KeyA', 65, undefined, 2); await keyR('Backspace', 'Backspace', 8); await sleep(150); };
  1022. const valR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('input.value').value`);
  1023. const artR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('article').innerHTML`);
  1024. await page.click('md-editor:nth-of-type(2) article');
  1025. await typeR('# Heading'); await sleep(200);
  1026. check('typing "# Heading" in an empty editor: heading, value "# Heading"', (await valR(1)) === '# Heading' && (await artR(1)) === '<h1>Heading</h1>', JSON.stringify([await valR(1), await artR(1)]));
  1027. await wipe(1);
  1028. await typeR('# Again'); await sleep(200);
  1029. check('typing "# " after the editor was emptied (an empty heading is left): "# Again", not "# # Again"', (await valR(1)) === '# Again', JSON.stringify(await valR(1)));
  1030. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1031. await typeR('- one'); await enterR(); await typeR('- two'); await sleep(200);
  1032. check('typing "- two" in a list item: the marker is consumed, value "- one\n- two"', (await valR(1)) === '- one\n- two', JSON.stringify([await valR(1), await artR(1)]));
  1033. await enterR(); await typeR('1. three'); await sleep(200);
  1034. check('typing "1. " in a bulleted list switches to a numbered list without the marker', !(await valR(1)).includes('1. 1.') && !/- 1\. three/.test(await valR(1)) && (await valR(1)).endsWith('three'), JSON.stringify(await valR(1)));
  1035. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1036. await typeR('1. a'); await enterR(); await typeR('2. b'); await sleep(200);
  1037. check('typing "2. b" in a numbered list: the marker is consumed, value "1. a\n2. b"', (await valR(1)) === '1. a\n2. b', JSON.stringify(await valR(1)));
  1038. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1039. await typeR('# One'); await enterR(); await typeR('text'); await enterR(); await typeR('## Two'); await sleep(200);
  1040. check('a heading, a paragraph and a second heading typed one after the other', (await valR(1)) === '# One\n\ntext\n\n## Two', JSON.stringify([await valR(1), await artR(1)]));
  1041. check('no console errors while typing shortcuts', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1042. // ==== mission 004 (creator notes#5): GITHUB PIPE TABLES in the Markdown editor — the behaviour of notes' md-editor.js (9acc27f),
  1043. // pure Hybriel. The demo's third editor ("plan") starts with a table; the second is typed into with real keys, one at a time.
  1044. await page.goto(BASE + '/md-editor');
  1045. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1046. await page.waitFor(`document.querySelectorAll('md-editor').length === 3 && document.querySelectorAll('md-editor')[2].querySelector('article h2') !== null`, { label: 'the third editor shows its value' });
  1047. // a setup step that cannot run (no table on old code) must not stop the gate: it answers null and the check after it fails
  1048. const evq = (e) => ev(e).catch(() => null);
  1049. const PLAN = '## Shopping\n\n| Item | Qty | Note \\| x |\n|:-----|:---:|---:|\n| **milk** | `2` | fresh |\n| bread | 1 | wholegrainsourdoughwithseedsfromthebakeryaroundthecorner |\n\nTab moves to the next cell, Enter adds a row.';
  1050. const tShape = (i) => ev(`(() => { const t = document.querySelectorAll('md-editor')[${i}].querySelector('article table'); if (!t) return null;
  1051. return { rows: [...t.querySelectorAll('tr')].map(tr => [...tr.children].map(c => c.tagName.toLowerCase() + ':' + c.innerHTML.replaceAll('\\u200b', ''))),
  1052. align: [...t.querySelector('tr').children].map(c => (c.getAttribute('data-align') || '') + '/' + getComputedStyle(c).textAlign),
  1053. before: t.previousElementSibling && t.previousElementSibling.outerHTML, after: t.nextElementSibling && t.nextElementSibling.outerHTML } })()`);
  1054. const s0 = await tShape(2).catch(() => null);
  1055. check('tables: a pipe table in a value shows as a table — header cells, the delimiter row\'s alignment (data-align + computed text-align), **bold** / `code` in cells, `\\|` a pipe in a cell',
  1056. s0 && JSON.stringify(s0.rows) === JSON.stringify([['th:Item', 'th:Qty', 'th:Note | x'], ['td:<strong>milk</strong>', 'td:<code>2</code>', 'td:fresh'], ['td:bread', 'td:1', 'td:wholegrainsourdoughwithseedsfromthebakeryaroundthecorner']])
  1057. && s0.align.join(' ') === 'left/left center/center right/right' && s0.before === '<h2>Shopping</h2>' && s0.after === '<p>Tab moves to the next cell, Enter adds a row.</p>', JSON.stringify(s0));
  1058. check('tables: an untouched table is the same Markdown byte for byte', (await valR(2)) === PLAN, JSON.stringify(await valR(2)));
  1059. await evq(`(() => { const a = document.querySelectorAll('md-editor')[2].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a.querySelector('table').nextElementSibling); s.collapseToEnd(); })()`);
  1060. await typeR(' More.'); await sleep(200);
  1061. check('tables: text typed next to a table leaves the unchanged table byte for byte (its own spelling, not re-padded)', (await valR(2)) === PLAN + ' More.', JSON.stringify(await valR(2)));
  1062. // one cell edited: only that row changes in the Markdown (written in the canonical padded form, the other cells the same)
  1063. await evq(`(() => { const a = document.querySelectorAll('md-editor')[2].querySelector('article'); const c = a.querySelectorAll('tbody td')[2]; const s = getSelection(); s.selectAllChildren(c); s.collapseToEnd(); })()`);
  1064. await typeR('!'); await sleep(200);
  1065. const v3 = await valR(2);
  1066. const mdCells = (l) => l.split(/(?<!\\)\|/).slice(1, -1).map(c => c.trim());
  1067. const tl3 = v3.split('\n').filter(l => l.startsWith('|'));
  1068. check('tables: editing one cell changes only that cell (the table is written in the canonical form, every other cell the same)',
  1069. v3.startsWith('## Shopping\n\n| Item ') && v3.endsWith('|\n\nTab moves to the next cell, Enter adds a row. More.') && JSON.stringify(tl3.map(mdCells)) === JSON.stringify([['Item', 'Qty', 'Note \\| x'], [':-------', ':-:', '-'.repeat(55) + ':'], ['**milk**', '`2`', 'fresh!'], ['bread', '1', 'wholegrainsourdoughwithseedsfromthebakeryaroundthecorner']])
  1070. && new Set(tl3.map(l => l.length)).size === 1, JSON.stringify(v3));
  1071. // typing a table with real keys in the (emptied) second editor
  1072. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1073. const tab = (shift) => keyR('Tab', 'Tab', 9, undefined, shift ? 8 : 0);
  1074. const caretCell = () => ev(`(() => { const s = getSelection(); const n = s.anchorNode; const c = n && (n.nodeType === 1 ? n : n.parentNode).closest('td, th'); if (!c) return (n && (n.nodeType === 1 ? n : n.parentNode).tagName) || '-'; const t = c.closest('table'); return c.tagName + [...t.querySelectorAll('th, td')].indexOf(c) })()`);
  1075. await typeR('Before the table'); await enterR();
  1076. await typeR('| Item | Qty | Note \\| x |'); await enterR();
  1077. await typeR('|:---|:---:|---:|'); await enterR(); await sleep(200);
  1078. const s1 = await tShape(1);
  1079. check('tables: typing a header row, Enter, `|:---|:---:|---:|`, Enter turns the two lines into a table with an empty row, the caret in its first cell',
  1080. s1 && JSON.stringify(s1.rows) === JSON.stringify([['th:Item', 'th:Qty', 'th:Note | x'], ['td:<br>', 'td:<br>', 'td:<br>']]) && (await caretCell()) === 'TD3', JSON.stringify([s1, await caretCell()]));
  1081. await typeR('**milk**'); await tab(); await typeR('`2`'); await tab(); await typeR('a|b'); await enterR();
  1082. check('tables: Tab moves to the next cell, Enter in a cell adds a row below (the caret in its first cell)', (await caretCell()) === 'TD6', await caretCell());
  1083. await typeR('bread'); await tab(); await typeR('1'); await tab(); await typeR('wholegrain-sourdough-with-seeds-and-a-very-long-name'); await enterR();
  1084. await enterR(); await sleep(150);
  1085. check('tables: Enter in the empty last row leaves the table (the row goes, the caret in the paragraph after it)', (await caretCell()) === 'P' && ((await tShape(1)) || { rows: [] }).rows.length === 3, JSON.stringify([await caretCell(), await tShape(1)]));
  1086. await typeR('after the table'); await enterR(); await typeR('a | b stays text'); await sleep(300);
  1087. const s2 = await tShape(1);
  1088. check('tables: the typed cells — **bold**, `code`, a typed pipe, a long word; the alignment of the delimiter row',
  1089. s2 && JSON.stringify(s2.rows) === JSON.stringify([['th:Item', 'th:Qty', 'th:Note | x'], ['td:<strong>milk</strong>', 'td:<code>2</code>', 'td:a|b'], ['td:bread', 'td:1', 'td:wholegrain-sourdough-with-seeds-and-a-very-long-name']])
  1090. && s2.align.join(' ') === 'left/left center/center right/right', JSON.stringify(s2));
  1091. check('tables: the paragraphs around the typed table stay paragraphs ("a | b stays text" is no table)', s2 && s2.before === '<p>Before the table</p>' && s2.after === '<p>after the table</p>'
  1092. && (await ev(`document.querySelectorAll('md-editor')[1].querySelectorAll('article table').length`)) === 1 && /<p>a \| b stays text<\/p>$/.test(await artR(1)), JSON.stringify([s2, await artR(1)]));
  1093. const W = [8, 3, 52], prow = (cells) => '| ' + cells.map((c, k) => c.padEnd(W[k])).join(' | ') + ' |';
  1094. const TYPED = ['Before the table', '', prow(['Item', 'Qty', 'Note \\| x']), '| :' + '-'.repeat(7) + ' | :-: | ' + '-'.repeat(51) + ': |', prow(['**milk**', '`2`', 'a\\|b']),
  1095. prow(['bread', '1', 'wholegrain-sourdough-with-seeds-and-a-very-long-name']), '', 'after the table', '', 'a | b stays text'].join('\n');
  1096. check('tables: the Markdown of the typed table — padded GitHub pipe table, `| :--- | :-: | --: |`, `\\|` for a pipe in a cell', (await valR(1)) === TYPED, JSON.stringify(await valR(1)));
  1097. // Shift+Tab back; Tab in the last cell adds a row
  1098. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = a.querySelector('tbody td'); a.focus(); const s = getSelection(); s.selectAllChildren(c); s.collapseToEnd(); })()`);
  1099. await tab(true);
  1100. check('tables: Shift+Tab moves to the cell before (here: the last header cell)', (await caretCell()) === 'TH2', await caretCell());
  1101. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = [...a.querySelectorAll('td')].pop(); const s = getSelection(); s.selectAllChildren(c); s.collapseToEnd(); })()`);
  1102. await tab(); await typeR('x'); await sleep(150);
  1103. check('tables: Tab in the last cell adds a row (the caret in its first cell)', ((await tShape(1)) || { rows: [] }).rows.length === 4 && /\n\| x {8}\| {5}\| {54}\|\n\nafter the table/.test(await valR(1)), JSON.stringify(await valR(1)));
  1104. // Backspace / Delete never merge a table with the text around it
  1105. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const p = a.querySelector('table').nextElementSibling; const s = getSelection(); s.collapse(p.firstChild, 0); })()`);
  1106. const before1 = await valR(1);
  1107. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1108. check('tables: Backspace at the start of the paragraph after a table does not merge it (the caret goes to the last cell)', (await valR(1)) === before1 && (await caretCell()) === 'TD11', JSON.stringify([await valR(1), await caretCell()]));
  1109. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const p = a.querySelector('p'); const s = getSelection(); s.collapse(p.firstChild, p.firstChild.length); })()`);
  1110. await keyR('Delete', 'Delete', 46); await sleep(150);
  1111. check('tables: Delete at the end of the paragraph before a table does not merge it', (await valR(1)) === before1, JSON.stringify(await valR(1)));
  1112. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = a.querySelector('th'); const s = getSelection(); s.collapse(c.firstChild, 0); })()`);
  1113. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1114. check('tables: Backspace at the start of the first cell does nothing (no merge with the paragraph before)', (await valR(1)) === before1, JSON.stringify(await valR(1)));
  1115. // a selection from the paragraph before into the table: the text is cut, the selected cells emptied, the table stays
  1116. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const p = a.querySelector('p'); const c = a.querySelectorAll('tbody td')[0]; const r = document.createRange(); r.setStart(p.firstChild, 6); r.setEnd(c, c.childNodes.length); const s = getSelection(); s.removeAllRanges(); s.addRange(r); })()`);
  1117. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1118. const s3 = await tShape(1);
  1119. check('tables: Backspace on a selection from the text into a table cuts the text, empties the selected cells, keeps the table (nothing merged)',
  1120. s3 && s3.before === '<p>Before</p>' && JSON.stringify(s3.rows[0]) === JSON.stringify(['th:<br>', 'th:<br>', 'th:<br>']) && s3.rows[1][0] === 'td:<br>' && s3.rows[1][1] === 'td:<code>2</code>' && s3.rows.length === 4, JSON.stringify(s3));
  1121. // the Markdown source switch and back: the same table
  1122. const v4 = await valR(1);
  1123. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  1124. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  1125. check('tables: the source view and back give the same table and the same Markdown', (await valR(1)) === v4 && JSON.stringify(((await tShape(1)) || {}).rows) === JSON.stringify((s3 || {}).rows) && s3 != null, JSON.stringify([await valR(1), v4]));
  1126. // a pasted HTML table (a spreadsheet, a web page) becomes a table: its cells' text, align / text-align, the widest row
  1127. await evq(`(() => { const a = document.querySelectorAll('md-editor')[0].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.collapseToEnd();
  1128. const dt = new DataTransfer(); dt.setData('text/html', '<meta charset="utf-8"><table><thead><tr><th>Name</th><th align="right">Price</th></tr></thead><tbody><tr><td>Tea <b>*green*</b></td><td style="text-align:right">3|4</td></tr><tr><td>Cake</td></tr></tbody></table><p>tail <img src=x onerror="window.__pwn=1"></p>'); dt.setData('text/plain', 'Name\\tPrice');
  1129. a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1130. await sleep(400);
  1131. check('tables: a pasted HTML table becomes a table (cells as text, `\\|` / `\\*` escaped, alignment kept, short rows padded); nothing else of the HTML is taken',
  1132. (await valR(0)).endsWith('- second\n\n| Name | Price |\n| ------------- | ----: |\n| Tea \\*green\\* | 3\\|4 |\n| Cake | |\n\ntail') && (await ev('window.__pwn')) == null && (await ev(`document.querySelectorAll('md-editor')[0].querySelectorAll('article img').length`)) === 0, JSON.stringify(await valR(0)));
  1133. // pasted Markdown with a table in it (plain text) becomes a table too
  1134. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1135. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); a.focus(); const dt = new DataTransfer(); dt.setData('text/plain', 'x\\n\\n| a | b |\\n|---|---|\\n| 1 | 2 |'); a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1136. await sleep(300);
  1137. check('tables: pasted Markdown with a pipe table shows it as a table (and keeps its spelling while unchanged)', JSON.stringify((await tShape(1) || {}).rows) === JSON.stringify([['th:a', 'th:b'], ['td:1', 'td:2']]) && (await valR(1)) === 'x\n\n| a | b |\n|---|---|\n| 1 | 2 |', JSON.stringify([await valR(1), await artR(1)]));
  1138. check('tables: no console errors while typing and pasting tables', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1139. // the look at 1280 and on a phone: thin grey lines, no colour; a wide table scrolls inside its box, the page does not
  1140. await page.goto(BASE + '/md-editor');
  1141. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1142. await page.waitFor(`document.querySelectorAll('md-editor')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  1143. const look = await evq(`(() => { const c = getComputedStyle(document.querySelectorAll('md-editor')[2].querySelector('article td')); return c.borderTopWidth + ' ' + c.paddingLeft })()`);
  1144. check("tables: the editor draws no cell borders of its own (the page's theme styles the table) and keeps the plain cell padding where no theme does", look === '0px 9.6px', look);
  1145. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1146. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  1147. await shot('md-editor-table-1280');
  1148. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  1149. await page.goto(BASE + '/md-editor');
  1150. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1151. await page.waitFor(`document.querySelectorAll('md-editor')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  1152. const ph = (await evq(`(() => { const t = document.querySelectorAll('md-editor')[2].querySelector('article table'); const e = t.closest('md-editor').getBoundingClientRect(); const b = t.getBoundingClientRect(); return { page: document.documentElement.scrollWidth <= window.innerWidth, scrolls: t.scrollWidth > t.clientWidth + 20, inside: b.right <= e.right + 0.5 && b.left >= e.left - 0.5 } })()`)) || {};
  1153. check('tables on a phone (390 px): the wide table scrolls inside its box, the page does not scroll sideways', ph.page && ph.scrolls && ph.inside, JSON.stringify(ph));
  1154. // E2: an app theme sets a smaller `th` size (notes: .85rem); on a phone the editor's table head is 16 px, the body's size
  1155. await ev(`(() => { const st = document.createElement('style'); st.id = 'e2-theme'; st.textContent = 'th { font-size: .85rem }'; document.head.appendChild(st); })()`);
  1156. const e2th = await ev(`(() => { const t = document.querySelectorAll('md-editor')[2].querySelector('article table'); return { th: parseFloat(getComputedStyle(t.querySelector('th')).fontSize), td: parseFloat(getComputedStyle(t.querySelector('td')).fontSize) }; })()`);
  1157. await ev(`document.getElementById('e2-theme').remove()`);
  1158. check('E2: at 390 px the table head text is at least 14 px (16 px, the body size) even under a theme `th` of .85rem', e2th.th >= 14 && e2th.th === e2th.td, JSON.stringify(e2th));
  1159. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  1160. await shot('md-editor-table-390');
  1161. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1162. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1163. await page.goto(BASE + '/md-editor'); await sleep(800);
  1164. check('the Markdown editor fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1165. await shot('md-editor-narrow');
  1166. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1167. // ==== mission 011: THE EDITOR'S REAL KEYS (tests/md-keys.mjs) — headings, lists, tables after lists, Ctrl+B/I/E/K, code blocks, source switch; at 390 and 1280
  1168. {
  1169. for (const w of [390, 1280]) {
  1170. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: w === 390 });
  1171. await page.goto(BASE + '/md-editor');
  1172. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1173. await mdKeys(page, { base: BASE, check, sleep, label: String(w) });
  1174. await mdPaste(page, { check, sleep, label: String(w) });
  1175. }
  1176. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1177. }
  1178. // ==== mission 011 END
  1179. // ticket #9: files and images in the Markdown editor (drop, paste, choose) go through emit, with progress, and land in the text
  1180. {
  1181. await page.goto(BASE + '/md-editor');
  1182. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1183. await sleep(600);
  1184. const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
  1185. const mkFiles = `const png = Uint8Array.from(atob('${PNG}'), c => c.charCodeAt(0)); const big = new Uint8Array(3145728).fill(65); const dt = new DataTransfer(); dt.items.add(new File([png], 'one.png', { type: 'image/png' })); dt.items.add(new File([png], 'two.png', { type: 'image/png' })); dt.items.add(new File([big], 'doc.pdf', { type: 'application/pdf' }));`;
  1186. await ev(`(() => { const ed = document.querySelectorAll('md-editor')[1]; window.__rows = []; window.__max = 0; new MutationObserver(() => { const l = ed.querySelector('ul.files'); window.__rows.push(l.children.length); const p = l.querySelector('progress'); if (p && p.max > 1) window.__max = Math.max(window.__max, p.value / p.max) }).observe(ed.querySelector('ul.files'), { subtree: true, attributes: true, childList: true }); const a = ed.querySelector('article'); a.focus(); ${mkFiles} a.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 50, clientY: 50 })); })()`);
  1187. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("doc.pdf")', { timeout: 30000, label: 'files uploaded' });
  1188. const v = await ev(md2(`querySelector('input.value').value`));
  1189. check('three dropped files: two images and a link in the Markdown', /^!\[one\.png\]\(\/md-editor\/files\/[\w.-]+\.png\)\n\n!\[two\.png\]\(\/md-editor\/files\/[\w.-]+\.png\)\n\n\[doc\.pdf\]\(\/md-editor\/files\/[\w.-]+\.pdf\)$/.test(v), JSON.stringify(v));
  1190. check('the editor shows two images and a link', (await ev(md2(`querySelectorAll('article img').length`))) === 2 && (await ev(md2(`querySelectorAll('article a').length`))) === 1);
  1191. check('the images load (the app stored and serves them)', await ev(`new Promise(r => setTimeout(() => r([...document.querySelectorAll('md-editor')[1].querySelectorAll('article img')].every(i => i.complete && i.naturalWidth === 1)), 500))`));
  1192. check('progress rows were shown, three files, and reached 100%', (await ev('Math.max(...window.__rows)')) === 3 && (await ev('window.__max')) >= 1, JSON.stringify(await ev('[window.__rows.length, window.__max]')));
  1193. check('progress rows are gone afterwards', (await ev(md2(`querySelector('ul.files').children.length`))) === 0);
  1194. const url = v.match(/\]\((\/md-editor\/files\/[\w.-]+\.pdf)\)/)[1];
  1195. const got = await fetch(BASE + url);
  1196. check('the stored file is served, not sniffed, sandboxed', got.ok && (await got.arrayBuffer()).byteLength === 3145728 && got.headers.get('x-content-type-options') === 'nosniff' && /sandbox/.test(got.headers.get('content-security-policy') || ''));
  1197. // a pasted image lands too, at the caret
  1198. await ev(`(() => { const a = document.querySelectorAll('md-editor')[0].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.collapseToEnd(); ${mkFiles.replace("dt.items.add(new File([png], 'two.png', { type: 'image/png' }));", '').replace("dt.items.add(new File([big], 'doc.pdf', { type: 'application/pdf' }));", '')} a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1199. await page.waitFor(md1(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'pasted image' });
  1200. check('a pasted image is added too', true);
  1201. // an image in typed-in Markdown is drawn; only http(s) and site paths are images
  1202. await ev(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); a.focus(); const dt = new DataTransfer(); dt.setData('text/plain', '![a](/x.png) ![b](javascript:alert(1)) ![c](data:image/png;base64,AAAA)'); a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1203. await sleep(300);
  1204. const srcs = await ev(`JSON.stringify([...document.querySelectorAll('md-editor')[1].querySelectorAll('article img')].map(i => i.getAttribute('src')))`);
  1205. check('javascript: and data: images are not made', !srcs.includes('javascript') && !srcs.includes('data:') && srcs.includes('/x.png'), srcs);
  1206. // ticket #12: a file added (dropped, pasted, chosen) with the caret at the end of a list item is its own block after the list
  1207. {
  1208. const one = mkFiles.replace("dt.items.add(new File([png], 'two.png', { type: 'image/png' }));", '').replace(/dt\.items\.add\(new File\(\[big\][^;]*;/, '');
  1209. const fire = {
  1210. drop: `a.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 0, clientY: 0 }));`,
  1211. paste: `a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));`,
  1212. choose: `const inp = ed.querySelector('input.pick'); inp.files = dt.files; inp.dispatchEvent(new Event('change', { bubbles: true }));`,
  1213. };
  1214. for (const way of ['drop', 'paste', 'choose']) {
  1215. for (const caret of ['in item', 'none']) {
  1216. await ev(`(() => { const ed = document.querySelectorAll('md-editor')[1]; const a = ed.querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.deleteFromDocument(); const dt = new DataTransfer(); dt.setData('text/plain', '- first\\n- second'); a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1217. await sleep(300);
  1218. await ev(`(() => { const ed = document.querySelectorAll('md-editor')[1]; const a = ed.querySelector('article'); ${caret === 'none' ? 's0' : ''} const li = a.querySelector('li:last-child'); a.focus(); const s = getSelection(); if (${caret === 'none'}) s.removeAllRanges(); else { s.selectAllChildren(li); s.collapseToEnd(); } ${one} ${fire[way]} })()`.replace('s0', ''));
  1219. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'list ' + way });
  1220. const lv = await ev(md2(`querySelector('input.value').value`));
  1221. check(`an image (${way}, caret ${caret}) after the last list item is its own block`, /^- first\n- second\n\n!\[one\.png\]\(\/md-editor\/files\/[\w.-]+\.png\)$/.test(lv), JSON.stringify(lv));
  1222. }
  1223. }
  1224. }
  1225. check('no console errors on files/images', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1226. await shot('md-editor-files');
  1227. }
  1228. // the code editor: real keys, real typing
  1229. {
  1230. check('home lists the code editor', home.includes('id="open-code-editor"'));
  1231. const cer = await fetch(BASE + '/code-editor/README.md');
  1232. check('Code editor README is served as Markdown', cer.ok && /markdown/.test(cer.headers.get('content-type')) && (await cer.text()).includes('Code editor'));
  1233. check('no .js of its own in components/code-editor', !execSync(`find ${join(APP, 'components/code-editor')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  1234. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1235. await page.goto(BASE + '/code-editor');
  1236. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1237. const CE = (i, q) => `document.querySelectorAll('code-editor')[${i}].${q}`;
  1238. const cval = (i) => ev(CE(i, `querySelector('input.value').value`));
  1239. const ctext = (i) => ev(CE(i, `querySelector('article').textContent`));
  1240. const cgut = (i) => ev(CE(i, `querySelector('code-gutter').textContent`));
  1241. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  1242. check('Hybriel code is highlighted: comment, keyword, string, function', await ev(`['comment','keyword','string','function'].every(k => ${CE(0, `querySelector('article .tok-' + k)`)} !== null)`));
  1243. check('JavaScript is highlighted too: number, comment, string', await ev(`['comment','string','number','keyword'].every(k => ${CE(1, `querySelector('article .tok-' + k)`)} !== null)`));
  1244. check('the keyword is coloured differently from the plain text', await ev(`getComputedStyle(${CE(0, `querySelector('article .tok-keyword')`)}).color !== getComputedStyle(${CE(0, `querySelector('article')`)}).color`));
  1245. check('line numbers: 1..10 for the ten lines', (await cgut(0)) === '1\n2\n3\n4\n5\n6\n7\n8\n9\n10', JSON.stringify(await cgut(0)));
  1246. check('the value is the plain text (no markup)', (await cval(0)).startsWith('// a Hybriel component\nString title') && !(await cval(0)).includes('<span'));
  1247. const ckey = async (k, code, vk, text, mods = 0) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, text, modifiers: mods }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, modifiers: mods }); };
  1248. const ctype = async (t) => { for (const ch of t) { if (ch === '\n') await ckey('Enter', 'Enter', 13, '\r'); else await ckey(ch, '', undefined, ch); } };
  1249. const CTRL = 2, SHIFT = 8;
  1250. const tab = (shift) => ckey('Tab', 'Tab', 9, undefined, shift ? SHIFT : 0);
  1251. const undo = () => ckey('z', 'KeyZ', 90, undefined, CTRL);
  1252. const redo = () => ckey('z', 'KeyZ', 90, undefined, CTRL | SHIFT);
  1253. // put the caret at text offsets (start..end) of editor i and focus it
  1254. const caret = (i, s, e = s) => ev(`(()=>{const a=${CE(i, `querySelector('article')`)};a.focus();const w=document.createTreeWalker(a,4);let pos=0,sn=null,so=0,en=null,eo=0,n;while((n=w.nextNode())){const l=n.data.length;if(!sn&&${s}<=pos+l){sn=n;so=${s}-pos}if(!en&&${e}<=pos+l){en=n;eo=${e}-pos}pos+=l}getSelection().setBaseAndExtent(sn,so,en,eo)})()`);
  1255. await caret(0, (await cval(0)).length);
  1256. await ctype('\nlet n = 5');
  1257. check('typing at the end: the value follows, the new line is numbered 11', (await cval(0)).endsWith('}\nlet n = 5') && (await cgut(0)).endsWith('\n11'), JSON.stringify((await cval(0)).slice(-20)) + ' / ' + JSON.stringify((await cgut(0)).slice(-8)));
  1258. check('the word you typed is highlighted while typing (let = keyword, 5 = number)', await ev(`(()=>{const k=[...${CE(0, `querySelectorAll('article .tok-keyword')`)}].map(x=>x.textContent);const n=[...${CE(0, `querySelectorAll('article .tok-number')`)}].map(x=>x.textContent);return k.includes('let')&&n.includes('5')})()`));
  1259. check('the demo shows that text below the editor', (await ev(`document.getElementById('code-value-hybriel').textContent`)) === (await cval(0)));
  1260. check('the other editor was not touched', (await cval(1)).startsWith('function add(a, b) {'));
  1261. // Tab / Shift+Tab on one line
  1262. await ctype('\n'); await tab(false); await ctype('x');
  1263. check('Tab inserts a tab character', (await cval(0)).endsWith('let n = 5\n\tx'), JSON.stringify((await cval(0)).slice(-14)));
  1264. await tab(true);
  1265. check('Shift+Tab removes it again', (await cval(0)).endsWith('let n = 5\nx'), JSON.stringify((await cval(0)).slice(-14)));
  1266. // Enter keeps the indent; { closes itself; Enter between the braces opens an indented line
  1267. await ctype('\n'); await tab(false); await ctype('if (a) {');
  1268. check('typing { adds the closing }', (await cval(0)).endsWith('\tif (a) {}'), JSON.stringify((await cval(0)).slice(-14)));
  1269. await ctype('\n');
  1270. check('Enter between { } indents the new line and puts } on its own line', (await cval(0)).endsWith('\tif (a) {\n\t\t\n\t}'), JSON.stringify((await cval(0)).slice(-20)));
  1271. await ctype('y'); await ctype('\n');
  1272. check('Enter keeps the indent of the line', (await cval(0)).endsWith('\tif (a) {\n\t\ty\n\t\t\n\t}'), JSON.stringify((await cval(0)).slice(-24)));
  1273. // typing the closer steps over it; a quote closes itself
  1274. await ckey('Backspace', 'Backspace', 8); await ckey('Backspace', 'Backspace', 8); await ctype('call("a"');
  1275. check('quotes close themselves and typing the closing quote / ) steps over it', (await cval(0)).includes('\ncall("a")'), JSON.stringify((await cval(0)).slice(-20)));
  1276. // undo / redo: back through typing, then forward again
  1277. const before = await cval(0);
  1278. await undo(); await sleep(50);
  1279. const u1 = await cval(0);
  1280. check('Ctrl+Z undoes the last change', u1 !== before && u1.length < before.length + 4, JSON.stringify(u1.slice(-20)));
  1281. await undo(); await undo(); await sleep(50);
  1282. const u3 = await cval(0);
  1283. check('Ctrl+Z again goes further back', u3.length < u1.length, JSON.stringify(u3.slice(-20)));
  1284. await redo(); await redo(); await redo(); await sleep(50);
  1285. check('Ctrl+Shift+Z redoes them: the text is back', (await cval(0)) === before, JSON.stringify((await cval(0)).slice(-20)));
  1286. await ckey('y', 'KeyY', 89, undefined, CTRL);
  1287. check('Ctrl+Z past the start stops at the first text', await (async () => { for (let i = 0; i < 80; i++) await undo(); return (await cval(0)).startsWith('// a Hybriel component') && !(await cval(0)).includes('let n'); })());
  1288. check('the line numbers follow undo', (await cgut(0)) === '1\n2\n3\n4\n5\n6\n7\n8\n9\n10', JSON.stringify(await cgut(0)));
  1289. // several lines selected: Tab indents all, Shift+Tab outdents all
  1290. const v0 = await cval(0);
  1291. await caret(0, 0, v0.length);
  1292. await tab(false);
  1293. check('Tab with several lines selected indents every non-empty line', (await cval(0)) === v0.split('\n').map(l => l === '' ? l : '\t' + l).join('\n'), JSON.stringify((await cval(0)).slice(0, 60)));
  1294. await tab(true);
  1295. check('Shift+Tab outdents them all again', (await cval(0)) === v0, JSON.stringify((await cval(0)).slice(0, 60)));
  1296. // the second editor indents with two spaces
  1297. const w0 = await cval(1);
  1298. await caret(1, 0); await tab(false);
  1299. check('spaces = 2: Tab inserts two spaces', (await cval(1)) === ' ' + w0, JSON.stringify((await cval(1)).slice(0, 30)));
  1300. await tab(true);
  1301. check('spaces = 2: Shift+Tab removes them', (await cval(1)) === w0);
  1302. // text inserted as a whole (paste): several lines, highlighted, numbered
  1303. await caret(1, (await cval(1)).length);
  1304. await ev(`(()=>{const a=${CE(1, `querySelector('article')`)};const dt=new DataTransfer();dt.setData('text/plain','\\n// pasted\\nlet z = 1');a.dispatchEvent(new ClipboardEvent('paste',{clipboardData:dt,bubbles:true,cancelable:true}))})()`);
  1305. await sleep(150);
  1306. check('inserted text (paste) is taken over, highlighted and numbered', (await cval(1)).endsWith('\n// pasted\nlet z = 1') && (await cgut(1)).split('\n').length === (await cval(1)).split('\n').length && (await ev(CE(1, `querySelectorAll('article .tok-comment').length`))) === 2, JSON.stringify(await cval(1)) + ' / ' + JSON.stringify(await cgut(1)));
  1307. // the form posts both by name
  1308. await page.click('#code-form button[type=submit]'); await sleep(800);
  1309. const curl = new URL(await ev('location.href'));
  1310. check('the form posts both texts by name', curl.searchParams.get('hybriel') != null && curl.searchParams.get('hybriel').replaceAll('\r\n', '\n') === v0 && curl.searchParams.get('js').includes('let z = 1'), curl.search.slice(0, 120));
  1311. // the code is only ever text: broken / hostile code shows literally, the page structure stays, nothing runs
  1312. await page.goto(BASE + '/code-editor');
  1313. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1314. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  1315. const shape = () => ev(`[...document.body.querySelectorAll('*')].filter(e => !e.closest('article')).length + ':' + document.querySelectorAll('code-editor').length + ':' + document.querySelectorAll('pre').length + ':' + [...document.querySelectorAll('b,img,div')].filter(e => !e.closest('main')).length + ':' + document.querySelectorAll('main b, main img, main div').length`);
  1316. const shape0 = await shape();
  1317. await caret(1, (await cval(1)).length);
  1318. await ctype('\nif (x) {');
  1319. await sleep(300);
  1320. check('unbalanced code renders inside the field as typed', (await cval(1)).includes('if (x) {}') && (await shape()) === shape0, await shape() + ' vs ' + shape0);
  1321. await ctype('\n'); await ctype('}');
  1322. check('typing } after Enter inside { } does not leave two: if (x) {\\n} only', (await cval(1)).endsWith('if (x) {\n}'), JSON.stringify((await cval(1)).slice(-20)));
  1323. await ev(`window.__pwned = undefined`);
  1324. await ctype('\n</div><b>x');
  1325. await ctype('\n<img src=x onerror=window.__pwned=1>');
  1326. await sleep(500);
  1327. check('markup typed is shown literally and the page structure is unchanged', (await cval(1)).includes('</div><b>x') && (await ctext(1)).includes('<img src=x onerror=window.__pwned=1>') && (await shape()) === shape0, await shape() + ' vs ' + shape0);
  1328. check('the code below the editor shows it literally too', (await ev(`document.getElementById('code-value-js').textContent`)).includes('<img src=x onerror=window.__pwned=1>'));
  1329. check('typed code did not run (window.__pwned stays undefined)', (await ev(`typeof window.__pwned`)) === 'undefined');
  1330. await page.goto(BASE + '/code-editor'); await sleep(800);
  1331. await page.goto(BASE + '/code-editor'); await sleep(800);
  1332. await shot('code-editor');
  1333. check('no console errors on the code editor page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1334. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1335. await page.goto(BASE + '/code-editor'); await sleep(800);
  1336. check('the code editor page fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1337. await shot('code-editor-narrow');
  1338. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1339. }
  1340. // ticket #13: the modal — open by the page, every way to close it with its reason, focus kept inside and given back, no scroll behind
  1341. {
  1342. check('home lists the modal', home.includes('id="open-modal"'));
  1343. const mor = await fetch(BASE + '/modal/README.md');
  1344. check('modal README is served as Markdown', mor.ok && /markdown/.test(mor.headers.get('content-type')) && (await mor.text()).includes('# Modal'));
  1345. check('no .js of its own in components/modal', !execSync(`find ${join(APP, 'components/modal')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  1346. const modalRun = async (w, h, mobile, tag) => {
  1347. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile });
  1348. await page.goto(BASE + '/modal');
  1349. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1350. await sleep(500);
  1351. const at = async (x, y) => {
  1352. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
  1353. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
  1354. await sleep(60);
  1355. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
  1356. await sleep(300);
  1357. };
  1358. const on = async (sel) => { const r = await ev(`(() => { const b = document.querySelector(${JSON.stringify(sel)}).getBoundingClientRect(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; })()`); await at(r.x, r.y); };
  1359. const mkey = async (k, code, vk, mods = 0) => { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: k, code, windowsVirtualKeyCode: vk, modifiers: mods }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, modifiers: mods }); await sleep(150); };
  1360. const openIds = () => ev(`[...document.querySelectorAll('dialog[open]')].map(d => d.id).join()`);
  1361. const last = () => ev(`document.getElementById('modal-last').textContent`);
  1362. const active = () => ev(`document.activeElement.id || document.activeElement.className || document.activeElement.tagName`);
  1363. const inside = (id) => ev(`document.getElementById(${JSON.stringify(id)}).contains(document.activeElement)`);
  1364. // a corner of the dim background, outside every window
  1365. const bg = async () => at(4, h - 4);
  1366. check(`modal ${tag}: closed at first (no dialog open)`, (await openIds()) === '' && (await ev(`getComputedStyle(document.getElementById('info')).display`)) === 'none');
  1367. // open by the page's button: title, content, focus inside, page inert behind
  1368. await on('#open-info');
  1369. check(`modal ${tag}: the page's button opens it (title and content shown)`, (await openIds()) === 'info' && (await ev(`document.querySelector('#info h2').textContent`)) === 'Information' && (await ev(`document.querySelector('#info modal-body p').getBoundingClientRect().height > 0`)));
  1370. check(`modal ${tag}: the focus is inside when it opens`, await inside('info'), await active());
  1371. const box = await ev(`JSON.stringify(document.getElementById('info').getBoundingClientRect())`);
  1372. const b = JSON.parse(box);
  1373. check(`modal ${tag}: the window is inside the screen`, b.left >= 0 && b.top >= 0 && b.right <= w && b.bottom <= h, box);
  1374. check(`modal ${tag}: the page behind is blocked (the element under a point outside is the dialog, not the page)`, await ev(`document.elementFromPoint(4, ${h - 4}) === document.getElementById('info')`));
  1375. await shot(`modal-open-${w}`);
  1376. // Esc
  1377. await mkey('Escape', 'Escape', 27);
  1378. check(`modal ${tag}: Esc closes it, reason "escape", focus back on the opener`, (await openIds()) === '' && (await last()) === 'info: escape' && (await active()) === 'open-info', `${await openIds()} / ${await last()} / ${await active()}`);
  1379. // ×
  1380. await on('#open-info'); await on('#info .modal-x');
  1381. check(`modal ${tag}: × closes it, reason "close", focus back on the opener`, (await openIds()) === '' && (await last()) === 'info: close' && (await active()) === 'open-info', `${await openIds()} / ${await last()} / ${await active()}`);
  1382. // the dim background
  1383. await on('#open-info'); await bg();
  1384. check(`modal ${tag}: a click on the dim background closes it, reason "backdrop"`, (await openIds()) === '' && (await last()) === 'info: backdrop' && (await active()) === 'open-info', `${await openIds()} / ${await last()} / ${await active()}`);
  1385. // a press inside the window that ends on the background (a text selection dragged out) does not close it
  1386. await on('#open-info');
  1387. const p = await ev(`(() => { const r = document.querySelector('#info modal-body p').getBoundingClientRect(); return { x: r.x + 5, y: r.y + 5 }; })()`);
  1388. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: p.x, y: p.y, button: 'none' });
  1389. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: p.x, y: p.y, button: 'left', clickCount: 1 });
  1390. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 4, y: h - 4, button: 'left' });
  1391. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 4, y: h - 4, button: 'left', clickCount: 1 });
  1392. await sleep(300);
  1393. check(`modal ${tag}: a press started inside and let go on the background keeps it open`, (await openIds()) === 'info');
  1394. await mkey('Escape', 'Escape', 27);
  1395. // footer buttons: the value is the reason
  1396. await on('#open-confirm');
  1397. check(`modal ${tag}: footer buttons are shown`, (await ev(`[...document.querySelectorAll('#confirm footer button')].map(b => b.textContent).join()`)) === 'Cancel,Delete');
  1398. check(`modal ${tag}: footer buttons have no border (creator's rule)`, await ev(`[...document.querySelectorAll('#confirm button')].every(b => getComputedStyle(b).borderTopWidth === '0px')`));
  1399. await on('#confirm footer button[value=ok]');
  1400. check(`modal ${tag}: a footer button closes it with its value ("ok")`, (await openIds()) === '' && (await last()) === 'confirm: ok' && (await active()) === 'open-confirm', `${await openIds()} / ${await last()} / ${await active()}`);
  1401. await on('#open-confirm'); await on('#confirm footer button[value=cancel]');
  1402. check(`modal ${tag}: Cancel closes it with "cancel"`, (await last()) === 'confirm: cancel');
  1403. // backdrop close switched off; focus goes round inside with Tab / Shift+Tab
  1404. await on('#open-form'); await bg();
  1405. check(`modal ${tag}: backdropClose = "false": a click on the background leaves it open`, (await openIds()) === 'form' && (await last()) === 'confirm: cancel' && await inside('form'));
  1406. const seen = [];
  1407. for (let i = 0; i < 9; i++) { await mkey('Tab', 'Tab', 9); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  1408. check(`modal ${tag}: Tab ×9 never leaves the window`, seen.every(s => s === 'in'), seen.join());
  1409. await ev(`document.getElementById('modal-save').focus()`); await mkey('Tab', 'Tab', 9);
  1410. check(`modal ${tag}: Tab on the last control goes round to the first (×)`, (await active()) === 'modal-x', await active());
  1411. await mkey('Tab', 'Tab', 9, 8);
  1412. check(`modal ${tag}: Shift+Tab on the first goes round to the last (Save)`, (await active()) === 'modal-save', await active());
  1413. for (let i = 0; i < 6; i++) { await mkey('Tab', 'Tab', 9, 8); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  1414. check(`modal ${tag}: Shift+Tab never leaves the window`, seen.every(s => s === 'in'), seen.join());
  1415. await ev(`document.getElementById('modal-name').focus()`);
  1416. await page.send('Input.insertText', { text: 'Ada' }); await sleep(150);
  1417. await shot(`modal-form-${w}`);
  1418. // the page closes it itself, with its own reason
  1419. await on('#modal-save');
  1420. check(`modal ${tag}: the page closes it itself (close('saved')), reason "saved", it read the field`, (await openIds()) === '' && (await last()) === 'form: saved' && (await ev(`document.getElementById('modal-saved').textContent`)) === 'Ada' && (await active()) === 'open-form', `${await last()} / ${await active()}`);
  1421. // no scroll behind: a long page scrolled down stays where it is; the long window scrolls itself
  1422. await ev(`(() => { const d = document.createElement('div'); d.id = 'gate-tall'; d.style.height = '3000px'; document.querySelector('main').appendChild(d); scrollTo(0, 200); })()`);
  1423. await sleep(100);
  1424. await ev(`document.getElementById('open-long').click()`); await sleep(300);
  1425. const y0 = await ev('scrollY');
  1426. check(`modal ${tag}: while open the page cannot scroll (html overflow hidden)`, (await ev(`getComputedStyle(document.documentElement).overflow`)) === 'hidden');
  1427. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 4, y: h - 4, deltaX: 0, deltaY: 600 }); await sleep(400);
  1428. const mb = await ev(`(() => { const r = document.querySelector('#long modal-body').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; })()`);
  1429. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: mb.x, y: mb.y, deltaX: 0, deltaY: 600 }); await sleep(400);
  1430. check(`modal ${tag}: the wheel does not scroll the page behind`, (await ev('scrollY')) === y0, `${y0} → ${await ev('scrollY')}`);
  1431. check(`modal ${tag}: a long window stays inside the screen and scrolls its content`, (await ev(`document.getElementById('long').getBoundingClientRect().bottom <= innerHeight`)) && (await ev(`document.querySelector('#long modal-body').scrollTop > 0`)));
  1432. await shot(`modal-long-${w}`);
  1433. await mkey('Escape', 'Escape', 27);
  1434. check(`modal ${tag}: after closing the page scrolls again`, (await ev(`getComputedStyle(document.documentElement).overflow`)) !== 'hidden' && (await last()) === 'long: escape');
  1435. await ev(`document.getElementById('gate-tall').remove(); scrollTo(0, 0)`); await sleep(100);
  1436. check(`modal ${tag}: no horizontal overflow`, await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1437. await shot(`modal-closed-${w}`);
  1438. check(`modal ${tag}: no console errors or warnings`, page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0 && !/not a standard DOM event/.test(page.dumpConsole()), page.dumpConsole());
  1439. };
  1440. await modalRun(1280, 900, false, '1280 px');
  1441. await modalRun(390, 800, true, '390 px');
  1442. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1443. }
  1444. await shot('wide');
  1445. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1446. await sleep(300);
  1447. check('no horizontal overflow at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1448. await shot('narrow');
  1449. // ==== MP START — the media player (audio + video, phone first), pure Hybriel: the browser's own media element, the component's
  1450. // own controls around it. REAL interaction: play/pause by click and by Space, the seek bar dragged with pointer events
  1451. // (Input.dispatchMouseEvent), back / forward 10 s, the speed cycle, the queue's current item marked with the accent only,
  1452. // tap sizes at 390, no horizontal scroll at 390. Screenshots .scratch/gate-media-{paused,playing,queue,390}.png.
  1453. {
  1454. check('MP: the home links the media player', home.includes('id="open-media-player"'));
  1455. check('MP: the README is served', (await fetch(BASE + '/media-player/README.md')).ok);
  1456. check('MP: the component has no .js file', existsSync(join(APP, 'components/media-player/media-player.hl')) && !execSync(`find ${join(APP, 'components/media-player')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  1457. check('MP: the demo media files are served (mp4 with the video type, mp3 audio, png cover)',
  1458. (await fetch(BASE + '/media/test-video.mp4')).ok && (await fetch(BASE + '/media/test-audio.mp3')).ok && (await fetch(BASE + '/media/cover.png')).ok
  1459. && /video\/mp4/.test((await fetch(BASE + '/media/test-video.mp4')).headers.get('content-type') || ''));
  1460. {
  1461. const ask = (r) => fetch(BASE + '/media/test-video.mp4', { headers: { Range: r } });
  1462. const tail = await ask('bytes=-500'), whole = await fetch(BASE + '/media/test-video.mp4'), size = (await whole.arrayBuffer()).byteLength;
  1463. check('MP: a suffix range (bytes=-500) answers the LAST 500 bytes', tail.status === 206 && tail.headers.get('content-range') === `bytes ${size - 500}-${size - 1}/${size}` && (await tail.arrayBuffer()).byteLength === 500, tail.status + ' ' + tail.headers.get('content-range'));
  1464. const first = await ask('bytes=0-9');
  1465. check('MP: a normal range (bytes=0-9) answers 206 with 10 bytes', first.status === 206 && (await first.arrayBuffer()).byteLength === 10);
  1466. const odd = [];
  1467. for (const r of ['bytes=0-10,20-30', 'bytes=abc', 'bytes=-', 'bytes=0-9,', 'bytes=x-5']) { const a = await ask(r); odd.push(r + ' ' + a.status); await a.arrayBuffer(); }
  1468. check('MP: a list of ranges or an unreadable Range header never makes the route fail (no 5xx)', odd.every(x => !/ 5\d\d$/.test(x)), odd.join(', '));
  1469. }
  1470. const page = await browser.newPage();
  1471. const ev = (e) => page.evaluate(e);
  1472. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  1473. const realClick = async (sel) => {
  1474. const r = await ev(`(() => { const b = document.querySelector(${JSON.stringify(sel)}).getBoundingClientRect(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; })()`);
  1475. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: r.x, y: r.y, button: 'none' });
  1476. await sleep(80);
  1477. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  1478. await sleep(60);
  1479. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  1480. await sleep(250);
  1481. };
  1482. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1483. await page.goto(BASE + '/media-player');
  1484. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1485. await page.waitFor('!!document.querySelector("media-player video") && document.querySelector("media-player video").duration > 0', { timeout: 15000, label: 'metadata loaded' });
  1486. check('MP: the video is 16:9 letterboxed (object-fit contain)', await ev(`(() => { const v = document.querySelector('media-player video'); const r = v.getBoundingClientRect(); return Math.abs(r.width / r.height - 16 / 9) < 0.05 && getComputedStyle(v).objectFit === 'contain'; })()`));
  1487. await page.waitFor(`document.querySelector('media-player .mp-times time:last-of-type').textContent === '0:30'`, { timeout: 15000, label: 'total time' }).catch(() => {});
  1488. check('MP: the controls exist (seek bar, back, play, forward, mute, speed, fullscreen) and the times are 0:00 / 0:30', await ev(`!!document.querySelector('media-player mp-seek') && !!document.querySelector('media-player button.mp-back') && !!document.querySelector('media-player button.mp-play') && !!document.querySelector('media-player button.mp-forward') && !!document.querySelector('media-player button.mp-mute') && !!document.querySelector('media-player button.mp-speed') && !!document.querySelector('media-player button.mp-fullscreen') && document.querySelectorAll('media-player .mp-times time').length === 2 && document.querySelector('media-player .mp-times time:last-of-type').textContent === '0:30'`));
  1489. await shot('media-paused');
  1490. // PLAY: a real click on the play button
  1491. await realClick('media-player button.mp-play');
  1492. await page.waitFor(`!!document.querySelector('media-player video') && !document.querySelector('media-player video').paused`, { timeout: 10000, label: 'playing' });
  1493. check('MP: a click on the play button plays (the pause icon shows)', await ev(`!document.querySelector('media-player video').paused && document.querySelector('media-player button.mp-play').className.includes('is-playing') && getComputedStyle(document.querySelector('media-player button.mp-play .i-pause')).display !== 'none'`));
  1494. await page.waitFor(`document.querySelector('media-player video').currentTime > 0.8`, { timeout: 10000, label: 'time moves' });
  1495. check('MP: the current time and the played bar follow (timeupdate)', await ev(`(() => { const v = document.querySelector('media-player video'); return v.currentTime > 0.8 && parseFloat(document.querySelector('media-player .mp-times time').textContent.slice(2)) >= 0 && parseFloat(document.querySelector('media-player .mp-played').style.width) > 0; })()`));
  1496. await page.waitFor(`document.querySelector('media-player video').buffered.length > 0 && (document.querySelector('media-player video').buffered.end(document.querySelector('media-player video').buffered.length - 1) > document.querySelector('media-player video').currentTime)`, { timeout: 15000, label: 'buffered' }).catch(() => {});
  1497. check('MP: the buffered part shows on the bar (more than the played part)', await ev(`(() => { const v = document.querySelector('media-player video'); const w = parseFloat(document.querySelector('media-player .mp-buffered').style.width); return v.buffered.length > 0 && w > parseFloat(document.querySelector('media-player .mp-played').style.width); })()`));
  1498. await shot('media-playing');
  1499. // PAUSE by Space on the video (keyboard): the video takes the focus (tabindex), the key lands on it
  1500. await ev(`document.querySelector('media-player video').focus()`);
  1501. await sleep(150);
  1502. if (await ev(`document.activeElement.tagName`) !== 'VIDEO') { await ev(`document.querySelector('media-player video').focus()`); await sleep(150); }
  1503. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: ' ', code: 'Space', windowsVirtualKeyCode: 32 });
  1504. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ' ', code: 'Space', windowsVirtualKeyCode: 32 });
  1505. await sleep(300);
  1506. check('MP: Space on the video pauses', await ev(`document.querySelector('media-player video').paused && !document.querySelector('media-player button.mp-play').className.includes('is-playing')`), await ev(`document.activeElement.tagName`));
  1507. // the seek bar: a real pointer drag from the middle to the left (Input.dispatchMouseEvent with pointer events)
  1508. const dragTo = async (fx) => {
  1509. const r = await ev(`(() => { const b = document.querySelector('media-player mp-seek').getBoundingClientRect(); return { x: b.x, y: b.y + b.height / 2, w: b.width }; })()`);
  1510. const y = r.y;
  1511. const x0 = r.x + r.w * 0.75, x1 = r.x + r.w * fx;
  1512. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: x0, y, button: 'none' });
  1513. await sleep(60);
  1514. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: x0, y, button: 'left', clickCount: 1 });
  1515. await sleep(120);
  1516. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: (x0 + x1) / 2, y, button: 'left' });
  1517. await sleep(120);
  1518. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: x1, y, button: 'left' });
  1519. await sleep(200);
  1520. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: x1, y, button: 'left', clickCount: 1 });
  1521. await sleep(600);
  1522. };
  1523. // start far from the target (25 s), so a seek that does nothing cannot pass the 10% check
  1524. await ev(`document.querySelector('media-player video').currentTime = 25`);
  1525. await sleep(400);
  1526. await dragTo(0.1);
  1527. check('MP: dragging the seek bar to 10% moves the time near 3 s of a 30 s clip (a finger drag)', await ev(`(() => { const t = document.querySelector('media-player video').currentTime; return t > 0.5 && t < 6; })()`), await ev(`'' + document.querySelector('media-player video').currentTime`));
  1528. await dragTo(0.6);
  1529. check('MP: dragging the seek bar to 60% moves the time near 18 s of a 30 s clip', await ev(`(() => { const t2 = document.querySelector('media-player video').currentTime; return t2 > 13 && t2 < 24; })()`), await ev(`'' + document.querySelector('media-player video').currentTime`));
  1530. check('MP: after a drag the pause state shows on the button (Space paused it, the drags kept it paused)',
  1531. await ev(`document.querySelector('media-player video').paused && !document.querySelector('media-player button.mp-play').className.includes('is-playing')`));
  1532. await realClick('media-player button.mp-play');
  1533. await sleep(250);
  1534. check('MP: play resumes from the seek position (near 18 s, playing)', await ev(`(() => { const v = document.querySelector('media-player video'); return !v.paused && v.currentTime > 13 && v.currentTime < 25; })()`), await ev(`'' + document.querySelector('media-player video').currentTime`));
  1535. // back / forward 10 s
  1536. await ev(`document.querySelector('media-player video').currentTime = 15`);
  1537. await sleep(200);
  1538. await realClick('media-player button.mp-back');
  1539. await sleep(300);
  1540. check('MP: back 10 s jumps ten seconds back', await ev(`Math.abs(document.querySelector('media-player video').currentTime - 5) < 1.5`), await ev(`'' + document.querySelector('media-player video').currentTime`));
  1541. await realClick('media-player button.mp-forward');
  1542. await sleep(300);
  1543. check('MP: forward 10 s jumps ten seconds forward', await ev(`Math.abs(document.querySelector('media-player video').currentTime - 15) < 1.5`), await ev(`'' + document.querySelector('media-player video').currentTime`));
  1544. // the speed cycle
  1545. const rates = [];
  1546. for (let i = 0; i < 4; i++) { await realClick('media-player button.mp-speed'); await sleep(200); rates.push(await ev(`document.querySelector('media-player video').playbackRate`)); }
  1547. check('MP: the speed button steps 1.25 → 1.5 → 2 → 1 and labels itself', JSON.stringify(rates) === JSON.stringify([1.25, 1.5, 2, 1]) && (await ev(`document.querySelector('media-player button.mp-speed').textContent.trim()`)).startsWith('1'), JSON.stringify(rates) + ' ' + await ev(`document.querySelector('media-player button.mp-speed').textContent`));
  1548. // the queue: the current item is the accent colour only
  1549. check('MP: the queue lists four items with their lengths, the first marked current', await ev(`[...document.querySelectorAll('media-player ol.mp-queue li')].length === 4 && document.querySelector('media-player ol.mp-queue li').className.includes('current') && !document.querySelectorAll('media-player ol.mp-queue li')[1].className.includes('current') && document.querySelector('media-player ol.mp-queue .mp-q-dur').textContent === '0:30'`));
  1550. check('MP: the current queue row is marked (surface background, the other transparent; the accent colour itself is the theme\'s to set)',
  1551. await ev(`(() => { const bs = [...document.querySelectorAll('media-player ol.mp-queue button')].map(b => getComputedStyle(b).backgroundColor); return bs.length === 4 && bs[0] !== 'rgba(0, 0, 0, 0)' && bs[1] === 'rgba(0, 0, 0, 0)'; })()`));
  1552. // a real tap on the second queue item: the host hands the audio back, the player becomes an audio player with the cover
  1553. // the clip must not be able to END by itself during the wait (it would then hand over to the next item without any tap): 5 s into 30 s
  1554. await ev(`document.querySelector('media-player video').currentTime = 5`);
  1555. await sleep(300);
  1556. await realClick('media-player ol.mp-queue li:nth-child(2) button');
  1557. await page.waitFor(`!!document.querySelector('media-player audio')`, { timeout: 8000, label: 'audio player' });
  1558. await page.waitFor(`!!document.querySelector('media-player audio') && !document.querySelector('media-player audio').paused`, { timeout: 15000, label: 'audio playing' }).catch(() => {});
  1559. check('MP: a tap on the second queue item plays the audio: no video element, the cover with title and artist, the row is current now', await ev(`!document.querySelector('media-player video') && !!document.querySelector('media-player audio') && !!document.querySelector('media-player .mp-cover img') && document.querySelector('media-player .mp-cover h2').textContent.includes('audio') && !document.querySelector('media-player ol.mp-queue li').className.includes('current') && document.querySelectorAll('media-player ol.mp-queue li')[1].className.includes('current') && !document.querySelector('media-player button.mp-fullscreen')`));
  1560. await shot('media-queue');
  1561. // the audio element is hidden (the cover is the face), but the controls still act on it
  1562. check('MP: the hidden audio element is display:none and still playing', await ev(`getComputedStyle(document.querySelector('media-player audio')).display === 'none' && !document.querySelector('media-player audio').paused`));
  1563. // mute
  1564. await realClick('media-player button.mp-mute');
  1565. await sleep(200);
  1566. check('MP: mute silences the element and flips the icon and the label', await ev(`document.querySelector('media-player audio').muted && document.querySelector('media-player button.mp-mute').className.includes('is-muted') && document.querySelector('media-player button.mp-mute').getAttribute('aria-label') === 'Unmute'`));
  1567. await realClick('media-player button.mp-mute');
  1568. await sleep(200);
  1569. check('MP: a second click unmutes', await ev(`!document.querySelector('media-player audio').muted`));
  1570. // a new item must show ITS state, not the old item's (speed, mute, play state, time, bars): the labels follow the element
  1571. const shows = `(() => { const m = document.querySelector('media-player'); const v = m.querySelector('video, audio'); const sp = m.querySelector('.mp-speed').textContent.trim(); const mu = m.querySelector('.mp-mute'); const pl = m.querySelector('.mp-play'); return { speedOk: sp === v.playbackRate + '×', muteOk: mu.className.includes('is-muted') === v.muted && mu.getAttribute('aria-label') === (v.muted ? 'Unmute' : 'Mute'), playOk: pl.className.includes('is-playing') === !v.paused, paused: v.paused, t: v.currentTime, bar: parseFloat(m.querySelector('.mp-played').style.width) }; })()`;
  1572. await realClick('media-player button.mp-speed');
  1573. await realClick('media-player button.mp-mute');
  1574. await realClick('media-player ol.mp-queue li:nth-child(1) button');
  1575. await page.waitFor(`!!document.querySelector('media-player video') && !document.querySelector('media-player video').paused`, { timeout: 10000, label: 'video again' }).catch(() => {});
  1576. await sleep(500);
  1577. const s1 = await ev(shows);
  1578. check('MP: a queue pick that changes the kind (audio to video) shows the new element\'s speed, mute and play state, not the old item\'s', s1.speedOk && s1.muteOk && s1.playOk && !s1.paused, JSON.stringify(s1));
  1579. await realClick('media-player button.mp-speed');
  1580. await realClick('media-player button.mp-mute');
  1581. await ev(`document.querySelector('media-player video').currentTime = 20`);
  1582. await sleep(700);
  1583. await realClick('media-player ol.mp-queue li:nth-child(3) button');
  1584. await page.waitFor(`document.querySelector('media-player video') && document.querySelector('media-player video').getAttribute('src').includes('again')`, { timeout: 10000, label: 'same-kind pick' }).catch(() => {});
  1585. await sleep(1500);
  1586. const s2 = await ev(shows);
  1587. check('MP: a queue pick of the same kind (video to video) starts the new item and shows its state (speed, mute, play, time restarted)', s2.speedOk && s2.muteOk && s2.playOk && !s2.paused && s2.t < 5 && s2.bar < 20, JSON.stringify(s2));
  1588. // AUDIO WITHOUT A COVER: the audio element is display:none and carries no mount animation; a pick must still start it and show its time
  1589. await realClick('media-player ol.mp-queue li:nth-child(4) button');
  1590. await page.waitFor(`!!document.querySelector('media-player audio') && !document.querySelector('media-player audio').paused`, { timeout: 10000, label: 'cover-less audio playing' }).catch(() => {});
  1591. await page.waitFor(`document.querySelector('media-player audio') && document.querySelector('media-player audio').currentTime > 1.2`, { timeout: 10000, label: 'cover-less audio time' }).catch(() => {});
  1592. await sleep(500);
  1593. const s3 = await ev(shows + ``);
  1594. const s3b = await ev(`(() => { const m = document.querySelector('media-player'); const a = m.querySelector('audio'); const tt = m.querySelectorAll('.mp-times time'); return { noCover: !m.querySelector('.mp-cover'), isAudio: !!a && !m.querySelector('video'), total: tt[1].textContent, now: tt[0].textContent, t: a.currentTime }; })()`);
  1595. check('MP: a queue pick of an audio item WITHOUT a cover starts it, shows the pause icon, the total time 0:45 and a running time', s3.playOk && !s3.paused && s3.speedOk && s3.muteOk && s3b.noCover && s3b.isAudio && s3b.total === '0:45' && s3b.now !== '0:00' && s3b.t > 1, JSON.stringify(s3) + JSON.stringify(s3b));
  1596. check('MP: the speed button names the current speed in its label and the seek slider says its time in words', await ev(`(() => { const m = document.querySelector('media-player'); const a = m.querySelector('audio'); const tt = m.querySelectorAll('.mp-times time'); return m.querySelector('.mp-speed').getAttribute('aria-label').includes(String(a.playbackRate)) && m.querySelector('mp-seek').getAttribute('aria-valuetext') === tt[0].textContent + ' of ' + tt[1].textContent; })()`));
  1597. check('MP: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1598. // 390 px: the phone. Every target at least 44 × 44, no horizontal scroll, the video 16:9 within the width.
  1599. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1600. await page.goto(BASE + '/media-player');
  1601. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1602. await page.waitFor('!!document.querySelector("media-player video") && document.querySelector("media-player video").duration > 0', { timeout: 15000, label: 'metadata' });
  1603. await sleep(400);
  1604. const targets = await ev(`[...document.querySelectorAll('media-player button, media-player mp-seek, media-player ol.mp-queue button')].map(el => { const r = el.getBoundingClientRect(); return el.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);
  1605. check('MP 390px: every control is at least 44 × 44 px (back, play, forward, mute, speed, fullscreen, the seek strip, both queue rows)', targets.length >= 8 && targets.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), JSON.stringify(targets));
  1606. check('MP 390px: the play button is the largest control (taller than every other button)', await ev(`(() => { const play = document.querySelector('media-player button.mp-play').getBoundingClientRect().height; return [...document.querySelectorAll('media-player mp-buttons button:not(.mp-play)')].every(b => b.getBoundingClientRect().height < play); })()`));
  1607. check('MP 390px: the video is 16:9 and fits the width (no letterbox overflow)', await ev(`(() => { const r = document.querySelector('media-player video').getBoundingClientRect(); return Math.abs(r.width / r.height - 16 / 9) < 0.05 && r.width <= window.innerWidth && r.right <= window.innerWidth + 0.5; })()`));
  1608. check('MP 390px: no horizontal scroll', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1609. await shot('media-390');
  1610. await page.close();
  1611. }
  1612. // ==== MP END
  1613. // ==== mission MC: MOBILE FIRST at 390 px (caramboleyo's Android phone, touch): on EVERY page and in the open dialogs / popups every
  1614. // button, field and link of its own is a 44 × 44 px target, nothing is wider than the screen, an input is 16 px+ (no iOS zoom), the
  1615. // header is the brand alone; the month names of the month view and both pickers follow the PAGE language (English when the page
  1616. // declares none — the browser's own locale, forced to German here, must not leak in; <html lang="de"> must).
  1617. {
  1618. const pages = ['/', '/month-view', '/date-picker', '/range-picker', '/pagination', '/md-editor', '/code-editor', '/file-upload', '/files-upload', '/files-upload/pick', '/modal', '/comments', '/media-player'];
  1619. // every visible interactive element that is not a text link inside a sentence and not switched off for the pointer
  1620. const SMALL = `(() => { const out = []; for (const e of document.querySelectorAll('a,button,input,select,textarea,summary,[role=button]')) {
  1621. const b = e.getBoundingClientRect(), s = getComputedStyle(e);
  1622. if (!(b.width > 0 && b.height > 0) || s.visibility === 'hidden' || s.display === 'none' || e.type === 'hidden' || s.pointerEvents === 'none') continue;
  1623. if (e.tagName === 'A' && s.display === 'inline') continue;
  1624. if (e.closest('md-editor, code-editor') && e.tagName !== 'BUTTON') continue;
  1625. if (b.width < 43.5 || b.height < 43.5) out.push(e.tagName + '#' + e.id + ' ' + (e.textContent || e.value || '').trim().slice(0, 20) + ' ' + Math.round(b.width) + 'x' + Math.round(b.height)); }
  1626. return out; })()`;
  1627. const mobile = async (loc) => {
  1628. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 3, mobile: true });
  1629. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  1630. await page.send('Emulation.setLocaleOverride', { locale: loc });
  1631. };
  1632. await mobile('de-DE');
  1633. for (const path of pages) {
  1634. await page.goto(BASE + path); await sleep(900);
  1635. const small = await ev(SMALL);
  1636. check(`m390 ${path}: every button / field / block link is at least 44 × 44 px`, small.length === 0, small.join(' | '));
  1637. check(`m390 ${path}: no horizontal overflow`, await ev('document.scrollingElement.scrollWidth <= innerWidth'));
  1638. check(`m390 ${path}: every input is 16 px or more (no zoom on focus)`, await ev(`[...document.querySelectorAll('input,textarea,select')].filter(e => e.type !== 'hidden' && e.getBoundingClientRect().width > 0).every(e => parseFloat(getComputedStyle(e).fontSize) >= 16)`));
  1639. if (path === '/') {
  1640. check('m390 header: the brand alone, a 44 px target, the header is at most 56 px high (the tagline is for wide screens)', await ev(`(() => { const h = document.querySelector('application-header'), p = h.querySelector('p'); return getComputedStyle(p).display === 'none' && h.getBoundingClientRect().height <= 56; })()`));
  1641. }
  1642. }
  1643. // the popups and dialogs at 390
  1644. await page.goto(BASE + '/date-picker'); await sleep(900);
  1645. await page.click('date-picker input'); await sleep(400);
  1646. check('m390 date picker open: the day cells and the month buttons are at least 44 px', await ev(`[...document.querySelectorAll('date-picker ol.days li, date-picker button')].filter(e => e.getBoundingClientRect().width > 0).every(e => e.getBoundingClientRect().height >= 43.5) && [...document.querySelectorAll('date-picker button')].filter(e => e.getBoundingClientRect().width > 0).every(e => e.getBoundingClientRect().width >= 43.5)`));
  1647. check('m390 date picker open: the popup is inside the screen', await ev(`(() => { const r = document.querySelector('date-picker picker-popup').getBoundingClientRect(); return r.left >= 0 && r.right <= innerWidth; })()`));
  1648. check('m390 date picker: the Send button has air (16 px+) above it', await ev(`(() => { const p = document.querySelector('.demo-send'); return !!p && parseFloat(getComputedStyle(p).marginTop) >= 16; })()`));
  1649. await page.goto(BASE + '/range-picker'); await sleep(900);
  1650. await page.click('#range-picker-input'); await sleep(400);
  1651. check('m390 range picker open: the day cells and the month buttons are at least 44 px', await ev(`[...document.querySelectorAll('range-picker ol.days li, range-picker button')].filter(e => e.getBoundingClientRect().width > 0).every(e => e.getBoundingClientRect().height >= 43.5)`));
  1652. check('m390 range picker: the Send button has air (16 px+) above it', await ev(`(() => { const p = document.querySelector('.demo-send'); return !!p && parseFloat(getComputedStyle(p).marginTop) >= 16; })()`));
  1653. await page.goto(BASE + '/modal'); await sleep(900);
  1654. for (const id of ['info', 'confirm', 'form', 'long']) {
  1655. await page.click('#open-' + id); await sleep(400);
  1656. const bad = await ev(`[...document.querySelectorAll('#${id} button')].filter(e => e.getBoundingClientRect().width > 0).filter(e => e.getBoundingClientRect().width < 43.5 || e.getBoundingClientRect().height < 43.5).map(e => (e.className || e.textContent) + ' ' + Math.round(e.getBoundingClientRect().width) + 'x' + Math.round(e.getBoundingClientRect().height))`);
  1657. check(`m390 modal ${id}: ×, footer buttons are at least 44 × 44 px`, bad.length === 0, bad.join(' | '));
  1658. await ev(`document.getElementById('${id}').close('gate')`); await sleep(200);
  1659. }
  1660. await page.goto(BASE + '/comments'); await sleep(1200);
  1661. check('m390 comments: "You are" is a labelled group of three buttons, the chosen one pressed and filled, the others quiet', await ev(`(() => { const g = document.querySelector('.comments-who'); const bs = [...g.querySelectorAll('button')]; return g.getAttribute('role') === 'group' && !!g.getAttribute('aria-label') && bs.length === 3 && bs[0].getAttribute('aria-pressed') === 'true' && !bs[0].classList.contains('quiet') && bs[1].getAttribute('aria-pressed') === 'false' && bs[1].classList.contains('quiet'); })()`));
  1662. await page.click('#as-bob'); await sleep(400);
  1663. check('m390 comments: choosing bob presses bob and shows "now bob"', await ev(`document.getElementById('as-bob').getAttribute('aria-pressed') === 'true' && document.getElementById('as-alice').getAttribute('aria-pressed') === 'false' && document.getElementById('comments-me').textContent === 'now bob'`));
  1664. check('m390 comments: the "edited" label, like / Edit / Delete are 44 px targets', await ev(`[...document.querySelectorAll('comments-block summary, comments-block button')].filter(e => e.getBoundingClientRect().width > 0 && e.closest('md-editor') == null).every(e => e.getBoundingClientRect().height >= 43.5)`));
  1665. // LANGUAGE: the browser says German, the page says nothing → English; the page says de → German, in all three
  1666. const names = async (path, open) => { await page.goto(BASE + path); await sleep(1100); if (open) { await page.click(open); await sleep(500); } return ev(`document.querySelector('${open ? 'picker-popup' : 'month-view'} h2').textContent + ' ' + document.querySelector('${open ? 'picker-popup' : 'month-view'} ol').textContent.trim()`); };
  1667. const en = { mv: await names('/month-view'), dp: await names('/date-picker', 'date-picker input'), rp: await names('/range-picker', '#range-picker-input') };
  1668. check('lang: browser locale de-DE but the page declares no language → month view, date picker, range picker are English', /^[A-Z][a-z]+ \d{4} MonTue/.test(en.mv) && /^[A-Z][a-z]+ \d{4} MonTue/.test(en.dp) && /^[A-Z][a-z]+ \d{4} MonTue/.test(en.rp) && !/Oktober|MoDi/.test(en.mv + en.dp + en.rp), JSON.stringify(en));
  1669. const initId = (await page.addInitScript(`const set = () => { if (document.documentElement) { document.documentElement.lang = 'de'; return true; } }; if (!set()) new MutationObserver((m, o) => { if (set()) o.disconnect(); }).observe(document, { childList: true })`)).identifier;
  1670. const de = { mv: await names('/month-view'), dp: await names('/date-picker', 'date-picker input'), rp: await names('/range-picker', '#range-picker-input') };
  1671. check('lang: <html lang="de"> → month view, date picker, range picker show German month and weekday names', /MoDiMiDoFrSaSo/.test(de.mv) && /MoDiMiDoFrSaSo/.test(de.dp) && /MoDiMiDoFrSaSo/.test(de.rp), JSON.stringify(de));
  1672. await page.send('Page.removeScriptToEvaluateOnNewDocument', { identifier: initId });
  1673. await page.send('Emulation.setLocaleOverride', { locale: '' });
  1674. await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  1675. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1676. await page.goto(BASE + '/');
  1677. }
  1678. await mediaOptions(page, BASE, check);
  1679. // ==== ticket #15: THE BASE LOOK — black, white and the greys of shared/base.hl, no WorldAPI colours, no decorative frames.
  1680. // (1) every colour written in a component's public file is a base value (or black with alpha for a shadow);
  1681. // (2) every demo page (+ the home) at 1280 and 390 px: the site declares no --color-… token, the page is white with black text, and
  1682. // EVERY element's computed colour, background, visible border, outline, caret, accent colour (and the modal's ::backdrop) is a grey
  1683. // (r = g = b); (3) inside the components, a visible border only on a drop zone and a Markdown table's cells (mission 004). Screenshots: .scratch/gate-bw-<page>-<width>.png.
  1684. const baseSrc = readFileSync(join(APP, 'shared/base.hl'), 'utf8');
  1685. const baseValues = [...baseSrc.matchAll(/^static \w+ = var\('(#[0-9a-f]+)'\)/gm)].map(m => m[1]);
  1686. check('base look: shared/base.hl names black, white and four greys', baseValues.join(' ') === '#000 #555 #999 #ddd #f2f2f2 #fff', baseValues.join(' '));
  1687. const publicFiles = ['month-view/month-view.hl', 'month-view/clock.hl', 'date-picker/date-picker.hl', 'range-picker/range-picker.hl', 'pagination/pagination.hl',
  1688. 'md-editor/md-editor.hl', 'code-editor/code-editor.hl', 'file-upload/file-upload.hl', 'files-upload/files-upload.hl', 'modal/modal.hl', 'comments/comments.hl', 'media-player/media-player.hl'];
  1689. const foreign = [];
  1690. for (const pf of publicFiles) {
  1691. readFileSync(join(APP, 'components', pf), 'utf8').split('\n').forEach((line, i) => {
  1692. if (/^\s*\/\//.test(line)) return;
  1693. for (const m of line.matchAll(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)/g))
  1694. if (!baseValues.includes(m[0]) && !/^rgba\(0, 0, 0, \.\d+\)$/.test(m[0])) foreign.push(`${pf}:${i + 1} ${m[0]}`);
  1695. });
  1696. }
  1697. check('base look: every colour in the 12 public component files is a base value (no WorldAPI palette fallback)', foreign.length === 0, foreign.join(', '));
  1698. const bwProbe = `(() => {
  1699. const grey = c => { const m = c.match(/rgba?\\(([\\d.]+), ([\\d.]+), ([\\d.]+)(?:, ([\\d.]+))?\\)/); return !m || m[4] === '0' || (m[1] === m[2] && m[2] === m[3]); };
  1700. const bad = [], frames = [];
  1701. const name = el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string' ? '.' + el.className.trim().replace(/\\s+/g, '.') : '');
  1702. const comp = 'month-view, date-picker, range-picker, pagination, md-editor, code-editor, file-upload, files-upload, modal-dialog, comments-block, media-player';
  1703. for (const el of document.querySelectorAll('*')) {
  1704. const cs = getComputedStyle(el);
  1705. const props = ['color', 'backgroundColor', 'caretColor', 'accentColor', 'textDecorationColor'];
  1706. for (const side of ['Top', 'Right', 'Bottom', 'Left']) if (parseFloat(cs['border' + side + 'Width']) > 0 && cs['border' + side + 'Style'] !== 'none') props.push('border' + side + 'Color');
  1707. if (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) props.push('outlineColor');
  1708. for (const p of props) if (cs[p] !== 'auto' && !grey(cs[p])) bad.push(name(el) + ' ' + p + ' ' + cs[p]);
  1709. if (/^(rgba?|.* rgba?)\\(/.test(cs.boxShadow) && !(cs.boxShadow.match(/rgba?\\([^)]*\\)/g) || []).every(grey)) bad.push(name(el) + ' boxShadow ' + cs.boxShadow);
  1710. if (el.tagName === 'DIALOG') { const b = getComputedStyle(el, '::backdrop').backgroundColor; if (!grey(b)) bad.push('dialog::backdrop ' + b); }
  1711. // a table's cell lines are functional (mission 004), like the drop zone's
  1712. if (el.closest(comp) && !el.closest('drop-zone') && !el.matches('md-editor article th, md-editor article td'))
  1713. for (const side of ['Top', 'Right', 'Bottom', 'Left'])
  1714. if (parseFloat(cs['border' + side + 'Width']) > 0 && cs['border' + side + 'Style'] !== 'none' && !/rgba\\([^)]*, 0\\)|transparent/.test(cs['border' + side + 'Color'])) { frames.push(name(el) + ' border' + side); break; }
  1715. }
  1716. const root = getComputedStyle(document.documentElement);
  1717. const tokens = ['--color-text', '--color-background', '--color-accent', '--color-surface', '--color-border', '--orange'].filter(t => root.getPropertyValue(t).trim() !== '');
  1718. const body = getComputedStyle(document.body);
  1719. return { bad: bad.slice(0, 12), nBad: bad.length, frames: frames.slice(0, 12), nFrames: frames.length, tokens, light: body.backgroundColor === 'rgb(255, 255, 255)' && body.color === 'rgb(0, 0, 0)' };
  1720. })()`;
  1721. const bwPages = ['/', '/month-view', '/date-picker', '/range-picker', '/pagination', '/md-editor', '/code-editor', '/file-upload', '/files-upload', '/files-upload/pick', '/modal', '/comments', '/media-player'];
  1722. for (const w of [1280, 390]) {
  1723. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 600 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 600 });
  1724. const results = [];
  1725. for (const p of bwPages) {
  1726. await page.goto(BASE + p);
  1727. // a page that does not come up (e.g. the pick demo on older code) is a FAIL of its own, not the end of the gate
  1728. if (!(await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated ' + p }).then(() => true, () => false))) { check(`base look ${w}px: ${p} comes up`, false, 'not hydrated'); continue; }
  1729. await sleep(300);
  1730. const r = await ev(bwProbe);
  1731. results.push([p, r]);
  1732. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  1733. writeFileSync(join(SCRATCH, `gate-bw-${p === '/' ? 'home' : p.slice(1).replace(/\//g, '-')}-${w}.png`), Buffer.from(data, 'base64'));
  1734. }
  1735. // the floating parts: the date picker's popup open, the modal open (its window and the dimmed page)
  1736. await page.goto(BASE + '/date-picker');
  1737. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1738. await page.click('date-picker input');
  1739. await page.waitFor(`getComputedStyle(document.querySelector('date-picker picker-popup')).display !== 'none'`, { label: 'bw popup open' });
  1740. results.push(['/date-picker (popup open)', await ev(bwProbe)]);
  1741. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-date-picker-open-${w}.png`), Buffer.from(data, 'base64')); }
  1742. await page.goto(BASE + '/modal');
  1743. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1744. await page.click('.modal-openers button');
  1745. await page.waitFor(`!!document.querySelector('modal-dialog > dialog[open]')`, { label: 'bw modal open' });
  1746. await sleep(200);
  1747. results.push(['/modal (open)', await ev(bwProbe)]);
  1748. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-modal-open-${w}.png`), Buffer.from(data, 'base64')); }
  1749. check(`base look ${w}px: the site declares none of the WorldAPI tokens (--color-…) on any page`, results.every(([, r]) => r.tokens.length === 0), JSON.stringify(results.filter(([, r]) => r.tokens.length).map(([p, r]) => [p, r.tokens])));
  1750. check(`base look ${w}px: light by default — white page, black text on every page`, results.every(([, r]) => r.light), results.filter(([, r]) => !r.light).map(([p]) => p).join(' '));
  1751. check(`base look ${w}px: every rendered colour on the home, the 11 demo pages, the open date popup and the open modal is a grey (r = g = b)`, results.every(([, r]) => r.nBad === 0), JSON.stringify(results.filter(([, r]) => r.nBad).map(([p, r]) => [p, r.nBad, r.bad])));
  1752. check(`base look ${w}px: no frames — inside the components a visible border only on the drop zone and a table's cells`, results.every(([, r]) => r.nFrames === 0), JSON.stringify(results.filter(([, r]) => r.nFrames).map(([p, r]) => [p, r.nFrames, r.frames])));
  1753. }
  1754. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1755. // ==== mission 046: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons /
  1756. // offline = [ Index ]), as tracker.worldapi.org#10. The manifest and every icon over HTTP; Chrome's own verdict
  1757. // (installability, manifest parse); the worker registered for the whole app; then OFFLINE: the tab loses the
  1758. // network (the note appears), the server is stopped too (CDP's offline emulation does not reach the service worker's
  1759. // own fetches, so only a dead server proves the cache), and `/` still opens: header + the note + the home list. A
  1760. // demo page gets hl:web's "Unavailable offline" page. A separate 390 px tab, so its expected socket errors stay out
  1761. // of the main tab's console checks. Phone screenshots: .scratch/gate-pwa-phone-{online,offline}.png.
  1762. const html = await (await fetch(BASE + '/')).text();
  1763. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1764. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (base black, #15)',
  1765. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1766. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="#000">'), html.slice(0, 900));
  1767. const mres = await fetch(BASE + mhref);
  1768. const man = await mres.json();
  1769. check('pwa: the manifest is served as application/manifest+json: name "Hybriel components", short name "Components", start_url /, scope /, display standalone, the base colours (black header, white page)',
  1770. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'Hybriel components' && man.short_name === 'Components' && man.start_url === '/' && man.scope === '/'
  1771. && man.display === 'standalone' && man.theme_color === '#000' && man.background_color === '#fff', JSON.stringify(man));
  1772. const iconOk = [];
  1773. for (const ic of man.icons || []) {
  1774. const ir = await fetch(BASE + ic.src);
  1775. const b = Buffer.from(await ir.arrayBuffer());
  1776. iconOk.push(ir.ok && ic.type === 'image/png' && b.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && b.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  1777. }
  1778. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1779. iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), JSON.stringify(man.icons) + ' ' + JSON.stringify(iconOk));
  1780. const touch = await fetch(BASE + '/icons/apple-touch-icon.png');
  1781. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1782. const fav = await fetch(BASE + '/icons/favicon.svg');
  1783. const favText = await fav.text();
  1784. const ico = await fetch(BASE + '/favicon.ico');
  1785. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1786. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in black and white (#15), /favicon.ico a real icon file',
  1787. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('fill="#fff"') && favText.includes('fill="#000"') && !favText.includes('#b5cea8')
  1788. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1789. await page.goto('about:blank'); // the server goes down below: the main tab must not sit on a page meanwhile
  1790. const app = await browser.newPage();
  1791. const aev = (e) => app.evaluate(e);
  1792. const ashot = async (name) => { const { data } = await app.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  1793. const appHydrated = () => app.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'app tab hydrated' });
  1794. await app.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1795. await app.goto(BASE + '/');
  1796. await appHydrated();
  1797. await app.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: 'service worker active' });
  1798. await app.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: 'page controlled by the worker' });
  1799. const inst = await app.send('Page.getInstallabilityErrors');
  1800. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  1801. const am = await app.send('Page.getAppManifest');
  1802. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, JSON.stringify(am.errors));
  1803. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1804. (await aev(`navigator.serviceWorker.getRegistration().then(r => new URL(r.scope).pathname + ' ' + new URL(r.active.scriptURL).pathname)`)) === '/ /__hl/sw.js' && (await aev('!!navigator.serviceWorker.controller')));
  1805. check('pwa: online, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1806. check('pwa: no horizontal overflow at 390 px', await aev('document.documentElement.scrollWidth <= window.innerWidth'));
  1807. await ashot('pwa-phone-online');
  1808. await app.setOffline(true);
  1809. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1810. check('offline: the open page says so within seconds (the shell\'s tick)', (await aev(`document.querySelector('#offline') ? document.querySelector('#offline').textContent : ''`)) === 'You are offline. The demos need the network.');
  1811. await stopServer();
  1812. let down = false;
  1813. try { await fetch(BASE + '/'); } catch { down = true; }
  1814. await app.goto(BASE + '/');
  1815. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1816. check('offline: with the server gone too, a reload of / still opens the shell from the worker\'s cache — header, brand, the note, the home list',
  1817. down && (await aev(`document.querySelector('application-header .brand') ? document.querySelector('application-header .brand').textContent : ''`)) === 'Hybriel components'
  1818. && (await aev(`!!document.querySelector('#offline')`)) && (await aev(`document.querySelectorAll('#components li').length`)) === 12
  1819. && (await aev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(0, 0, 0)', 'server down: ' + down);
  1820. await ashot('pwa-phone-offline');
  1821. await app.goto(BASE + '/month-view');
  1822. check('offline: a demo page (/month-view) is not kept — hl:web\'s "Unavailable offline" page', (await aev(`!!document.querySelector('main[data-hl-offline]') && document.querySelector('h1').textContent`)) === 'Unavailable offline');
  1823. await app.setOffline(false);
  1824. await startServer();
  1825. await app.goto(BASE + '/');
  1826. await appHydrated();
  1827. await app.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1828. check('back online: / from the server again, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1829. await app.close();
  1830. }
  1831. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  1832. await stop();
  1833. console.log(`${passes} passed, ${failures} failed`);
  1834. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 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
  • bd4aa808Record VL24 deployment and live verificationmre
  • e5b98ecfRun virtual-list gate before deploymentmre
  • 2e9b4a8evirtual-list: into main, with centerId and scrollTop/onScroll (jukebox#20)mre
  • 69954249Align all plugin sources with Hybriel day38bmre
  • f740f666Re-vendor components to Hybriel set day38bmre
  • 8176eb14Record CS23b deployment and live verificationmre
  • 84e3ddaaRemove blank line before pagination Style closing bracemre
  • a92298ddRecord exact CSS and same-date proof after specificity reviewmre
  • c71a0abePreserve consumer theme specificity with nested tag rulesmre
  • 64a2bc27Document CS23b style formatting proof and review statusmre
  • a72b57cficons: nest Style rules in the language's formmre
  • 927616e2pagination: nest Style rules in the language's formmre
  • aab8ad29code-editor: nest Style rules in the language's formmre
  • ba30727afile-upload: nest Style rules in the language's formmre
  • 42fefa4emodal: nest Style rules in the language's formmre
  • 6fd953e3range-picker: nest Style rules in the language's formmre
  • f661951ddate-picker: nest Style rules in the language's formmre