gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit77a93c1677a93c16mission 011: gate hook for md-keys (480/0), flatten() runs one at a time (removeChild race), surface also built on first focus / pointer-down (background tab), md-bg test, README keysmre77a93c16/tests/browser.mjs

164.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 { mdKeys } from './md-keys.mjs';
  11. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  12. const HERE = dirname(fileURLToPath(import.meta.url));
  13. const APP = resolve(HERE, '..');
  14. const PORT = Number(process.env.COMPONENTS_GATE_PORT || 8700);
  15. const [CH_FROM, CH_TO] = (process.env.COMPONENTS_GATE_CHROME || '8701-8709').split('-').map(Number);
  16. const BASE = `http://127.0.0.1:${PORT}`;
  17. const SCRATCH = join(APP, '.scratch');
  18. const SESSIONS = join(SCRATCH, 'gate-sessions');
  19. // a re-vendored Hybriel compiles the app at its first start (cold 18–41 s, hybriel#148; then ~1 s from its build cache):
  20. // every server start waits up to COLD_MS (COMPONENTS_COLD_MS, default 120 s)
  21. const COLD_MS = Number(process.env.COMPONENTS_COLD_MS || 120000);
  22. rmSync(SESSIONS, { recursive: true, force: true });
  23. mkdirSync(SESSIONS, { recursive: true });
  24. let failures = 0, passes = 0;
  25. function check(label, ok, detail = '') {
  26. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  27. if (ok) passes++; else failures++;
  28. }
  29. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  30. let log = '', server = null, browser = null;
  31. async function stop() {
  32. if (browser) { try { await browser.close(); } catch {} browser = null; }
  33. await stopServer();
  34. }
  35. // the server alone goes down and up again in the offline checks (mission 046)
  36. async function stopServer() {
  37. if (server) {
  38. try { server.kill('SIGTERM'); } catch {}
  39. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  40. server = null;
  41. }
  42. }
  43. async function startServer() {
  44. 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'] });
  45. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  46. for (const t0 = Date.now(); ; ) {
  47. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  48. if (Date.now() - t0 > COLD_MS) throw new Error('server did not come up\n' + log);
  49. await sleep(250);
  50. }
  51. }
  52. async function main() {
  53. await startServer();
  54. // the home lists the component; its README is served
  55. const home = await (await fetch(BASE + '/')).text();
  56. 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')));
  57. check('home lists the month view', home.includes('id="open-month-view"'));
  58. check('home shows only the list, no component embedded (creator 2026-09-25)', !home.includes('<month-view'));
  59. const readme = await fetch(BASE + '/month-view/README.md');
  60. check('README is served as Markdown', readme.ok && /markdown/.test(readme.headers.get('content-type')) && (await readme.text()).includes('Month view'));
  61. // first render on the server: 6 weeks of 7 days, one today
  62. const demo = await (await fetch(BASE + '/month-view')).text();
  63. check('server renders 42 days and one today', (demo.match(/<li class=/g) || []).length === 42 && (demo.match(/class="today"/g) || []).length === 1);
  64. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  65. const page = await browser.newPage();
  66. const SLOW = 3;
  67. const goto = page.goto.bind(page);
  68. page.goto = (u, o = {}) => goto(u, { ...o, timeout: 15000 * SLOW });
  69. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  70. // a zone already on the next day (UTC+14) compared with the server's UTC date: the visitor's today must win (ticket #11)
  71. await page.send('Emulation.setTimezoneOverride', { timezoneId: 'Pacific/Kiritimati' });
  72. await page.goto(BASE + '/month-view');
  73. // the month view's own demo page (the home only lists the components)
  74. await page.waitForSelector('#month-title');
  75. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  76. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  77. const ev = (e) => page.evaluate(e);
  78. const title = () => ev('document.querySelector("#month-title").textContent');
  79. 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()); })()`);
  80. const expectTitle = (y, m) => ev(`new Intl.DateTimeFormat(navigator.language, { month: 'long' }).format(new Date(Date.UTC(${y}, ${m - 1}, 15, 12))) + ' ${y}'`);
  81. const [ty, tm] = localToday.split('-').map(Number);
  82. // the browser's today and language arrive at load, with no pointer needed
  83. await page.waitFor(`!!document.querySelector('li.today time') && document.querySelector('li.today time').getAttribute('datetime') === ${JSON.stringify(localToday)}`, { label: 'browser today marked at load' });
  84. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 300, y: 200 });
  85. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === (${JSON.stringify(await expectTitle(ty, tm))}).toLowerCase()`, { label: 'title in the browser language' });
  86. check('title is the current month and year in the browser language', true);
  87. check('today is marked (browser date)', (await ev(`document.querySelector('li.today time').getAttribute('datetime')`)) === localToday, localToday);
  88. check('42 days, 6 weeks', (await ev('document.querySelectorAll("#month-days li").length')) === 42);
  89. const t0 = await title();
  90. // next / prev
  91. await page.click('#month-next');
  92. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(t0)}`, { label: 'next month' });
  93. const nm = tm === 12 ? 1 : tm + 1, ny = tm === 12 ? ty + 1 : ty;
  94. await page.waitFor(`document.querySelector('#month-title').textContent.toLowerCase() === ${JSON.stringify((await expectTitle(ny, nm)).toLowerCase())}`, { label: 'next month in the browser language' });
  95. check('next shows the next month', true);
  96. await page.click('#month-prev');
  97. await page.waitFor(`document.querySelector("#month-title").textContent === ${JSON.stringify(t0)}`, { label: 'prev month' });
  98. check('prev returns to the month, today marked again', (await ev('document.querySelectorAll("li.today").length')) === 1);
  99. // walk to February 2028 (leap year) and check its days and its first weekday (Tuesday)
  100. let guard = 0;
  101. const feb28 = (await expectTitle(2028, 2)).toLowerCase();
  102. while ((await title()).toLowerCase() !== feb28 && guard++ < 40) {
  103. const before = await title();
  104. await page.click('#month-next');
  105. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging' });
  106. }
  107. 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 }; })()`);
  108. check('Feb 2028: 29 days, the 1st is a Tuesday (column 2)', feb.n === 29 && feb.col === 1, JSON.stringify(feb));
  109. // year rollover: go back to December 2027 and January 2028 by prev
  110. await page.click('#month-prev');
  111. await page.click('#month-prev');
  112. const dec27 = (await expectTitle(2027, 12)).toLowerCase();
  113. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify(dec27)}`, { label: 'back to December' });
  114. 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 }))()`);
  115. check('Dec 2027: 31 days, the 1st is a Wednesday', dec.n === 31 && dec.col === 2, JSON.stringify(dec));
  116. check('no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  117. // the date picker: click the field, pick a day, the value is YYYY-MM-DD; typing works
  118. check('home lists the date picker', home.includes('id="open-date-picker"'));
  119. check('date picker README is served', (await fetch(BASE + '/date-picker/README.md')).ok);
  120. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  121. await page.goto(BASE + '/date-picker');
  122. await page.waitForSelector('date-picker input');
  123. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  124. await sleep(1500);
  125. 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);
  126. const pop = (n) => `getComputedStyle(document.querySelectorAll('date-picker picker-popup')[${n}]).display !== 'none'`;
  127. const val = (n) => ev(`document.querySelectorAll('date-picker input')[${n}].value`);
  128. const realClick = async (sel) => {
  129. 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 }; })()`);
  130. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: r.x, y: r.y, button: 'none' });
  131. await sleep(120);
  132. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  133. await sleep(100);
  134. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  135. await sleep(700);
  136. };
  137. const typeInto = async (n, text) => {
  138. await ev(`document.querySelectorAll('date-picker input')[${n}].focus()`);
  139. await ev(`document.querySelectorAll('date-picker input')[${n}].select()`);
  140. await page.send('Input.insertText', { text });
  141. await sleep(400);
  142. };
  143. check('two fields with their names', (await ev(`[...document.querySelectorAll('date-picker input')].map(i => i.name).join()`)) === 'arrival,departure');
  144. check('the month is closed at first', !(await ev(pop(0))) && !(await ev(pop(1))));
  145. await realClick('date-picker input[name=arrival]');
  146. await page.waitFor(pop(0), { label: 'popup open' });
  147. check('click on the field opens the month under it', (await ev(pop(0))) && !(await ev(pop(1))));
  148. 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 }; })()`);
  149. check('the month sits right under the field', pos.dx < 2 && pos.dy >= 0 && pos.dy < 12, JSON.stringify(pos));
  150. await ev(`document.querySelector('date-picker input[name=arrival]').__mark = 1`);
  151. await realClick('date-picker date-field:nth-child(1) ol.days li:not(.outside) time[datetime$="-15"]');
  152. const picked = await val(0);
  153. check('the field element is the same one after picking (not re-created)', (await ev(`document.querySelector('date-picker input[name=arrival]').__mark`)) === 1);
  154. check('a picked day is in the field as YYYY-MM-DD', /^\d{4}-\d{2}-15$/.test(picked), picked);
  155. check('the month closes after picking', !(await ev(pop(0))));
  156. // the month arrows page
  157. await realClick('date-picker input[name=departure]');
  158. await page.waitFor(pop(1), { label: 'popup open 2' });
  159. const dt0 = await ev(`document.querySelectorAll('date-picker h2')[1].textContent`);
  160. await realClick('date-picker date-field:nth-child(2) button.next');
  161. check('the next-month arrow changes the month', (await ev(`document.querySelectorAll('date-picker h2')[1].textContent`)) !== dt0);
  162. await realClick('date-picker date-field:nth-child(2) ol.days li:not(.outside) time[datetime$="-20"]');
  163. 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));
  164. // typing: a date in another month opens on that month and is marked
  165. await typeInto(0, '2028-02-29');
  166. check('typing works: the field holds the typed date', (await val(0)) === '2028-02-29', await val(0));
  167. 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');
  168. await typeInto(0, '2027-02-30');
  169. check('an impossible date marks the field invalid', (await ev(`document.querySelectorAll('date-picker input')[0].getAttribute('aria-invalid')`)) === 'true');
  170. await typeInto(0, '2028-02-29');
  171. await sleep(300); await shot('picker');
  172. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
  173. await sleep(300);
  174. check('Escape closes the month', !(await ev(pop(0))));
  175. await realClick('h1'); await sleep(200);
  176. // the form posts both fields by name
  177. await ev(`document.querySelector('date-picker-demo form button[type=submit]').click()`);
  178. await page.waitFor(`location.search.includes('arrival=2028-02-29')`, { label: 'form posted' });
  179. 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'));
  180. 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());
  181. // the date range picker: a start click, an end click, both in the field, the days between highlighted
  182. check('home lists the range picker', home.includes('id="open-range-picker"'));
  183. check('range picker README is served', (await fetch(BASE + '/range-picker/README.md')).ok);
  184. await page.goto(BASE + '/range-picker');
  185. await page.waitForSelector('#range-picker-input');
  186. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  187. await sleep(1500);
  188. const rvis = () => ev(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`);
  189. const rval = () => ev(`document.getElementById('range-picker-input').value`);
  190. const day = (n) => ev(`document.querySelector('range-picker ol.days li:not(.outside) time[datetime$="-${n}"]').closest('li').click()`);
  191. check('range: month is closed at first', !(await rvis()));
  192. await page.click('#range-picker-input');
  193. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup open' });
  194. await day('20');
  195. check('range: the first click is the start, the month stays open', /^\d{4}-\d{2}-20 – $/.test(await rval()) && await rvis(), await rval());
  196. await day('10');
  197. const rv = await rval();
  198. check('range: second (earlier) click swaps: start – end in the field', /^\d{4}-\d{2}-10 – \d{4}-\d{2}-20$/.test(rv), rv);
  199. await sleep(500);
  200. check('range: the month closes after the end', !(await rvis()));
  201. await page.click('#range-picker-input');
  202. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup reopen' });
  203. 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) }))()`);
  204. check('range: start and end marked, the 9 days between highlighted', hl.sel.join() === '10,20' && hl.between.length === 9, JSON.stringify(hl));
  205. await shot('range');
  206. 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 })); })()`);
  207. await page.waitFor(`document.querySelectorAll('range-picker li.between').length === 27`, { label: 'typed range marked' });
  208. check('range: a typed range shows its month, 27 days between', true);
  209. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-30'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  210. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'true'`, { label: 'impossible range marked' });
  211. check('range: an impossible range marks the field invalid', true);
  212. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-29'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  213. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'false'`, { label: 'valid again' });
  214. await ev(`document.querySelector('form button[type=submit]').click()`);
  215. await page.waitFor(`location.search.length > 0`, { label: 'form posted' });
  216. const q = decodeURIComponent(await ev(`location.search`)).replace(/\+/g, ' ');
  217. check('range: the form posts the period by the field name', q.includes('range=2028-02-01 – 2028-02-29'), q);
  218. check('range picker has no .js file', !existsSync(join(APP, 'components/range-picker/range-picker.js')));
  219. 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());
  220. // ticket #4: the one-file upload (pure Hybriel): choose / drop -> name, size, progress -> listed; the app stores it
  221. {
  222. check('home lists the file upload', home.includes('id="open-file-upload"'));
  223. check('file upload README is served', (await fetch(BASE + '/file-upload/README.md')).ok);
  224. check('file upload has no .js file', !existsSync(join(APP, 'components/file-upload/file-upload.js')));
  225. 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());
  226. await page.goto(BASE + '/file-upload');
  227. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  228. await sleep(600);
  229. const FU = (s) => `document.querySelector('file-upload ${s}')`;
  230. const mk = (name, n) => `const dt = new DataTransfer(); dt.items.add(new File([new Uint8Array(${n}).fill(66)], '${name}', { type: 'text/plain' }));`;
  231. 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 })); })()`);
  232. await page.waitFor(`${FU('.state')}.textContent === 'Uploaded'`, { timeout: 30000, label: 'uploaded' });
  233. check('upload: name and size shown', (await ev(FU('.name') + '.textContent')) === 'report.txt' && (await ev(FU('.size') + '.textContent')) === '3.0 MB');
  234. check('upload: progress bar reaches 100%', (await ev(FU('progress') + '.value')) === 100 && (await ev('window.__max')) >= 1);
  235. check('upload: listed under Uploaded', (await ev(FU('ul.uploaded li') + '.textContent')) === 'report.txt — 3.0 MB');
  236. const stored = execSync(`ls -l ${join(APP, 'storage/uploads')} | grep -c ' 3145728 '`).toString().trim();
  237. check('upload: the app stored all bytes', Number(stored) >= 1, stored);
  238. // choosing a second file (input) adds a second row
  239. const { root } = await page.send('DOM.getDocument');
  240. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'file-upload input[type=file]' });
  241. writeFileSync(join(SCRATCH, 'pick.txt'), 'hello');
  242. await page.send('DOM.setFileInputFiles', { files: [join(SCRATCH, 'pick.txt')], nodeId });
  243. await page.waitFor(`document.querySelectorAll('file-upload ul.uploaded li').length === 2`, { timeout: 30000, label: 'chosen file listed' });
  244. 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');
  245. check('upload: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  246. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  247. await sleep(300); await shot('file-upload-narrow');
  248. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  249. await sleep(200); await shot('file-upload');
  250. }
  251. // ticket #5 (mission 005): the upload for several files, pure Hybriel (emit server uploadFile per file, hybriel#94): REAL drops of files
  252. // from disk (Chrome's drag and drop, Input.dispatchDragEvent), the multiple file input, a row per file with live progress, one file at a
  253. // 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
  254. // the waiting is seen. Screenshots .scratch/gate-files-upload-{1280,390}.png.
  255. {
  256. check('home lists the upload for several files', home.includes('id="open-files-upload"'));
  257. check('files upload README is served', (await fetch(BASE + '/files-upload/README.md')).ok);
  258. 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());
  259. const FD = join(SCRATCH, 'gate-files');
  260. mkdirSync(FD, { recursive: true });
  261. 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));
  262. const F = (n) => join(FD, n);
  263. // its own tab: the over-limit file's expected 413 stays out of the main tab's console checks
  264. const page = await browser.newPage();
  265. const ev = (e) => page.evaluate(e);
  266. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  267. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  268. await page.goto(BASE + '/files-upload');
  269. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  270. await sleep(600);
  271. 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('|'))`);
  272. const summary = () => ev(`(document.querySelector('files-upload output.summary') || {}).textContent`);
  273. // a REAL drop of files (Chrome's own drag and drop through the Input domain, files from disk)
  274. const dropFiles = async (names) => {
  275. const b = await page.box('files-upload drop-zone');
  276. if (!b) return;
  277. const data = { items: [], files: names.map(F), dragOperationsMask: 1 };
  278. for (const type of ['dragEnter', 'dragOver', 'drop']) await page.send('Input.dispatchDragEvent', { type, x: Math.round(b.x), y: Math.round(b.y), data });
  279. };
  280. await page.send('Network.enable');
  281. const slow = (on) => page.send('Network.emulateNetworkConditions', { offline: false, latency: on ? 20 : 0, downloadThroughput: -1, uploadThroughput: on ? 2 * 1024 * 1024 : -1 });
  282. await slow(true);
  283. 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 }); })()`);
  284. 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 }); })()`);
  285. await dropFiles(['photo.jpg', 'notes.txt', 'slides.pdf']);
  286. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 3`, { timeout: 10000, label: 'three rows' }).catch(() => {});
  287. const r0 = await rows();
  288. 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));
  289. 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));
  290. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 3`, { timeout: 60000, label: 'three uploaded' }).catch(() => {});
  291. const r1 = await rows();
  292. const sn = await ev('window.__snaps');
  293. 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));
  294. check('#5: all three end Uploaded with a full bar', r1.length === 3 && r1.every(r => r.endsWith('|Uploaded|1')), JSON.stringify(r1));
  295. check('#5: the line under them says 3 of 3 uploaded', (await summary()) === '3 of 3 uploaded', await summary());
  296. const sizes = execSync(`ls -l ${join(APP, 'storage/uploads')}`).toString();
  297. 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);
  298. const fr = await ev('window.__fr');
  299. 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)));
  300. 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));
  301. // choosing several files (the input takes more than one)
  302. const { root } = await page.send('DOM.getDocument');
  303. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload input[type=file]' });
  304. 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`));
  305. try { await page.send('DOM.setFileInputFiles', { files: [F('a.txt'), F('b.txt')], nodeId }); } catch {}
  306. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 5`, { timeout: 30000, label: 'five uploaded' }).catch(() => {});
  307. const r2 = await rows();
  308. 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()]));
  309. // a file over the app's limit fails in its own row; the next file still goes
  310. await dropFiles(['huge.bin', 'a.txt']);
  311. await page.waitFor(`document.querySelectorAll('files-upload li.done, files-upload li.failed').length === 7`, { timeout: 60000, label: 'seven ended' }).catch(() => {});
  312. const r3 = await rows();
  313. 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()]));
  314. // a drop during an upload waits in its row and follows
  315. await dropFiles(['big.bin']);
  316. await page.waitFor(`!!document.querySelector('files-upload li.busy')`, { timeout: 10000, label: 'big busy' }).catch(() => {});
  317. await dropFiles(['late.txt']);
  318. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 9`, { timeout: 10000, label: 'late row' }).catch(() => {});
  319. const r4 = await rows();
  320. 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)));
  321. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 8`, { timeout: 60000, label: 'all ended' }).catch(() => {});
  322. const r5 = await rows();
  323. 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()]));
  324. await slow(false);
  325. await page.send('Network.disable');
  326. 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());
  327. await ev('scrollTo(0, 0)'); await sleep(200); await shot('files-upload-1280');
  328. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  329. await ev('scrollTo(0, 0)'); await sleep(300); await shot('files-upload-390');
  330. await page.close();
  331. }
  332. // ==== #18 START — ticket #18 (mission 008): FilesUpload PICK FIRST, SEND LATER (for HyperConductor's chat attachments, hycon#46), pure
  333. // Hybriel. The demo `/files-upload/pick` is a chat input: the page owns the list (`files = attached`, `onChange`), the text field + Send
  334. // sit inside the component. REAL input only: Chrome's own drag and drop of files from disk, the file input (DOM.setFileInputFiles), a
  335. // 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.
  336. // Checked: nothing is uploaded while picking; thumbnails drawn (naturalWidth > 0), other files as name + size + kind; a file over maxSize
  337. // 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
  338. // 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,
  339. // the Camera button (accept image/*, capture), no horizontal overflow. Screenshots .scratch/gate-files-pick-{1280,390}.png.
  340. {
  341. 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; };
  342. const png = (w, h, rgb) => {
  343. 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]); };
  344. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  345. 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);
  346. 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))]);
  347. };
  348. const PD = join(SCRATCH, 'gate-pick');
  349. mkdirSync(PD, { recursive: true });
  350. writeFileSync(join(PD, 'photo.png'), png(320, 200, [180, 40, 40]));
  351. writeFileSync(join(PD, 'notes.txt'), Buffer.alloc(1200, 110));
  352. writeFileSync(join(PD, 'a.txt'), 'hello');
  353. writeFileSync(join(PD, 'huge.bin'), Buffer.alloc(3 * 1048576, 1));
  354. const longName = 'a-very-long-file-name-without-any-break-that-a-phone-must-wrap-somewhere-2026-10-20.txt';
  355. writeFileSync(join(PD, longName), 'x'.repeat(300));
  356. const P = (n) => join(PD, n);
  357. const sizeOf = (n) => readFileSync(P(n)).length;
  358. check('#18: the home links the pick-first demo', home.includes('id="open-files-upload-pick"') && home.includes('href="/files-upload/pick"'));
  359. const page = await browser.newPage();
  360. const ev = (e) => page.evaluate(e);
  361. 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')); };
  362. // null-safe reads and actions: on the old code the elements are missing, every check must FAIL, not end the gate
  363. const val = (sel, prop) => ev(`(document.querySelector(${JSON.stringify(sel)}) || {})[${JSON.stringify(prop)}]`);
  364. const tryDo = async (f) => { try { await f(); } catch {} };
  365. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  366. await browser.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  367. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  368. await page.goto(BASE + '/files-upload/pick');
  369. await hydrated();
  370. await sleep(600);
  371. 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('|'))`);
  372. const refusedRows = () => ev(`[...document.querySelectorAll('files-upload ul.files li.refused')].map(li => li.querySelector('.name').textContent + '|' + li.querySelector('.state').textContent)`);
  373. const uploadsSeen = () => ev(`performance.getEntriesByType('resource').filter(r => r.name.includes('/__hl/upload')).length`);
  374. const storedCount = () => existsSync(join(APP, 'storage/uploads')) ? execSync(`ls ${join(APP, 'storage/uploads')} | wc -l`).toString().trim() : '0';
  375. const stored0 = storedCount();
  376. const dropOn = async (sel, names) => {
  377. const b = await page.box(sel);
  378. if (!b) return;
  379. const data = { items: [], files: names.map(P), dragOperationsMask: 1 };
  380. for (const type of ['dragEnter', 'dragOver', 'drop']) await page.send('Input.dispatchDragEvent', { type, x: Math.round(b.x), y: Math.round(b.y), data });
  381. };
  382. // a real drop: on the component's drop zone
  383. await dropOn('files-upload drop-zone', ['photo.png', 'notes.txt']);
  384. 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(() => {});
  385. const q1 = await prows();
  386. 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));
  387. 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'));
  388. // choose: the "Choose files" input (several at once)
  389. {
  390. const { root } = await page.send('DOM.getDocument');
  391. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload label.choose input[type=file]' });
  392. try { await page.send('DOM.setFileInputFiles', { files: [P('a.txt')], nodeId }); } catch {}
  393. }
  394. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 3`, { timeout: 10000, label: 'three picked' }).catch(() => {});
  395. const q2 = await prows();
  396. 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));
  397. // 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
  398. await page.send('Page.bringToFront');
  399. await tryDo(() => page.focus('#chat-text'));
  400. 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; } })()`);
  401. const ctrlV = async () => {
  402. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  403. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  404. };
  405. await ctrlV();
  406. 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(() => {});
  407. const q3 = await prows();
  408. 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));
  409. // a text paste is left to the field
  410. await ev(`navigator.clipboard.writeText('pasted words')`);
  411. await ctrlV();
  412. await sleep(500);
  413. 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'));
  414. // 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
  415. await dropOn('#chat-text', ['huge.bin']);
  416. await page.waitFor(`document.querySelectorAll('files-upload li.refused').length === 1`, { timeout: 10000, label: 'refused' }).catch(() => {});
  417. 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()]));
  418. 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()}`);
  419. // ✕ removes one (a real click), the thumbnails stay drawn
  420. await tryDo(() => page.click('files-upload li.picked[data-i="1"] button.remove', { timeout: 3000 }));
  421. await page.waitFor(`document.querySelectorAll('files-upload li.picked').length === 3`, { timeout: 10000, label: 'removed' }).catch(() => {});
  422. await sleep(400);
  423. const q4 = await prows();
  424. 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));
  425. 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');
  426. await shot('files-pick-1280');
  427. // Send: real typing, a real click; the page's face gets the text and every byte, the list is emptied
  428. await tryDo(() => page.type('#chat-text', ' and three files', {}));
  429. const stored1 = Number(storedCount());
  430. await tryDo(() => page.click('#chat-send', { timeout: 3000 }));
  431. await page.waitFor(`document.querySelectorAll('#sent li').length === 1`, { timeout: 30000, label: 'sent' }).catch(() => {});
  432. const pastedSize = Number(((q4[2] || '').match(/\|(\d+) B\|/) || [])[1]); // the pasted File's size (Chrome's clipboard encodes its own PNG)
  433. const sentFiles = await ev(`(document.querySelector('#sent li .sent-files') || {}).textContent`);
  434. 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'
  435. && sentFiles === `photo.png (${sizeOf('photo.png')} B), a.txt (5 B), image.png (${pastedSize} B)` && Number(storedCount()) === stored1 + 3, sentFiles + ' stored ' + storedCount());
  436. 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')) === '');
  437. // the 390 px phone, touch: targets, the camera, no overflow (with a long file name and a refused row)
  438. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  439. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  440. await page.goto(BASE + '/files-upload/pick');
  441. await hydrated();
  442. await sleep(600);
  443. {
  444. const { root } = await page.send('DOM.getDocument');
  445. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload label.choose input[type=file]' });
  446. try { await page.send('DOM.setFileInputFiles', { files: [P('photo.png'), P(longName), P('huge.bin')], nodeId }); } catch {}
  447. }
  448. 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(() => {});
  449. 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); })`);
  450. 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));
  451. 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; })()`));
  452. 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`));
  453. await shot('files-pick-390');
  454. // 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
  455. await page.goto(BASE + '/files-upload');
  456. await hydrated();
  457. await sleep(600);
  458. 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)]; })()`);
  459. 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));
  460. 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')`));
  461. await page.send('Page.bringToFront');
  462. await tryDo(() => page.focus('files-upload drop-zone'));
  463. 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 })]); })()`);
  464. await ctrlV();
  465. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 1`, { timeout: 20000, label: 'pasted upload' }).catch(() => {});
  466. 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');
  467. check('#18: no console errors', page.problems().filter(m => !/favicon/.test(m.text)).length === 0, page.dumpConsole());
  468. await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  469. await page.close();
  470. }
  471. // ==== #18 END
  472. // layouts#2 (mission 006): THE COMMENTS BLOCK, pure Hybriel — the host passes the list + the current user and hears post / edit /
  473. // delete / like through the four functions it hands (hybriel#87); the demo's page makes a new list each time (lib/comments.hl).
  474. // REAL clicks and keys only: a comment typed into the Markdown editor and posted (button and Ctrl+Enter), an edit typed and saved
  475. // shows "edited" + the earlier version, Edit / Delete only on the user's own comments (alice, bob, nobody), Delete asks first,
  476. // the like toggles and counts, "1 comment" / "n comments". Own tab. Screenshots .scratch/gate-comments-{1280,390}.png.
  477. {
  478. check('home lists the comments block', home.includes('id="open-comments"'));
  479. check('comments README is served', (await fetch(BASE + '/comments/README.md')).ok);
  480. 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());
  481. const ssr = await (await fetch(BASE + '/comments')).text();
  482. 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);
  483. const page = await browser.newPage();
  484. const ev = (e) => page.evaluate(e);
  485. 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')); };
  486. 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); };
  487. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  488. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  489. await page.goto(BASE + '/comments');
  490. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  491. const R = (id) => `document.querySelector('comments-block li.comment[data-id="${id}"]')`;
  492. const art = (id) => ev(`(() => { const li = ${R(id)}; const a = li && li.querySelector('md-editor[data-readonly="true"] article'); return a ? a.innerHTML : null; })()`);
  493. const btns = (id) => ev(`[...${R(id)}.querySelectorAll('comment-actions button')].map(b => b.textContent).join('|')`);
  494. const ids = () => ev(`[...document.querySelectorAll('comments-block li.comment')].map(li => li.dataset.id).join(',')`);
  495. const count = () => ev(`document.querySelector('comments-block .comments-count').textContent`);
  496. const told = () => ev(`document.querySelector('#comments-told').textContent`);
  497. const newValue = () => ev(`(document.querySelector('comments-block form.comment-form md-editor input.value') || {}).value`);
  498. await page.waitFor(`!!${R('c1')}.querySelector('md-editor article ul')`, { label: 'comment Markdown drawn' }).catch(() => {});
  499. check('comments: each text shows as formatted Markdown (bold, italic, code, link, list) by MdEditor readonly',
  500. (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'));
  501. check('comments: a shown text is not editable, and shows no toolbar, no source switch',
  502. 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; })()`));
  503. 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'; })()`));
  504. // POST, typed in the Markdown editor with real keys: **x** and `x` format while typing; the Comment button sends it
  505. await page.click('comments-block form.comment-form md-editor article');
  506. await typeText('Hello **world** and `code` here'); await sleep(200);
  507. 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());
  508. await page.click('comments-block button.comment-post');
  509. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 4 && !!${R('n1')}.querySelector('md-editor article p')`, { label: 'posted' }).catch(() => {});
  510. await sleep(300);
  511. 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'
  512. && (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(' / '));
  513. 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(' '));
  514. // Ctrl+Enter in the editor sends it too
  515. await page.click('comments-block form.comment-form md-editor article');
  516. await typeText('Second, by keyboard'); await key('Enter', 'Enter', 13, '\r', 2);
  517. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 5 && !!${R('n2')}.querySelector('md-editor article p')`, { label: 'posted by Ctrl+Enter' }).catch(() => {});
  518. 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')));
  519. // an empty editor sends nothing
  520. await page.click('comments-block button.comment-post'); await sleep(400);
  521. check('comments: an empty form sends nothing', (await ids()) === 'c1,c2,c3,n1,n2');
  522. // LIKE: toggles and counts
  523. 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');
  524. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`);
  525. await page.waitFor(`${R('c1')}.querySelector('.comment-like').textContent === '♥ 3' && document.querySelector('#comments-told').textContent === 'like c1'`, { label: 'liked' }).catch(() => {});
  526. await sleep(300);
  527. 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(' / '));
  528. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`);
  529. await page.waitFor(`${R('c1')}.querySelector('.comment-like').textContent === '♡ 2'`, { label: 'unliked' }).catch(() => {});
  530. await sleep(300);
  531. 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(' / '));
  532. // a text changed from outside (in an app: a push after another user's edit) is drawn anew, nothing pressed in the block
  533. await page.click('#elsewhere');
  534. await page.waitFor(`/elsewhere/.test(${R('c2')}.querySelector('md-editor[data-readonly="true"] article').innerHTML)`, { label: 'pushed edit' }).catch(() => {});
  535. 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'));
  536. // EDIT: the editor opens with the text, typed keys, Save → the new text, "edited" with the earlier version
  537. check('comments: "edited" only on an edited comment', (await ev(`!!${R('c2')}.querySelector('details.comment-history')`)) && !(await ev(`!!${R('c3')}.querySelector('details.comment-history')`)));
  538. await page.click(`comments-block li.comment[data-id="c3"] .comment-edit-start`);
  539. await page.waitFor(`!!${R('c3')}.querySelector('form.comment-edit article p')`, { label: 'edit form' }).catch(() => {});
  540. 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`)));
  541. await page.click(`comments-block li.comment[data-id="c3"] form.comment-edit article`);
  542. await key('End', 'End', 35, undefined, 2);
  543. await typeText(' Now **edited**.'); await sleep(200);
  544. await page.click(`comments-block li.comment[data-id="c3"] .comment-save`);
  545. await page.waitFor(`!!${R('c3')}.querySelector('details.comment-history')`, { label: 'edited' }).catch(() => {});
  546. await sleep(300);
  547. 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(' / '));
  548. await page.click(`comments-block li.comment[data-id="c3"] details.comment-history summary`); await sleep(200);
  549. check('comments: "edited" opens the history — "Edited once" and the earlier text', (await ev(`${R('c3')}.querySelector('details.comment-history').open`))
  550. && (await ev(`${R('c3')}.querySelector('.comment-history-title').textContent`)) === 'Edited once'
  551. && (await ev(`${R('c3')}.querySelector('details.comment-history li pre').textContent`)) === 'A long word wraps on a phone: Donaudampfschifffahrtsgesellschaftskapitänswitwenrentenversicherung.'
  552. && (await ev(`${R('c3')}.querySelector('details.comment-history li pre').getBoundingClientRect().height > 0`)));
  553. 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**.');
  554. // Cancel keeps the text
  555. await page.click(`comments-block li.comment[data-id="n2"] .comment-edit-start`);
  556. await page.waitFor(`!!${R('n2')}.querySelector('form.comment-edit article p')`, { label: 'edit form n2' }).catch(() => {});
  557. await page.click(`comments-block li.comment[data-id="n2"] form.comment-edit article`);
  558. await typeText(' not this'); await sleep(150);
  559. await page.click(`comments-block li.comment[data-id="n2"] .comment-cancel`); await sleep(400);
  560. 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')`)));
  561. // EDIT / DELETE ONLY FOR THE AUTHOR
  562. 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')));
  563. await page.click('#as-bob');
  564. await page.waitFor(`${R('c2')}.querySelectorAll('comment-actions button').length === 3`, { label: 'as bob' }).catch(() => {});
  565. 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(' / '));
  566. await page.click('#as-nobody');
  567. await page.waitFor(`!document.querySelector('comments-block form.comment-form')`, { label: 'as nobody' }).catch(() => {});
  568. 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.');
  569. await page.click(`comments-block li.comment[data-id="c1"] .comment-like`); await sleep(400);
  570. check('comments: as nobody the like does nothing', (await ev(`${R('c1')}.querySelector('.comment-like').textContent`)) === '♡ 2' && (await told()) === 'edit c3');
  571. // DELETE asks first; Keep keeps; the counter says 1 comment / n comments
  572. await page.click('#as-alice');
  573. await page.waitFor(`!!document.querySelector('comments-block form.comment-form')`, { label: 'as alice' }).catch(() => {});
  574. await page.click(`comments-block li.comment[data-id="c1"] .comment-delete`);
  575. await page.waitFor(`!!${R('c1')}.querySelector('comment-ask')`, { label: 'ask' }).catch(() => {});
  576. 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');
  577. await page.click(`comments-block li.comment[data-id="c1"] .comment-delete-keep`); await sleep(300);
  578. check('comments: Keep — the comment stays, the question goes', (await ids()) === 'c1,c2,c3,n1,n2' && !(await ev(`!!${R('c1')}.querySelector('comment-ask')`)));
  579. for (const id of ['c1', 'c3', 'n1', 'n2']) {
  580. await page.click(`comments-block li.comment[data-id="${id}"] .comment-delete`);
  581. await page.waitFor(`!!${R(id)}.querySelector('.comment-delete-yes')`, { label: 'ask ' + id }).catch(() => {});
  582. await page.click(`comments-block li.comment[data-id="${id}"] .comment-delete-yes`);
  583. await page.waitFor(`!${R(id)}`, { label: 'gone ' + id }).catch(() => {});
  584. 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(' / '));
  585. }
  586. check('comments: counter "1 comment" for one', (await ids()) === 'c2' && (await count()) === '1 comment', (await ids()) + ' ' + (await count()));
  587. await page.click('#as-bob');
  588. await page.waitFor(`!!${R('c2')}.querySelector('.comment-delete')`, { label: 'bob delete' }).catch(() => {});
  589. await page.click(`comments-block li.comment[data-id="c2"] .comment-delete`);
  590. await page.waitFor(`!!${R('c2')}.querySelector('.comment-delete-yes')`, { label: 'ask c2' }).catch(() => {});
  591. await page.click(`comments-block li.comment[data-id="c2"] .comment-delete-yes`);
  592. await page.waitFor(`!${R('c2')}`, { label: 'gone c2' }).catch(() => {});
  593. 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.');
  594. await page.click('comments-block form.comment-form md-editor article');
  595. await typeText('Back again'); await key('Enter', 'Enter', 13, '\r', 2);
  596. await page.waitFor(`document.querySelectorAll('comments-block li.comment').length === 1`, { label: 'one again' }).catch(() => {});
  597. 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');
  598. check('comments: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  599. // the look: a fresh thread at 1280 and 390 px; on the phone nothing is wider than the screen
  600. await page.goto(BASE + '/comments');
  601. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  602. await page.waitFor(`!!${R('c1')}.querySelector('md-editor article ul')`, { label: 'drawn' }).catch(() => {});
  603. await page.click(`comments-block li.comment[data-id="c2"] details.comment-history summary`); await sleep(300);
  604. await ev('scrollTo(0, 0)'); await shot('comments-1280');
  605. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  606. await sleep(400);
  607. 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`)));
  608. await ev('scrollTo(0, 0)'); await shot('comments-390');
  609. await page.close();
  610. }
  611. // ==== m009 START — tickets#27 (mission 009): ATTACHMENTS IN THE COMMENTS BLOCK. `attach = "true"` puts the block's form inside the
  612. // shared FilesUpload (pick mode); the editor in it has files = "off" (no File button; pasted / dropped files go on to FilesUpload);
  613. // `onPost(text, files)`; a comment record's `files` ([{ name, url, image, size }]) show as thumbnails (open the full picture) or rows
  614. // (kind, name, size; no url = no link). REAL input: the chooser's file input (DOM.setFileInputFiles), a real Ctrl+V of an image into
  615. // the editor, real clicks / keys; the demo's face stores the files (lib/uploads.hl) and the page shows the new comment's files.
  616. // Null-safe reads: on the old code every check FAILS instead of ending the gate. Screenshots .scratch/gate-comments-attach-{1280,390}.png.
  617. {
  618. 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; };
  619. const png = (w, h, rgb) => {
  620. 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]); };
  621. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  622. 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);
  623. 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))]);
  624. };
  625. const AD = join(SCRATCH, 'gate-attach');
  626. mkdirSync(AD, { recursive: true });
  627. writeFileSync(join(AD, 'shot-390.png'), png(390, 300, [20, 120, 200]));
  628. writeFileSync(join(AD, 'shot-1280.png'), png(640, 400, [200, 80, 20]));
  629. writeFileSync(join(AD, 'big.bin'), Buffer.alloc(3 * 1048576, 7));
  630. writeFileSync(join(AD, 'log.txt'), 'line one\nline two\n');
  631. const A = (n) => join(AD, n);
  632. const ssr = (await (await fetch(BASE + '/comments')).text()).replace(/<!--[\[\]]-->/g, '');
  633. 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',
  634. /<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)
  635. && /<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)
  636. && /<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]);
  637. const page = await browser.newPage();
  638. const ev = (e) => page.evaluate(e);
  639. 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')); };
  640. const tryDo = async (f) => { try { await f(); } catch {} };
  641. 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); };
  642. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  643. const hydrated = () => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  644. const R = (id) => `document.querySelector('comments-block li.comment[data-id="${id}"]')`;
  645. 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; })()`);
  646. 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'))`);
  647. const told = () => ev(`(document.querySelector('#comments-told') || {}).textContent`);
  648. const chooseFiles = async (names) => {
  649. const { root } = await page.send('DOM.getDocument');
  650. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'comments-block files-upload label.choose input[type=file]' });
  651. try { await page.send('DOM.setFileInputFiles', { files: names.map(A), nodeId }); } catch {}
  652. };
  653. await browser.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  654. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  655. await page.goto(BASE + '/comments');
  656. await hydrated();
  657. await page.waitFor(`!!${R('c2')} && [...${R('c2')}.querySelectorAll('ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 10000, label: 'thumbs' }).catch(() => {});
  658. const c2 = await filesOf('c2');
  659. 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));
  660. check('m009: the form sits inside the FilesUpload (pick mode); the editor in it has no File button (files = "off")',
  661. 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 drop-zone label.choose'); })()`));
  662. // choose two pictures, then a REAL Ctrl+V of a third into the editor
  663. await chooseFiles(['shot-390.png', 'shot-1280.png']);
  664. 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(() => {});
  665. await sleep(400);
  666. await tryDo(() => page.click('comments-block form.comment-form md-editor article'));
  667. 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(() => {});
  668. await typeText('Two shots and a paste'); await sleep(200);
  669. 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; } })()`);
  670. await page.send('Page.bringToFront');
  671. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  672. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  673. 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(() => {});
  674. const pk = await picked();
  675. 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)',
  676. 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'
  677. && (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`)));
  678. // a file over the block's maxFileSize (2 MB): refused in its row, not added
  679. await chooseFiles(['big.bin']);
  680. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.refused').length === 1`, { timeout: 10000, label: 'refused' }).catch(() => {});
  681. 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);
  682. // send with Ctrl+Enter: the host gets text + the three files, its face stores them, the new comment shows three drawn thumbnails
  683. await tryDo(() => page.click('comments-block form.comment-form md-editor article'));
  684. await key('Enter', 'Enter', 13, '\r', 2);
  685. 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(() => {});
  686. const n1 = await filesOf('n1') || [];
  687. 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',
  688. (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));
  689. const first = (n1[0] || '').split(':').slice(2).join(':');
  690. const full = first ? await fetch(BASE + first) : null;
  691. const fullBuf = full ? Buffer.from(await full.arrayBuffer()) : Buffer.alloc(0);
  692. check('m009: the thumbnail\'s link is the stored picture, byte for byte', !!full && full.ok && fullBuf.equals(readFileSync(A('shot-390.png'))), first);
  693. 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`)) === '');
  694. // a REAL click on a thumbnail opens the full picture in a new tab
  695. const tabs0 = (await browser.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length;
  696. await tryDo(() => page.click(`comments-block li.comment[data-id="n1"] a.comment-thumb`, { timeout: 3000 }));
  697. let opened = null;
  698. 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); }
  699. 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));
  700. if (opened) await browser.conn.send('Target.closeTarget', { targetId: opened.targetId }).catch(() => {});
  701. // files only, no text: a post of one text file is a row with its kind, name and size, linked
  702. await chooseFiles(['log.txt']);
  703. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 1`, { timeout: 10000, label: 'txt' }).catch(() => {});
  704. await tryDo(() => page.click('comments-block button.comment-post', { timeout: 3000 }));
  705. await page.waitFor(`!!${R('n2')}`, { timeout: 30000, label: 'files only' }).catch(() => {});
  706. 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')));
  707. await tryDo(() => page.click('comments-block button.comment-post', { timeout: 3000 })); await sleep(400);
  708. check('m009: an empty form (no text, no file) still sends nothing', !(await ev(`!!${R('n3')}`)));
  709. check('m009: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  710. await ev('scrollTo(0, 0)'); await shot('comments-attach-1280');
  711. // the 390 px phone, touch: targets ≥ 44 × 44 (thumbnails, file rows, Choose files, Camera, Comment, ✕), nothing wider than the screen
  712. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  713. await page.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  714. await page.goto(BASE + '/comments');
  715. await hydrated();
  716. await page.click('#as-alice').catch(() => {});
  717. await chooseFiles(['shot-390.png', 'log.txt']);
  718. await page.waitFor(`document.querySelectorAll('comments-block files-upload li.picked').length === 2`, { timeout: 10000, label: 'phone picked' }).catch(() => {});
  719. await sleep(500);
  720. 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); })`);
  721. 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));
  722. 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`));
  723. await ev('scrollTo(0, 0)'); await shot('comments-attach-390');
  724. await page.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  725. await page.close();
  726. }
  727. // ==== m009 END
  728. // the pagination: 89 pages; the ticket's three shapes
  729. check('home lists the pagination', home.includes('id="open-pagination"'));
  730. check('pagination README is served', (await fetch(BASE + '/pagination/README.md')).ok);
  731. await page.goto(BASE + '/pagination');
  732. await page.waitForSelector('#pagination-items');
  733. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  734. await sleep(500);
  735. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  736. const clickPg = (t) => ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === ${JSON.stringify(t)}).click()`);
  737. const waitPg = (t) => page.waitFor(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ') === ${JSON.stringify(t)}`, { label: 'pagination ' + t });
  738. check('pagination: first page shows 1 2 3 4 … 89 Next', (await pg()) === '1 2 3 4 … 89 Next', await pg());
  739. await clickPg('4'); await waitPg('Previous 1 2 3 4 5 … 89 Next');
  740. check('pagination: page 4 fills a one-page gap: Previous 1 2 3 4 5 … 89 Next', true);
  741. 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');
  742. await waitPg('Previous 1 … 6 7 8 … 89 Next');
  743. check('pagination: middle shows first, last, current ± 1', true);
  744. check('pagination: current page is marked', (await ev(`document.querySelector('#pagination-items li.current button').textContent`)) === '7');
  745. await ev(`document.querySelector('#pagination-items li.gap button').click()`); await sleep(300);
  746. check('pagination: a click on … does nothing', (await pg()) === 'Previous 1 … 6 7 8 … 89 Next');
  747. await clickPg('Previous'); await waitPg('Previous 1 … 5 6 7 … 89 Next');
  748. check('pagination: Previous goes back one page', true);
  749. await clickPg('89'); await waitPg('Previous 1 … 86 87 88 89');
  750. check('pagination: last page shows Previous 1 … 86 87 88 89, no Next', true);
  751. await clickPg('1'); await waitPg('1 2 3 4 … 89 Next');
  752. check('pagination: back on page 1 no Previous', true);
  753. // ticket #16 (mission 005): the host is told the target page on every click — real pointer clicks, keyboard Enter / Space, a script's
  754. // click(); Previous / Next / numbers / the first and last page; nothing for … or the current page. The demo hands `onPage = heardPage`.
  755. {
  756. await page.goto(BASE + '/pagination');
  757. await page.waitForSelector('#pagination-items');
  758. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  759. await sleep(500);
  760. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  761. const heard = () => ev(`(document.getElementById('pagination-heard') || {}).textContent`);
  762. 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`; };
  763. const told = (want) => page.waitFor(`(document.getElementById('pagination-heard') || {}).textContent === ${JSON.stringify(want)}`, { label: 'host told ' + want, timeout: 3000 }).then(() => true, () => false);
  764. 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); };
  765. 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); };
  766. check('#16: the host has heard nothing before a click', (await heard()) === 'none yet', await heard());
  767. 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()]));
  768. 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()]));
  769. 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()]));
  770. 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()]));
  771. 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()]));
  772. 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()]));
  773. const g = await sel('…'); try { await page.click(g, { timeout: 2000 }); } catch {} await sleep(400);
  774. 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()]));
  775. const c = await sel('1'); try { await page.click(c, { timeout: 2000 }); } catch {} await sleep(400);
  776. check('#16: a click on the current page tells nothing', (await heard()) === 'page 1', await heard());
  777. check('#16: keyboard Enter on 3 tells page 3', await pressOn('3', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  778. check('#16: keyboard Space on Next tells page 4', await pressOn('Next', ' ', 'page 4'), JSON.stringify([await heard(), await pg()]));
  779. check('#16: keyboard Enter on Previous tells page 3', await pressOn('Previous', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  780. 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`));
  781. await ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === '89').click()`);
  782. check('#16: a script click() on 89 tells page 89', await told('page 89'), await heard());
  783. 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(' ')`));
  784. check('#16: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  785. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  786. await sleep(300); await shot('pagination-390');
  787. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  788. await sleep(200);
  789. }
  790. await shot('pagination');
  791. check('no console errors on the pagination page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  792. // the Markdown editor: two on one page, real typing and real clicks
  793. check('home lists the Markdown editor', home.includes('id="open-md-editor"'));
  794. const mdr = await fetch(BASE + '/md-editor/README.md');
  795. check('Markdown editor README is served as Markdown', mdr.ok && /markdown/.test(mdr.headers.get('content-type')) && (await mdr.text()).includes('Markdown editor'));
  796. 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());
  797. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  798. await page.goto(BASE + '/md-editor');
  799. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  800. const ED = 'md-editor:nth-of-type(1)';
  801. const md1 = (q) => `document.querySelectorAll('md-editor')[0].${q}`;
  802. const md2 = (q) => `document.querySelectorAll('md-editor')[1].${q}`;
  803. const val1 = () => ev(md1(`querySelector('input.value').value`));
  804. const val2 = () => ev(md2(`querySelector('input.value').value`));
  805. const art1 = () => ev(md1(`querySelector('article').innerHTML`));
  806. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  807. 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());
  808. 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());
  809. check('the canonical form of the value equals it (round trip)', await ev(md1(`mdCanon`) + ` === ` + md1(`querySelector('input.value').value`)));
  810. check('the second editor is empty and shows its placeholder', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('.placeholder')).display`)) === 'block');
  811. // ==== 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
  812. 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'; })()`));
  813. 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`));
  814. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  815. await sleep(300);
  816. const bar390 = await ev(`(() => { const n = document.querySelectorAll('md-editor')[0].querySelector('nav'); const bs = [...n.querySelectorAll('button')].filter(b => getComputedStyle(b).display !== 'none').map(b => b.getBoundingClientRect()); return { rows: new Set(bs.map(r => Math.round(r.top))).size, minW: Math.min(...bs.map(r => r.width)), minH: Math.min(...bs.map(r => r.height)), n: bs.length, barH: n.getBoundingClientRect().height, docW: document.documentElement.scrollWidth }; })()`);
  817. check('m010: at 390 px the toolbar is ONE row (it scrolls sideways) and every button is a 44 px target; the page does not scroll sideways', bar390.rows === 1 && bar390.minW >= 43.9 && bar390.minH >= 43.9 && bar390.docW <= 390, JSON.stringify(bar390));
  818. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  819. // ==== m010 END
  820. 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 }); };
  821. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  822. const enter = () => key('Enter', 'Enter', 13, '\r');
  823. // type into the second editor: heading, bold, code, list
  824. await page.click('md-editor:nth-of-type(2) article');
  825. check('the placeholder goes away when it has text', true);
  826. await typeText('# Title'); await typeText(' '); await typeText('here'); await enter();
  827. await typeText('a **bold** and `code` x'); await enter();
  828. check('typing "# " makes a heading while you type', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  829. const html2 = await ev(md2(`querySelector('article').innerHTML`));
  830. check('typing **x** and `x` formats them', /<strong>bold<\/strong>/.test(html2) && /<code>code<\/code>/.test(html2), html2);
  831. await typeText('- '); await sleep(100);
  832. check('typing "- " makes a list', (await ev(md2(`querySelector('article ul')`) + ' !== null')));
  833. await typeText('item one'); await enter(); await typeText('item two');
  834. await sleep(400);
  835. const v2 = await val2();
  836. 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));
  837. check('the demo shows that value below the editor', (await ev(`document.getElementById('md-value-summary').textContent`)) === v2);
  838. check('the first editor was not touched by typing in the second', (await val1()).startsWith('# Hello'));
  839. check('the editor content survives re-renders of the page (same article element)', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  840. // toolbar: select the first list item in the first editor, Bold, then Undo
  841. 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)})()`);
  842. await selectIn(0, 'li:nth-child(1)');
  843. await page.click('md-editor:nth-of-type(1) nav button.bold'); await sleep(250);
  844. check('toolbar Bold: the selection is **bold** in the value', (await val1()).endsWith('- **first**\n- second'), await val1());
  845. await page.click('md-editor:nth-of-type(1) nav button.undo'); await sleep(250);
  846. check('toolbar Undo takes it back', (await val1()).endsWith('- first\n- second'), await val1());
  847. await selectIn(0, 'h1');
  848. await page.click('md-editor:nth-of-type(1) nav button.heading'); await sleep(250);
  849. check('toolbar heading button: H1 becomes H2', (await val1()).startsWith('## Hello'), await val1());
  850. await selectIn(0, 'ul');
  851. await page.click('md-editor:nth-of-type(1) nav button.ol'); await sleep(250);
  852. check('toolbar numbered list: the bullets become 1. 2.', (await val1()).endsWith('1. first\n2. second'), await val1());
  853. await selectIn(0, 'p');
  854. await page.click('md-editor:nth-of-type(1) nav button.pre'); await sleep(250);
  855. check('toolbar code block: the paragraph becomes a fenced block', /```\nSome .*\n```/.test(await val1()), await val1());
  856. // link: Ctrl+K opens the small form, Apply
  857. 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()})()`);
  858. await page.click('md-editor:nth-of-type(2) nav button.link'); await sleep(250);
  859. check('the link form opens', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('link-form')).display`)) === 'flex');
  860. await ev(md2(`querySelector('link-form input').focus()`));
  861. await typeText('https://example.org/x'); await enter(); await sleep(300);
  862. check('a link is added: [text](url) in the value', (await val2()).includes('# [Title here](https://example.org/x)'), await val2());
  863. 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:'); })());
  864. // paste Markdown in: formatted, plain text; html in it stays text
  865. 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}))})()`);
  866. await sleep(300);
  867. const a1 = await art1();
  868. check('pasted Markdown shows formatted', /<h2>Pasted<\/h2><p>hello <strong>there<\/strong> /.test(a1), a1);
  869. check('pasted HTML stays text (no element made from it)', !/<b>x<\/b>/.test(a1) && (await val1()).includes('\\<b>x\\</b>'), a1);
  870. // the Markdown source switch
  871. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  872. 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');
  873. 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 }))`);
  874. await sleep(200);
  875. 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()));
  876. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  877. 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());
  878. // the form posts both editors by name
  879. await page.click('#md-form button[type=submit]'); await sleep(800);
  880. const url = new URL(await ev('location.href'));
  881. 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);
  882. await shot('md-editor');
  883. 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());
  884. // typed Markdown shortcuts are CONSUMED: the marker disappears, only the formatting stays (real keys, one character at a time)
  885. await page.goto(BASE + '/md-editor');
  886. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  887. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  888. 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); };
  889. const typeR = async (t) => { for (const ch of t) await keyR(ch, ch === ' ' ? 'Space' : '', ch === ' ' ? 32 : undefined, ch); };
  890. const enterR = () => keyR('Enter', 'Enter', 13, '\r');
  891. // ticket #17 (mission 005): backslash + r in loaded Markdown stays — it is text (C:\root), not a carriage return; typed in the source
  892. // view with real keys, loaded back into the visual editor, written as Markdown and loaded once more. A REAL carriage return (a Windows
  893. // clipboard's CR LF) goes.
  894. {
  895. const S2 = 'md-editor:nth-of-type(2)';
  896. const text2 = () => ev(md2(`querySelector('article').textContent`));
  897. await page.click(S2 + ' footer button'); await sleep(300);
  898. await page.focus(S2 + ' textarea');
  899. await typeR('Path C:\\root\\new and \\r\\n stay'); await sleep(200);
  900. await page.click(S2 + ' footer button'); await sleep(400);
  901. 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()));
  902. const v17 = await val2();
  903. 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));
  904. await page.click(S2 + ' footer button'); await sleep(300);
  905. await page.click(S2 + ' footer button'); await sleep(400);
  906. 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()]));
  907. 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 })); })()`);
  908. await sleep(400);
  909. const v17b = await val2();
  910. 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));
  911. check('#17: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  912. await page.goto(BASE + '/md-editor');
  913. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  914. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  915. }
  916. 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); };
  917. const valR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('input.value').value`);
  918. const artR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('article').innerHTML`);
  919. await page.click('md-editor:nth-of-type(2) article');
  920. await typeR('# Heading'); await sleep(200);
  921. 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)]));
  922. await wipe(1);
  923. await typeR('# Again'); await sleep(200);
  924. check('typing "# " after the editor was emptied (an empty heading is left): "# Again", not "# # Again"', (await valR(1)) === '# Again', JSON.stringify(await valR(1)));
  925. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  926. await typeR('- one'); await enterR(); await typeR('- two'); await sleep(200);
  927. 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)]));
  928. await enterR(); await typeR('1. three'); await sleep(200);
  929. 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)));
  930. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  931. await typeR('1. a'); await enterR(); await typeR('2. b'); await sleep(200);
  932. 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)));
  933. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  934. await typeR('# One'); await enterR(); await typeR('text'); await enterR(); await typeR('## Two'); await sleep(200);
  935. 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)]));
  936. check('no console errors while typing shortcuts', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  937. // ==== mission 004 (creator notes#5): GITHUB PIPE TABLES in the Markdown editor — the behaviour of notes' md-editor.js (9acc27f),
  938. // pure Hybriel. The demo's third editor ("plan") starts with a table; the second is typed into with real keys, one at a time.
  939. await page.goto(BASE + '/md-editor');
  940. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  941. 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' });
  942. // 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
  943. const evq = (e) => ev(e).catch(() => null);
  944. 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.';
  945. const tShape = (i) => ev(`(() => { const t = document.querySelectorAll('md-editor')[${i}].querySelector('article table'); if (!t) return null;
  946. return { rows: [...t.querySelectorAll('tr')].map(tr => [...tr.children].map(c => c.tagName.toLowerCase() + ':' + c.innerHTML.replaceAll('\\u200b', ''))),
  947. align: [...t.querySelector('tr').children].map(c => (c.getAttribute('data-align') || '') + '/' + getComputedStyle(c).textAlign),
  948. before: t.previousElementSibling && t.previousElementSibling.outerHTML, after: t.nextElementSibling && t.nextElementSibling.outerHTML } })()`);
  949. const s0 = await tShape(2).catch(() => null);
  950. 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',
  951. 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']])
  952. && 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));
  953. check('tables: an untouched table is the same Markdown byte for byte', (await valR(2)) === PLAN, JSON.stringify(await valR(2)));
  954. await evq(`(() => { const a = document.querySelectorAll('md-editor')[2].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a.querySelector('table').nextElementSibling); s.collapseToEnd(); })()`);
  955. await typeR(' More.'); await sleep(200);
  956. 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)));
  957. // one cell edited: only that row changes in the Markdown (written in the canonical padded form, the other cells the same)
  958. 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(); })()`);
  959. await typeR('!'); await sleep(200);
  960. const v3 = await valR(2);
  961. const mdCells = (l) => l.split(/(?<!\\)\|/).slice(1, -1).map(c => c.trim());
  962. const tl3 = v3.split('\n').filter(l => l.startsWith('|'));
  963. check('tables: editing one cell changes only that cell (the table is written in the canonical form, every other cell the same)',
  964. 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']])
  965. && new Set(tl3.map(l => l.length)).size === 1, JSON.stringify(v3));
  966. // typing a table with real keys in the (emptied) second editor
  967. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  968. const tab = (shift) => keyR('Tab', 'Tab', 9, undefined, shift ? 8 : 0);
  969. 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) })()`);
  970. await typeR('Before the table'); await enterR();
  971. await typeR('| Item | Qty | Note \\| x |'); await enterR();
  972. await typeR('|:---|:---:|---:|'); await enterR(); await sleep(200);
  973. const s1 = await tShape(1);
  974. 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',
  975. 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()]));
  976. await typeR('**milk**'); await tab(); await typeR('`2`'); await tab(); await typeR('a|b'); await enterR();
  977. 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());
  978. await typeR('bread'); await tab(); await typeR('1'); await tab(); await typeR('wholegrain-sourdough-with-seeds-and-a-very-long-name'); await enterR();
  979. await enterR(); await sleep(150);
  980. 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)]));
  981. await typeR('after the table'); await enterR(); await typeR('a | b stays text'); await sleep(300);
  982. const s2 = await tShape(1);
  983. check('tables: the typed cells — **bold**, `code`, a typed pipe, a long word; the alignment of the delimiter row',
  984. 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']])
  985. && s2.align.join(' ') === 'left/left center/center right/right', JSON.stringify(s2));
  986. 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>'
  987. && (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)]));
  988. const W = [8, 3, 52], prow = (cells) => '| ' + cells.map((c, k) => c.padEnd(W[k])).join(' | ') + ' |';
  989. const TYPED = ['Before the table', '', prow(['Item', 'Qty', 'Note \\| x']), '| :' + '-'.repeat(7) + ' | :-: | ' + '-'.repeat(51) + ': |', prow(['**milk**', '`2`', 'a\\|b']),
  990. prow(['bread', '1', 'wholegrain-sourdough-with-seeds-and-a-very-long-name']), '', 'after the table', '', 'a | b stays text'].join('\n');
  991. 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)));
  992. // Shift+Tab back; Tab in the last cell adds a row
  993. 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(); })()`);
  994. await tab(true);
  995. check('tables: Shift+Tab moves to the cell before (here: the last header cell)', (await caretCell()) === 'TH2', await caretCell());
  996. 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(); })()`);
  997. await tab(); await typeR('x'); await sleep(150);
  998. 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)));
  999. // Backspace / Delete never merge a table with the text around it
  1000. 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); })()`);
  1001. const before1 = await valR(1);
  1002. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1003. 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()]));
  1004. 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); })()`);
  1005. await keyR('Delete', 'Delete', 46); await sleep(150);
  1006. 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)));
  1007. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = a.querySelector('th'); const s = getSelection(); s.collapse(c.firstChild, 0); })()`);
  1008. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1009. 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)));
  1010. // a selection from the paragraph before into the table: the text is cut, the selected cells emptied, the table stays
  1011. 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); })()`);
  1012. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  1013. const s3 = await tShape(1);
  1014. check('tables: Backspace on a selection from the text into a table cuts the text, empties the selected cells, keeps the table (nothing merged)',
  1015. 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));
  1016. // the Markdown source switch and back: the same table
  1017. const v4 = await valR(1);
  1018. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  1019. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  1020. 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]));
  1021. // a pasted HTML table (a spreadsheet, a web page) becomes a table: its cells' text, align / text-align, the widest row
  1022. await evq(`(() => { const a = document.querySelectorAll('md-editor')[0].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.collapseToEnd();
  1023. 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');
  1024. a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  1025. await sleep(400);
  1026. 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',
  1027. (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)));
  1028. // pasted Markdown with a table in it (plain text) becomes a table too
  1029. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  1030. 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 })); })()`);
  1031. await sleep(300);
  1032. 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)]));
  1033. 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());
  1034. // the look at 1280 and on a phone: thin grey lines, no colour; a wide table scrolls inside its box, the page does not
  1035. await page.goto(BASE + '/md-editor');
  1036. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1037. await page.waitFor(`document.querySelectorAll('md-editor')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  1038. const look = await evq(`(() => { const c = getComputedStyle(document.querySelectorAll('md-editor')[2].querySelector('article td')); return c.borderTopWidth + ' ' + c.borderTopStyle + ' ' + c.borderTopColor })()`);
  1039. check('tables: thin grey cell lines (1px solid #999 in the base look)', look === '1px solid rgb(153, 153, 153)', look);
  1040. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1041. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  1042. await shot('md-editor-table-1280');
  1043. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  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')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  1047. 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 } })()`)) || {};
  1048. 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));
  1049. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  1050. await shot('md-editor-table-390');
  1051. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1052. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1053. await page.goto(BASE + '/md-editor'); await sleep(800);
  1054. check('the Markdown editor fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1055. await shot('md-editor-narrow');
  1056. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1057. // ==== 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
  1058. {
  1059. for (const w of [390, 1280]) {
  1060. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: 900, deviceScaleFactor: 1, mobile: w === 390 });
  1061. await page.goto(BASE + '/md-editor');
  1062. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1063. await mdKeys(page, { base: BASE, check, sleep, label: String(w) });
  1064. }
  1065. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1066. }
  1067. // ==== mission 011 END
  1068. // ticket #9: files and images in the Markdown editor (drop, paste, choose) go through emit, with progress, and land in the text
  1069. {
  1070. await page.goto(BASE + '/md-editor');
  1071. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1072. await sleep(600);
  1073. const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
  1074. 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' }));`;
  1075. 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 })); })()`);
  1076. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("doc.pdf")', { timeout: 30000, label: 'files uploaded' });
  1077. const v = await ev(md2(`querySelector('input.value').value`));
  1078. 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));
  1079. 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);
  1080. 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))`));
  1081. 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]')));
  1082. check('progress rows are gone afterwards', (await ev(md2(`querySelector('ul.files').children.length`))) === 0);
  1083. const url = v.match(/\]\((\/md-editor\/files\/[\w.-]+\.pdf)\)/)[1];
  1084. const got = await fetch(BASE + url);
  1085. 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') || ''));
  1086. // a pasted image lands too, at the caret
  1087. 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 })); })()`);
  1088. await page.waitFor(md1(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'pasted image' });
  1089. check('a pasted image is added too', true);
  1090. // an image in typed-in Markdown is drawn; only http(s) and site paths are images
  1091. 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 })); })()`);
  1092. await sleep(300);
  1093. const srcs = await ev(`JSON.stringify([...document.querySelectorAll('md-editor')[1].querySelectorAll('article img')].map(i => i.getAttribute('src')))`);
  1094. check('javascript: and data: images are not made', !srcs.includes('javascript') && !srcs.includes('data:') && srcs.includes('/x.png'), srcs);
  1095. // 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
  1096. {
  1097. const one = mkFiles.replace("dt.items.add(new File([png], 'two.png', { type: 'image/png' }));", '').replace(/dt\.items\.add\(new File\(\[big\][^;]*;/, '');
  1098. const fire = {
  1099. drop: `a.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 0, clientY: 0 }));`,
  1100. paste: `a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));`,
  1101. choose: `const inp = ed.querySelector('input.pick'); inp.files = dt.files; inp.dispatchEvent(new Event('change', { bubbles: true }));`,
  1102. };
  1103. for (const way of ['drop', 'paste', 'choose']) {
  1104. for (const caret of ['in item', 'none']) {
  1105. 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 })); })()`);
  1106. await sleep(300);
  1107. 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', ''));
  1108. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'list ' + way });
  1109. const lv = await ev(md2(`querySelector('input.value').value`));
  1110. 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));
  1111. }
  1112. }
  1113. }
  1114. check('no console errors on files/images', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  1115. await shot('md-editor-files');
  1116. }
  1117. // the code editor: real keys, real typing
  1118. {
  1119. check('home lists the code editor', home.includes('id="open-code-editor"'));
  1120. const cer = await fetch(BASE + '/code-editor/README.md');
  1121. check('Code editor README is served as Markdown', cer.ok && /markdown/.test(cer.headers.get('content-type')) && (await cer.text()).includes('Code editor'));
  1122. check('no .js of its own in components/code-editor', !execSync(`find ${join(APP, 'components/code-editor')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  1123. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  1124. await page.goto(BASE + '/code-editor');
  1125. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1126. const CE = (i, q) => `document.querySelectorAll('code-editor')[${i}].${q}`;
  1127. const cval = (i) => ev(CE(i, `querySelector('input.value').value`));
  1128. const ctext = (i) => ev(CE(i, `querySelector('article').textContent`));
  1129. const cgut = (i) => ev(CE(i, `querySelector('code-gutter').textContent`));
  1130. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  1131. check('Hybriel code is highlighted: comment, keyword, string, function', await ev(`['comment','keyword','string','function'].every(k => ${CE(0, `querySelector('article .tok-' + k)`)} !== null)`));
  1132. check('JavaScript is highlighted too: number, comment, string', await ev(`['comment','string','number','keyword'].every(k => ${CE(1, `querySelector('article .tok-' + k)`)} !== null)`));
  1133. 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`));
  1134. 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)));
  1135. check('the value is the plain text (no markup)', (await cval(0)).startsWith('// a Hybriel component\nString title') && !(await cval(0)).includes('<span'));
  1136. 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 }); };
  1137. const ctype = async (t) => { for (const ch of t) { if (ch === '\n') await ckey('Enter', 'Enter', 13, '\r'); else await ckey(ch, '', undefined, ch); } };
  1138. const CTRL = 2, SHIFT = 8;
  1139. const tab = (shift) => ckey('Tab', 'Tab', 9, undefined, shift ? SHIFT : 0);
  1140. const undo = () => ckey('z', 'KeyZ', 90, undefined, CTRL);
  1141. const redo = () => ckey('z', 'KeyZ', 90, undefined, CTRL | SHIFT);
  1142. // put the caret at text offsets (start..end) of editor i and focus it
  1143. 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)})()`);
  1144. await caret(0, (await cval(0)).length);
  1145. await ctype('\nlet n = 5');
  1146. 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)));
  1147. 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')})()`));
  1148. check('the demo shows that text below the editor', (await ev(`document.getElementById('code-value-hybriel').textContent`)) === (await cval(0)));
  1149. check('the other editor was not touched', (await cval(1)).startsWith('function add(a, b) {'));
  1150. // Tab / Shift+Tab on one line
  1151. await ctype('\n'); await tab(false); await ctype('x');
  1152. check('Tab inserts a tab character', (await cval(0)).endsWith('let n = 5\n\tx'), JSON.stringify((await cval(0)).slice(-14)));
  1153. await tab(true);
  1154. check('Shift+Tab removes it again', (await cval(0)).endsWith('let n = 5\nx'), JSON.stringify((await cval(0)).slice(-14)));
  1155. // Enter keeps the indent; { closes itself; Enter between the braces opens an indented line
  1156. await ctype('\n'); await tab(false); await ctype('if (a) {');
  1157. check('typing { adds the closing }', (await cval(0)).endsWith('\tif (a) {}'), JSON.stringify((await cval(0)).slice(-14)));
  1158. await ctype('\n');
  1159. 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)));
  1160. await ctype('y'); await ctype('\n');
  1161. 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)));
  1162. // typing the closer steps over it; a quote closes itself
  1163. await ckey('Backspace', 'Backspace', 8); await ckey('Backspace', 'Backspace', 8); await ctype('call("a"');
  1164. 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)));
  1165. // undo / redo: back through typing, then forward again
  1166. const before = await cval(0);
  1167. await undo(); await sleep(50);
  1168. const u1 = await cval(0);
  1169. check('Ctrl+Z undoes the last change', u1 !== before && u1.length < before.length + 4, JSON.stringify(u1.slice(-20)));
  1170. await undo(); await undo(); await sleep(50);
  1171. const u3 = await cval(0);
  1172. check('Ctrl+Z again goes further back', u3.length < u1.length, JSON.stringify(u3.slice(-20)));
  1173. await redo(); await redo(); await redo(); await sleep(50);
  1174. check('Ctrl+Shift+Z redoes them: the text is back', (await cval(0)) === before, JSON.stringify((await cval(0)).slice(-20)));
  1175. await ckey('y', 'KeyY', 89, undefined, CTRL);
  1176. 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'); })());
  1177. check('the line numbers follow undo', (await cgut(0)) === '1\n2\n3\n4\n5\n6\n7\n8\n9\n10', JSON.stringify(await cgut(0)));
  1178. // several lines selected: Tab indents all, Shift+Tab outdents all
  1179. const v0 = await cval(0);
  1180. await caret(0, 0, v0.length);
  1181. await tab(false);
  1182. 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)));
  1183. await tab(true);
  1184. check('Shift+Tab outdents them all again', (await cval(0)) === v0, JSON.stringify((await cval(0)).slice(0, 60)));
  1185. // the second editor indents with two spaces
  1186. const w0 = await cval(1);
  1187. await caret(1, 0); await tab(false);
  1188. check('spaces = 2: Tab inserts two spaces', (await cval(1)) === ' ' + w0, JSON.stringify((await cval(1)).slice(0, 30)));
  1189. await tab(true);
  1190. check('spaces = 2: Shift+Tab removes them', (await cval(1)) === w0);
  1191. // text inserted as a whole (paste): several lines, highlighted, numbered
  1192. await caret(1, (await cval(1)).length);
  1193. 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}))})()`);
  1194. await sleep(150);
  1195. 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)));
  1196. // the form posts both by name
  1197. await page.click('#code-form button[type=submit]'); await sleep(800);
  1198. const curl = new URL(await ev('location.href'));
  1199. 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));
  1200. // the code is only ever text: broken / hostile code shows literally, the page structure stays, nothing runs
  1201. await page.goto(BASE + '/code-editor');
  1202. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1203. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  1204. 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`);
  1205. const shape0 = await shape();
  1206. await caret(1, (await cval(1)).length);
  1207. await ctype('\nif (x) {');
  1208. await sleep(300);
  1209. check('unbalanced code renders inside the field as typed', (await cval(1)).includes('if (x) {}') && (await shape()) === shape0, await shape() + ' vs ' + shape0);
  1210. await ctype('\n'); await ctype('}');
  1211. 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)));
  1212. await ev(`window.__pwned = undefined`);
  1213. await ctype('\n</div><b>x');
  1214. await ctype('\n<img src=x onerror=window.__pwned=1>');
  1215. await sleep(500);
  1216. 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);
  1217. 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>'));
  1218. check('typed code did not run (window.__pwned stays undefined)', (await ev(`typeof window.__pwned`)) === 'undefined');
  1219. await page.goto(BASE + '/code-editor'); await sleep(800);
  1220. await page.goto(BASE + '/code-editor'); await sleep(800);
  1221. await shot('code-editor');
  1222. 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());
  1223. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1224. await page.goto(BASE + '/code-editor'); await sleep(800);
  1225. check('the code editor page fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1226. await shot('code-editor-narrow');
  1227. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1228. }
  1229. // 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
  1230. {
  1231. check('home lists the modal', home.includes('id="open-modal"'));
  1232. const mor = await fetch(BASE + '/modal/README.md');
  1233. check('modal README is served as Markdown', mor.ok && /markdown/.test(mor.headers.get('content-type')) && (await mor.text()).includes('# Modal'));
  1234. check('no .js of its own in components/modal', !execSync(`find ${join(APP, 'components/modal')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  1235. const modalRun = async (w, h, mobile, tag) => {
  1236. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile });
  1237. await page.goto(BASE + '/modal');
  1238. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1239. await sleep(500);
  1240. const at = async (x, y) => {
  1241. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
  1242. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
  1243. await sleep(60);
  1244. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
  1245. await sleep(300);
  1246. };
  1247. 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); };
  1248. 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); };
  1249. const openIds = () => ev(`[...document.querySelectorAll('dialog[open]')].map(d => d.id).join()`);
  1250. const last = () => ev(`document.getElementById('modal-last').textContent`);
  1251. const active = () => ev(`document.activeElement.id || document.activeElement.className || document.activeElement.tagName`);
  1252. const inside = (id) => ev(`document.getElementById(${JSON.stringify(id)}).contains(document.activeElement)`);
  1253. // a corner of the dim background, outside every window
  1254. const bg = async () => at(4, h - 4);
  1255. check(`modal ${tag}: closed at first (no dialog open)`, (await openIds()) === '' && (await ev(`getComputedStyle(document.getElementById('info')).display`)) === 'none');
  1256. // open by the page's button: title, content, focus inside, page inert behind
  1257. await on('#open-info');
  1258. 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`)));
  1259. check(`modal ${tag}: the focus is inside when it opens`, await inside('info'), await active());
  1260. const box = await ev(`JSON.stringify(document.getElementById('info').getBoundingClientRect())`);
  1261. const b = JSON.parse(box);
  1262. check(`modal ${tag}: the window is inside the screen`, b.left >= 0 && b.top >= 0 && b.right <= w && b.bottom <= h, box);
  1263. 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')`));
  1264. await shot(`modal-open-${w}`);
  1265. // Esc
  1266. await mkey('Escape', 'Escape', 27);
  1267. 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()}`);
  1268. // ×
  1269. await on('#open-info'); await on('#info .modal-x');
  1270. 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()}`);
  1271. // the dim background
  1272. await on('#open-info'); await bg();
  1273. 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()}`);
  1274. // a press inside the window that ends on the background (a text selection dragged out) does not close it
  1275. await on('#open-info');
  1276. const p = await ev(`(() => { const r = document.querySelector('#info modal-body p').getBoundingClientRect(); return { x: r.x + 5, y: r.y + 5 }; })()`);
  1277. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: p.x, y: p.y, button: 'none' });
  1278. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: p.x, y: p.y, button: 'left', clickCount: 1 });
  1279. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 4, y: h - 4, button: 'left' });
  1280. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 4, y: h - 4, button: 'left', clickCount: 1 });
  1281. await sleep(300);
  1282. check(`modal ${tag}: a press started inside and let go on the background keeps it open`, (await openIds()) === 'info');
  1283. await mkey('Escape', 'Escape', 27);
  1284. // footer buttons: the value is the reason
  1285. await on('#open-confirm');
  1286. check(`modal ${tag}: footer buttons are shown`, (await ev(`[...document.querySelectorAll('#confirm footer button')].map(b => b.textContent).join()`)) === 'Cancel,Delete');
  1287. check(`modal ${tag}: footer buttons have no border (creator's rule)`, await ev(`[...document.querySelectorAll('#confirm button')].every(b => getComputedStyle(b).borderTopWidth === '0px')`));
  1288. await on('#confirm footer button[value=ok]');
  1289. 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()}`);
  1290. await on('#open-confirm'); await on('#confirm footer button[value=cancel]');
  1291. check(`modal ${tag}: Cancel closes it with "cancel"`, (await last()) === 'confirm: cancel');
  1292. // backdrop close switched off; focus goes round inside with Tab / Shift+Tab
  1293. await on('#open-form'); await bg();
  1294. check(`modal ${tag}: backdropClose = "false": a click on the background leaves it open`, (await openIds()) === 'form' && (await last()) === 'confirm: cancel' && await inside('form'));
  1295. const seen = [];
  1296. for (let i = 0; i < 9; i++) { await mkey('Tab', 'Tab', 9); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  1297. check(`modal ${tag}: Tab ×9 never leaves the window`, seen.every(s => s === 'in'), seen.join());
  1298. await ev(`document.getElementById('modal-save').focus()`); await mkey('Tab', 'Tab', 9);
  1299. check(`modal ${tag}: Tab on the last control goes round to the first (×)`, (await active()) === 'modal-x', await active());
  1300. await mkey('Tab', 'Tab', 9, 8);
  1301. check(`modal ${tag}: Shift+Tab on the first goes round to the last (Save)`, (await active()) === 'modal-save', await active());
  1302. for (let i = 0; i < 6; i++) { await mkey('Tab', 'Tab', 9, 8); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  1303. check(`modal ${tag}: Shift+Tab never leaves the window`, seen.every(s => s === 'in'), seen.join());
  1304. await ev(`document.getElementById('modal-name').focus()`);
  1305. await page.send('Input.insertText', { text: 'Ada' }); await sleep(150);
  1306. await shot(`modal-form-${w}`);
  1307. // the page closes it itself, with its own reason
  1308. await on('#modal-save');
  1309. 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()}`);
  1310. // no scroll behind: a long page scrolled down stays where it is; the long window scrolls itself
  1311. await ev(`(() => { const d = document.createElement('div'); d.id = 'gate-tall'; d.style.height = '3000px'; document.querySelector('main').appendChild(d); scrollTo(0, 200); })()`);
  1312. await sleep(100);
  1313. await ev(`document.getElementById('open-long').click()`); await sleep(300);
  1314. const y0 = await ev('scrollY');
  1315. check(`modal ${tag}: while open the page cannot scroll (html overflow hidden)`, (await ev(`getComputedStyle(document.documentElement).overflow`)) === 'hidden');
  1316. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 4, y: h - 4, deltaX: 0, deltaY: 600 }); await sleep(400);
  1317. 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 }; })()`);
  1318. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: mb.x, y: mb.y, deltaX: 0, deltaY: 600 }); await sleep(400);
  1319. check(`modal ${tag}: the wheel does not scroll the page behind`, (await ev('scrollY')) === y0, `${y0} → ${await ev('scrollY')}`);
  1320. 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`)));
  1321. await shot(`modal-long-${w}`);
  1322. await mkey('Escape', 'Escape', 27);
  1323. check(`modal ${tag}: after closing the page scrolls again`, (await ev(`getComputedStyle(document.documentElement).overflow`)) !== 'hidden' && (await last()) === 'long: escape');
  1324. await ev(`document.getElementById('gate-tall').remove(); scrollTo(0, 0)`); await sleep(100);
  1325. check(`modal ${tag}: no horizontal overflow`, await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1326. await shot(`modal-closed-${w}`);
  1327. 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());
  1328. };
  1329. await modalRun(1280, 900, false, '1280 px');
  1330. await modalRun(390, 800, true, '390 px');
  1331. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1332. }
  1333. await shot('wide');
  1334. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  1335. await sleep(300);
  1336. check('no horizontal overflow at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  1337. await shot('narrow');
  1338. // ==== ticket #15: THE BASE LOOK — black, white and the greys of shared/base.hl, no WorldAPI colours, no decorative frames.
  1339. // (1) every colour written in a component's public file is a base value (or black with alpha for a shadow);
  1340. // (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
  1341. // EVERY element's computed colour, background, visible border, outline, caret, accent colour (and the modal's ::backdrop) is a grey
  1342. // (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.
  1343. const baseSrc = readFileSync(join(APP, 'shared/base.hl'), 'utf8');
  1344. const baseValues = [...baseSrc.matchAll(/^static \w+ = var\('(#[0-9a-f]+)'\)/gm)].map(m => m[1]);
  1345. check('base look: shared/base.hl names black, white and four greys', baseValues.join(' ') === '#000 #555 #999 #ddd #f2f2f2 #fff', baseValues.join(' '));
  1346. const publicFiles = ['month-view/month-view.hl', 'month-view/clock.hl', 'date-picker/date-picker.hl', 'range-picker/range-picker.hl', 'pagination/pagination.hl',
  1347. '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'];
  1348. const foreign = [];
  1349. for (const pf of publicFiles) {
  1350. readFileSync(join(APP, 'components', pf), 'utf8').split('\n').forEach((line, i) => {
  1351. if (/^\s*\/\//.test(line)) return;
  1352. for (const m of line.matchAll(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)/g))
  1353. if (!baseValues.includes(m[0]) && !/^rgba\(0, 0, 0, \.\d+\)$/.test(m[0])) foreign.push(`${pf}:${i + 1} ${m[0]}`);
  1354. });
  1355. }
  1356. check('base look: every colour in the 11 public component files is a base value (no WorldAPI palette fallback)', foreign.length === 0, foreign.join(', '));
  1357. const bwProbe = `(() => {
  1358. 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]); };
  1359. const bad = [], frames = [];
  1360. const name = el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string' ? '.' + el.className.trim().replace(/\\s+/g, '.') : '');
  1361. const comp = 'month-view, date-picker, range-picker, pagination, md-editor, code-editor, file-upload, files-upload, modal-dialog, comments-block';
  1362. for (const el of document.querySelectorAll('*')) {
  1363. const cs = getComputedStyle(el);
  1364. const props = ['color', 'backgroundColor', 'caretColor', 'accentColor', 'textDecorationColor'];
  1365. 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');
  1366. if (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) props.push('outlineColor');
  1367. for (const p of props) if (cs[p] !== 'auto' && !grey(cs[p])) bad.push(name(el) + ' ' + p + ' ' + cs[p]);
  1368. if (/^(rgba?|.* rgba?)\\(/.test(cs.boxShadow) && !(cs.boxShadow.match(/rgba?\\([^)]*\\)/g) || []).every(grey)) bad.push(name(el) + ' boxShadow ' + cs.boxShadow);
  1369. if (el.tagName === 'DIALOG') { const b = getComputedStyle(el, '::backdrop').backgroundColor; if (!grey(b)) bad.push('dialog::backdrop ' + b); }
  1370. // a table's cell lines are functional (mission 004), like the drop zone's
  1371. if (el.closest(comp) && !el.closest('drop-zone') && !el.matches('md-editor article th, md-editor article td'))
  1372. for (const side of ['Top', 'Right', 'Bottom', 'Left'])
  1373. 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; }
  1374. }
  1375. const root = getComputedStyle(document.documentElement);
  1376. const tokens = ['--color-text', '--color-background', '--color-accent', '--color-surface', '--color-border', '--orange'].filter(t => root.getPropertyValue(t).trim() !== '');
  1377. const body = getComputedStyle(document.body);
  1378. 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)' };
  1379. })()`;
  1380. const bwPages = ['/', '/month-view', '/date-picker', '/range-picker', '/pagination', '/md-editor', '/code-editor', '/file-upload', '/files-upload', '/files-upload/pick', '/modal', '/comments'];
  1381. for (const w of [1280, 390]) {
  1382. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 600 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 600 });
  1383. const results = [];
  1384. for (const p of bwPages) {
  1385. await page.goto(BASE + p);
  1386. // 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
  1387. 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; }
  1388. await sleep(300);
  1389. const r = await ev(bwProbe);
  1390. results.push([p, r]);
  1391. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  1392. writeFileSync(join(SCRATCH, `gate-bw-${p === '/' ? 'home' : p.slice(1).replace(/\//g, '-')}-${w}.png`), Buffer.from(data, 'base64'));
  1393. }
  1394. // the floating parts: the date picker's popup open, the modal open (its window and the dimmed page)
  1395. await page.goto(BASE + '/date-picker');
  1396. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1397. await page.click('date-picker input');
  1398. await page.waitFor(`getComputedStyle(document.querySelector('date-picker picker-popup')).display !== 'none'`, { label: 'bw popup open' });
  1399. results.push(['/date-picker (popup open)', await ev(bwProbe)]);
  1400. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-date-picker-open-${w}.png`), Buffer.from(data, 'base64')); }
  1401. await page.goto(BASE + '/modal');
  1402. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  1403. await page.click('.modal-openers button');
  1404. await page.waitFor(`!!document.querySelector('modal-dialog > dialog[open]')`, { label: 'bw modal open' });
  1405. await sleep(200);
  1406. results.push(['/modal (open)', await ev(bwProbe)]);
  1407. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-modal-open-${w}.png`), Buffer.from(data, 'base64')); }
  1408. 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])));
  1409. 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(' '));
  1410. 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])));
  1411. 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])));
  1412. }
  1413. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  1414. // ==== mission 046: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons /
  1415. // offline = [ Index ]), as tracker.worldapi.org#10. The manifest and every icon over HTTP; Chrome's own verdict
  1416. // (installability, manifest parse); the worker registered for the whole app; then OFFLINE: the tab loses the
  1417. // network (the note appears), the server is stopped too (CDP's offline emulation does not reach the service worker's
  1418. // own fetches, so only a dead server proves the cache), and `/` still opens: header + the note + the home list. A
  1419. // demo page gets hl:web's "Unavailable offline" page. A separate 390 px tab, so its expected socket errors stay out
  1420. // of the main tab's console checks. Phone screenshots: .scratch/gate-pwa-phone-{online,offline}.png.
  1421. const html = await (await fetch(BASE + '/')).text();
  1422. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1423. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (base black, #15)',
  1424. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1425. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="#000">'), html.slice(0, 900));
  1426. const mres = await fetch(BASE + mhref);
  1427. const man = await mres.json();
  1428. 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)',
  1429. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'Hybriel components' && man.short_name === 'Components' && man.start_url === '/' && man.scope === '/'
  1430. && man.display === 'standalone' && man.theme_color === '#000' && man.background_color === '#fff', JSON.stringify(man));
  1431. const iconOk = [];
  1432. for (const ic of man.icons || []) {
  1433. const ir = await fetch(BASE + ic.src);
  1434. const b = Buffer.from(await ir.arrayBuffer());
  1435. 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]));
  1436. }
  1437. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1438. 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));
  1439. const touch = await fetch(BASE + '/icons/apple-touch-icon.png');
  1440. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1441. const fav = await fetch(BASE + '/icons/favicon.svg');
  1442. const favText = await fav.text();
  1443. const ico = await fetch(BASE + '/favicon.ico');
  1444. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1445. 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',
  1446. 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')
  1447. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1448. await page.goto('about:blank'); // the server goes down below: the main tab must not sit on a page meanwhile
  1449. const app = await browser.newPage();
  1450. const aev = (e) => app.evaluate(e);
  1451. const ashot = async (name) => { const { data } = await app.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  1452. const appHydrated = () => app.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'app tab hydrated' });
  1453. await app.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1454. await app.goto(BASE + '/');
  1455. await appHydrated();
  1456. await app.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: 'service worker active' });
  1457. await app.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: 'page controlled by the worker' });
  1458. const inst = await app.send('Page.getInstallabilityErrors');
  1459. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  1460. const am = await app.send('Page.getAppManifest');
  1461. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, JSON.stringify(am.errors));
  1462. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1463. (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')));
  1464. check('pwa: online, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1465. check('pwa: no horizontal overflow at 390 px', await aev('document.documentElement.scrollWidth <= window.innerWidth'));
  1466. await ashot('pwa-phone-online');
  1467. await app.setOffline(true);
  1468. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1469. 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.');
  1470. await stopServer();
  1471. let down = false;
  1472. try { await fetch(BASE + '/'); } catch { down = true; }
  1473. await app.goto(BASE + '/');
  1474. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1475. 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',
  1476. down && (await aev(`document.querySelector('application-header .brand') ? document.querySelector('application-header .brand').textContent : ''`)) === 'Hybriel components'
  1477. && (await aev(`!!document.querySelector('#offline')`)) && (await aev(`document.querySelectorAll('#components li').length`)) === 10
  1478. && (await aev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(0, 0, 0)', 'server down: ' + down);
  1479. await ashot('pwa-phone-offline');
  1480. await app.goto(BASE + '/month-view');
  1481. 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');
  1482. await app.setOffline(false);
  1483. await startServer();
  1484. await app.goto(BASE + '/');
  1485. await appHydrated();
  1486. await app.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1487. check('back online: / from the server again, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1488. await app.close();
  1489. }
  1490. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  1491. await stop();
  1492. console.log(`${passes} passed, ${failures} failed`);
  1493. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 77a93c16mission 011: gate hook for md-keys (480/0), flatten() runs one at a time (removeChild race), surface also built on first focus / pointer-down (background tab), md-bg test, README keysmre
  • 3c906718mission 011: md-editor key tests (real keys) and fixes: nested p/ul flatten, bare br, link change, Ctrl+E, code block exit (WIP)mre
  • 1442e583mission 010: report, LOG, STATUSmre
  • 6f27ad31md-editor: phone toolbar row contained (inline-size) so it never widens a grid parentmre
  • d702d76dmd-editor look: root class md-empty (a host .empty rule hit it), rows = surface height, one phone toolbar row with 44 px targets; comment form rows 3; gate 360/0mre
  • 15be2ac0comments: attach (FilesUpload pick), onPost(text, files), files per comment; md-editor files=off; README, gate fixmre
  • 1f8d79d6comments (mission 009 WIP, tickets#27): attachments — attach="true" puts the form in FilesUpload pick mode, onPost(text, files), files per comment (thumbnails open full size, file rows, no url = no link); MdEditor files="off"; demo with attachments; gate m009 checks (WIP: 356/1)mre
  • 13389d67mission 008: report, LOG, STATUSmre
  • ab47e4a2files-upload (mission 008, #18 for hycon#46): pick-first-send-later mode — host-owned list (files + onChange), slot for the host's input area, Ctrl+V paste (both modes), thumbnails, name+size rows, ✕ remove, maxSize per file, Camera on touch screens, 44 px targets; demo /files-upload/pick; gate 343/0 (19 new, 18 fail on the old code)mre
  • 172e66bemission brief 008mre
  • 9db927dfpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 00a95329components (mission 007): re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ git-ignored), gate 324/0 old and new, real-data copy unchanged, report 007, same-output.mjs ports overridablemre
  • fe50766bmission brief 007mre
  • 2dce51b8components (mission 006) 4/4: docs (README comments + gate 324, STATUS, LOG), report reports/006-comments.mdmre
  • 9ec7273ecomponents layouts#2 (mission 006) 3/4: comments — each text is MdEditor readonly directly in its row (hl:web builds a composed child anew when a bound value changes, so the keyed one-row list was not needed); demo 'bob edits his comment elsewhere (a push)' + gate check that a text the host changes from outside is drawn anew; theme radii (var(--radius-small/large) with 5px/10px fallbacks: layouts' check-theme 0 problems with comments.hl copied in); README 'How it is built'; gate 324/0 (34 comments checks)mre
  • fd57c18bcomponents layouts#2 (mission 006) 2/3: comments block (components/comments, demo /comments) — pure Hybriel: '1 comment' / 'n comments', avatar initial, bubble with name, time, 'edited' (<details> with the earlier versions), the text drawn by MdEditor readonly (one-row list keyed by id + text, so an edit redraws), like ♥ n (aria-pressed), Edit / Delete (asks first) only where author == user, the form below in MdEditor (Comment button or Ctrl+Enter; a fresh editor after a post). Host passes comments + user and hands onPost / onEdit / onDelete / onLike (hybriel#87); demo keeps a mock thread from lib/comments.hl in the page, switches alice / bob / nobody. Home entry, routes, map line, README; base-look gate covers comments; 33 gate checks with real clicks / keysmre
  • 850a376bcomponents (mission 006) 1/3: MdEditor readonly = "true" — the Markdown shown formatted and nothing else (no toolbar, link form, file rows, placeholder, source view or switch; article contenteditable false, tabindex -1, role document; no field background or focus ring); the mount only loads the value. For the comments block, which draws every comment with the editor's own renderermre
  • ee9f1b57mission brief w6mre
  • fe691586components (mission 005) 4/4: docs (README components + gate 290, STATUS, LOG), report reports/005-fixes-16-17-5.mdmre
  • f1ebab53components #5 (mission 005) 3/4: file upload for several files (components/files-upload, demo /files-upload) — pure Hybriel, each file through emit server uploadFile (hybriel#94), drop or choose many, a row per file with live progress, one after the other in order, a drop during an upload waits, a file over uploadMax fails in its row and the next goes, 'n of m uploaded'; home entry, routes, map line, README; pagination keyboard focus ring #555 (Chrome painted its own orange one); docker-compose init: true (hybriel#156); gate 290/0 (17 #5 checks with real file drops, 1 #16 focus check)mre