gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf1ebab53f1ebab53components #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)mref1ebab53/tests/browser.mjs

112.0 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 { launchBrowser } from './cdp.mjs';
  9. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  10. const HERE = dirname(fileURLToPath(import.meta.url));
  11. const APP = resolve(HERE, '..');
  12. const PORT = Number(process.env.COMPONENTS_GATE_PORT || 8700);
  13. const [CH_FROM, CH_TO] = (process.env.COMPONENTS_GATE_CHROME || '8701-8709').split('-').map(Number);
  14. const BASE = `http://127.0.0.1:${PORT}`;
  15. const SCRATCH = join(APP, '.scratch');
  16. const SESSIONS = join(SCRATCH, 'gate-sessions');
  17. // a re-vendored Hybriel compiles the app at its first start (cold 18–41 s, hybriel#148; then ~1 s from its build cache):
  18. // every server start waits up to COLD_MS (COMPONENTS_COLD_MS, default 120 s)
  19. const COLD_MS = Number(process.env.COMPONENTS_COLD_MS || 120000);
  20. rmSync(SESSIONS, { recursive: true, force: true });
  21. mkdirSync(SESSIONS, { recursive: true });
  22. let failures = 0, passes = 0;
  23. function check(label, ok, detail = '') {
  24. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  25. if (ok) passes++; else failures++;
  26. }
  27. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  28. let log = '', server = null, browser = null;
  29. async function stop() {
  30. if (browser) { try { await browser.close(); } catch {} browser = null; }
  31. await stopServer();
  32. }
  33. // the server alone goes down and up again in the offline checks (mission 046)
  34. async function stopServer() {
  35. if (server) {
  36. try { server.kill('SIGTERM'); } catch {}
  37. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  38. server = null;
  39. }
  40. }
  41. async function startServer() {
  42. 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'] });
  43. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  44. for (const t0 = Date.now(); ; ) {
  45. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  46. if (Date.now() - t0 > COLD_MS) throw new Error('server did not come up\n' + log);
  47. await sleep(250);
  48. }
  49. }
  50. async function main() {
  51. await startServer();
  52. // the home lists the component; its README is served
  53. const home = await (await fetch(BASE + '/')).text();
  54. 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')));
  55. check('home lists the month view', home.includes('id="open-month-view"'));
  56. check('home shows only the list, no component embedded (creator 2026-09-25)', !home.includes('<month-view'));
  57. const readme = await fetch(BASE + '/month-view/README.md');
  58. check('README is served as Markdown', readme.ok && /markdown/.test(readme.headers.get('content-type')) && (await readme.text()).includes('Month view'));
  59. // first render on the server: 6 weeks of 7 days, one today
  60. const demo = await (await fetch(BASE + '/month-view')).text();
  61. check('server renders 42 days and one today', (demo.match(/<li class=/g) || []).length === 42 && (demo.match(/class="today"/g) || []).length === 1);
  62. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  63. const page = await browser.newPage();
  64. const SLOW = 3;
  65. const goto = page.goto.bind(page);
  66. page.goto = (u, o = {}) => goto(u, { ...o, timeout: 15000 * SLOW });
  67. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  68. // a zone already on the next day (UTC+14) compared with the server's UTC date: the visitor's today must win (ticket #11)
  69. await page.send('Emulation.setTimezoneOverride', { timezoneId: 'Pacific/Kiritimati' });
  70. await page.goto(BASE + '/month-view');
  71. // the month view's own demo page (the home only lists the components)
  72. await page.waitForSelector('#month-title');
  73. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  74. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  75. const ev = (e) => page.evaluate(e);
  76. const title = () => ev('document.querySelector("#month-title").textContent');
  77. 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()); })()`);
  78. const expectTitle = (y, m) => ev(`new Intl.DateTimeFormat(navigator.language, { month: 'long' }).format(new Date(Date.UTC(${y}, ${m - 1}, 15, 12))) + ' ${y}'`);
  79. const [ty, tm] = localToday.split('-').map(Number);
  80. // the browser's today and language arrive at load, with no pointer needed
  81. await page.waitFor(`!!document.querySelector('li.today time') && document.querySelector('li.today time').getAttribute('datetime') === ${JSON.stringify(localToday)}`, { label: 'browser today marked at load' });
  82. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 300, y: 200 });
  83. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === (${JSON.stringify(await expectTitle(ty, tm))}).toLowerCase()`, { label: 'title in the browser language' });
  84. check('title is the current month and year in the browser language', true);
  85. check('today is marked (browser date)', (await ev(`document.querySelector('li.today time').getAttribute('datetime')`)) === localToday, localToday);
  86. check('42 days, 6 weeks', (await ev('document.querySelectorAll("#month-days li").length')) === 42);
  87. const t0 = await title();
  88. // next / prev
  89. await page.click('#month-next');
  90. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(t0)}`, { label: 'next month' });
  91. const nm = tm === 12 ? 1 : tm + 1, ny = tm === 12 ? ty + 1 : ty;
  92. await page.waitFor(`document.querySelector('#month-title').textContent.toLowerCase() === ${JSON.stringify((await expectTitle(ny, nm)).toLowerCase())}`, { label: 'next month in the browser language' });
  93. check('next shows the next month', true);
  94. await page.click('#month-prev');
  95. await page.waitFor(`document.querySelector("#month-title").textContent === ${JSON.stringify(t0)}`, { label: 'prev month' });
  96. check('prev returns to the month, today marked again', (await ev('document.querySelectorAll("li.today").length')) === 1);
  97. // walk to February 2028 (leap year) and check its days and its first weekday (Tuesday)
  98. let guard = 0;
  99. const feb28 = (await expectTitle(2028, 2)).toLowerCase();
  100. while ((await title()).toLowerCase() !== feb28 && guard++ < 40) {
  101. const before = await title();
  102. await page.click('#month-next');
  103. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging' });
  104. }
  105. 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 }; })()`);
  106. check('Feb 2028: 29 days, the 1st is a Tuesday (column 2)', feb.n === 29 && feb.col === 1, JSON.stringify(feb));
  107. // year rollover: go back to December 2027 and January 2028 by prev
  108. await page.click('#month-prev');
  109. await page.click('#month-prev');
  110. const dec27 = (await expectTitle(2027, 12)).toLowerCase();
  111. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify(dec27)}`, { label: 'back to December' });
  112. 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 }))()`);
  113. check('Dec 2027: 31 days, the 1st is a Wednesday', dec.n === 31 && dec.col === 2, JSON.stringify(dec));
  114. check('no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  115. // the date picker: click the field, pick a day, the value is YYYY-MM-DD; typing works
  116. check('home lists the date picker', home.includes('id="open-date-picker"'));
  117. check('date picker README is served', (await fetch(BASE + '/date-picker/README.md')).ok);
  118. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  119. await page.goto(BASE + '/date-picker');
  120. await page.waitForSelector('date-picker input');
  121. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  122. await sleep(1500);
  123. 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);
  124. const pop = (n) => `getComputedStyle(document.querySelectorAll('date-picker picker-popup')[${n}]).display !== 'none'`;
  125. const val = (n) => ev(`document.querySelectorAll('date-picker input')[${n}].value`);
  126. const realClick = async (sel) => {
  127. 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 }; })()`);
  128. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: r.x, y: r.y, button: 'none' });
  129. await sleep(120);
  130. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  131. await sleep(100);
  132. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: r.x, y: r.y, button: 'left', clickCount: 1 });
  133. await sleep(700);
  134. };
  135. const typeInto = async (n, text) => {
  136. await ev(`document.querySelectorAll('date-picker input')[${n}].focus()`);
  137. await ev(`document.querySelectorAll('date-picker input')[${n}].select()`);
  138. await page.send('Input.insertText', { text });
  139. await sleep(400);
  140. };
  141. check('two fields with their names', (await ev(`[...document.querySelectorAll('date-picker input')].map(i => i.name).join()`)) === 'arrival,departure');
  142. check('the month is closed at first', !(await ev(pop(0))) && !(await ev(pop(1))));
  143. await realClick('date-picker input[name=arrival]');
  144. await page.waitFor(pop(0), { label: 'popup open' });
  145. check('click on the field opens the month under it', (await ev(pop(0))) && !(await ev(pop(1))));
  146. 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 }; })()`);
  147. check('the month sits right under the field', pos.dx < 2 && pos.dy >= 0 && pos.dy < 12, JSON.stringify(pos));
  148. await ev(`document.querySelector('date-picker input[name=arrival]').__mark = 1`);
  149. await realClick('date-picker date-field:nth-child(1) ol.days li:not(.outside) time[datetime$="-15"]');
  150. const picked = await val(0);
  151. check('the field element is the same one after picking (not re-created)', (await ev(`document.querySelector('date-picker input[name=arrival]').__mark`)) === 1);
  152. check('a picked day is in the field as YYYY-MM-DD', /^\d{4}-\d{2}-15$/.test(picked), picked);
  153. check('the month closes after picking', !(await ev(pop(0))));
  154. // the month arrows page
  155. await realClick('date-picker input[name=departure]');
  156. await page.waitFor(pop(1), { label: 'popup open 2' });
  157. const dt0 = await ev(`document.querySelectorAll('date-picker h2')[1].textContent`);
  158. await realClick('date-picker date-field:nth-child(2) button.next');
  159. check('the next-month arrow changes the month', (await ev(`document.querySelectorAll('date-picker h2')[1].textContent`)) !== dt0);
  160. await realClick('date-picker date-field:nth-child(2) ol.days li:not(.outside) time[datetime$="-20"]');
  161. 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));
  162. // typing: a date in another month opens on that month and is marked
  163. await typeInto(0, '2028-02-29');
  164. check('typing works: the field holds the typed date', (await val(0)) === '2028-02-29', await val(0));
  165. 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');
  166. await typeInto(0, '2027-02-30');
  167. check('an impossible date marks the field invalid', (await ev(`document.querySelectorAll('date-picker input')[0].getAttribute('aria-invalid')`)) === 'true');
  168. await typeInto(0, '2028-02-29');
  169. await sleep(300); await shot('picker');
  170. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
  171. await sleep(300);
  172. check('Escape closes the month', !(await ev(pop(0))));
  173. await realClick('h1'); await sleep(200);
  174. // the form posts both fields by name
  175. await ev(`document.querySelector('date-picker-demo form button[type=submit]').click()`);
  176. await page.waitFor(`location.search.includes('arrival=2028-02-29')`, { label: 'form posted' });
  177. 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'));
  178. 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());
  179. // the date range picker: a start click, an end click, both in the field, the days between highlighted
  180. check('home lists the range picker', home.includes('id="open-range-picker"'));
  181. check('range picker README is served', (await fetch(BASE + '/range-picker/README.md')).ok);
  182. await page.goto(BASE + '/range-picker');
  183. await page.waitForSelector('#range-picker-input');
  184. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  185. await sleep(1500);
  186. const rvis = () => ev(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`);
  187. const rval = () => ev(`document.getElementById('range-picker-input').value`);
  188. const day = (n) => ev(`document.querySelector('range-picker ol.days li:not(.outside) time[datetime$="-${n}"]').closest('li').click()`);
  189. check('range: month is closed at first', !(await rvis()));
  190. await page.click('#range-picker-input');
  191. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup open' });
  192. await day('20');
  193. check('range: the first click is the start, the month stays open', /^\d{4}-\d{2}-20 – $/.test(await rval()) && await rvis(), await rval());
  194. await day('10');
  195. const rv = await rval();
  196. check('range: second (earlier) click swaps: start – end in the field', /^\d{4}-\d{2}-10 – \d{4}-\d{2}-20$/.test(rv), rv);
  197. await sleep(500);
  198. check('range: the month closes after the end', !(await rvis()));
  199. await page.click('#range-picker-input');
  200. await page.waitFor(`getComputedStyle(document.querySelector('range-picker picker-popup')).display !== 'none'`, { label: 'popup reopen' });
  201. 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) }))()`);
  202. check('range: start and end marked, the 9 days between highlighted', hl.sel.join() === '10,20' && hl.between.length === 9, JSON.stringify(hl));
  203. await shot('range');
  204. 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 })); })()`);
  205. await page.waitFor(`document.querySelectorAll('range-picker li.between').length === 27`, { label: 'typed range marked' });
  206. check('range: a typed range shows its month, 27 days between', true);
  207. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-30'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  208. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'true'`, { label: 'impossible range marked' });
  209. check('range: an impossible range marks the field invalid', true);
  210. await ev(`(() => { const f = document.getElementById('range-picker-input'); f.value = '2028-02-01 – 2028-02-29'; f.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  211. await page.waitFor(`document.getElementById('range-picker-input').getAttribute('aria-invalid') === 'false'`, { label: 'valid again' });
  212. await ev(`document.querySelector('form button[type=submit]').click()`);
  213. await page.waitFor(`location.search.length > 0`, { label: 'form posted' });
  214. const q = decodeURIComponent(await ev(`location.search`)).replace(/\+/g, ' ');
  215. check('range: the form posts the period by the field name', q.includes('range=2028-02-01 – 2028-02-29'), q);
  216. check('range picker has no .js file', !existsSync(join(APP, 'components/range-picker/range-picker.js')));
  217. 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());
  218. // ticket #4: the one-file upload (pure Hybriel): choose / drop -> name, size, progress -> listed; the app stores it
  219. {
  220. check('home lists the file upload', home.includes('id="open-file-upload"'));
  221. check('file upload README is served', (await fetch(BASE + '/file-upload/README.md')).ok);
  222. check('file upload has no .js file', !existsSync(join(APP, 'components/file-upload/file-upload.js')));
  223. 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());
  224. await page.goto(BASE + '/file-upload');
  225. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  226. await sleep(600);
  227. const FU = (s) => `document.querySelector('file-upload ${s}')`;
  228. const mk = (name, n) => `const dt = new DataTransfer(); dt.items.add(new File([new Uint8Array(${n}).fill(66)], '${name}', { type: 'text/plain' }));`;
  229. 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 })); })()`);
  230. await page.waitFor(`${FU('.state')}.textContent === 'Uploaded'`, { timeout: 30000, label: 'uploaded' });
  231. check('upload: name and size shown', (await ev(FU('.name') + '.textContent')) === 'report.txt' && (await ev(FU('.size') + '.textContent')) === '3.0 MB');
  232. check('upload: progress bar reaches 100%', (await ev(FU('progress') + '.value')) === 100 && (await ev('window.__max')) >= 1);
  233. check('upload: listed under Uploaded', (await ev(FU('ul.uploaded li') + '.textContent')) === 'report.txt — 3.0 MB');
  234. const stored = execSync(`ls -l ${join(APP, 'storage/uploads')} | grep -c ' 3145728 '`).toString().trim();
  235. check('upload: the app stored all bytes', Number(stored) >= 1, stored);
  236. // choosing a second file (input) adds a second row
  237. const { root } = await page.send('DOM.getDocument');
  238. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'file-upload input[type=file]' });
  239. writeFileSync(join(SCRATCH, 'pick.txt'), 'hello');
  240. await page.send('DOM.setFileInputFiles', { files: [join(SCRATCH, 'pick.txt')], nodeId });
  241. await page.waitFor(`document.querySelectorAll('file-upload ul.uploaded li').length === 2`, { timeout: 30000, label: 'chosen file listed' });
  242. 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');
  243. check('upload: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  244. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  245. await sleep(300); await shot('file-upload-narrow');
  246. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  247. await sleep(200); await shot('file-upload');
  248. }
  249. // ticket #5 (mission 005): the upload for several files, pure Hybriel (emit server uploadFile per file, hybriel#94): REAL drops of files
  250. // from disk (Chrome's drag and drop, Input.dispatchDragEvent), the multiple file input, a row per file with live progress, one file at a
  251. // 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
  252. // the waiting is seen. Screenshots .scratch/gate-files-upload-{1280,390}.png.
  253. {
  254. check('home lists the upload for several files', home.includes('id="open-files-upload"'));
  255. check('files upload README is served', (await fetch(BASE + '/files-upload/README.md')).ok);
  256. 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());
  257. const FD = join(SCRATCH, 'gate-files');
  258. mkdirSync(FD, { recursive: true });
  259. 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));
  260. const F = (n) => join(FD, n);
  261. // its own tab: the over-limit file's expected 413 stays out of the main tab's console checks
  262. const page = await browser.newPage();
  263. const ev = (e) => page.evaluate(e);
  264. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  265. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  266. await page.goto(BASE + '/files-upload');
  267. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' }).catch(() => {});
  268. await sleep(600);
  269. 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('|'))`);
  270. const summary = () => ev(`(document.querySelector('files-upload output.summary') || {}).textContent`);
  271. // a REAL drop of files (Chrome's own drag and drop through the Input domain, files from disk)
  272. const dropFiles = async (names) => {
  273. const b = await page.box('files-upload drop-zone');
  274. if (!b) return;
  275. const data = { items: [], files: names.map(F), dragOperationsMask: 1 };
  276. for (const type of ['dragEnter', 'dragOver', 'drop']) await page.send('Input.dispatchDragEvent', { type, x: Math.round(b.x), y: Math.round(b.y), data });
  277. };
  278. await page.send('Network.enable');
  279. const slow = (on) => page.send('Network.emulateNetworkConditions', { offline: false, latency: on ? 20 : 0, downloadThroughput: -1, uploadThroughput: on ? 2 * 1024 * 1024 : -1 });
  280. await slow(true);
  281. 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 }); })()`);
  282. 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 }); })()`);
  283. await dropFiles(['photo.jpg', 'notes.txt', 'slides.pdf']);
  284. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 3`, { timeout: 10000, label: 'three rows' }).catch(() => {});
  285. const r0 = await rows();
  286. 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));
  287. 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));
  288. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 3`, { timeout: 60000, label: 'three uploaded' }).catch(() => {});
  289. const r1 = await rows();
  290. const sn = await ev('window.__snaps');
  291. 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));
  292. check('#5: all three end Uploaded with a full bar', r1.length === 3 && r1.every(r => r.endsWith('|Uploaded|1')), JSON.stringify(r1));
  293. check('#5: the line under them says 3 of 3 uploaded', (await summary()) === '3 of 3 uploaded', await summary());
  294. const sizes = execSync(`ls -l ${join(APP, 'storage/uploads')}`).toString();
  295. 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);
  296. const fr = await ev('window.__fr');
  297. 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)));
  298. 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));
  299. // choosing several files (the input takes more than one)
  300. const { root } = await page.send('DOM.getDocument');
  301. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: 'files-upload input[type=file]' });
  302. 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`));
  303. try { await page.send('DOM.setFileInputFiles', { files: [F('a.txt'), F('b.txt')], nodeId }); } catch {}
  304. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 5`, { timeout: 30000, label: 'five uploaded' }).catch(() => {});
  305. const r2 = await rows();
  306. 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()]));
  307. // a file over the app's limit fails in its own row; the next file still goes
  308. await dropFiles(['huge.bin', 'a.txt']);
  309. await page.waitFor(`document.querySelectorAll('files-upload li.done, files-upload li.failed').length === 7`, { timeout: 60000, label: 'seven ended' }).catch(() => {});
  310. const r3 = await rows();
  311. 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()]));
  312. // a drop during an upload waits in its row and follows
  313. await dropFiles(['big.bin']);
  314. await page.waitFor(`!!document.querySelector('files-upload li.busy')`, { timeout: 10000, label: 'big busy' }).catch(() => {});
  315. await dropFiles(['late.txt']);
  316. await page.waitFor(`document.querySelectorAll('files-upload ul.files li').length === 9`, { timeout: 10000, label: 'late row' }).catch(() => {});
  317. const r4 = await rows();
  318. 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)));
  319. await page.waitFor(`document.querySelectorAll('files-upload li.done').length === 8`, { timeout: 60000, label: 'all ended' }).catch(() => {});
  320. const r5 = await rows();
  321. 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()]));
  322. await slow(false);
  323. await page.send('Network.disable');
  324. 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());
  325. await ev('scrollTo(0, 0)'); await sleep(200); await shot('files-upload-1280');
  326. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  327. await ev('scrollTo(0, 0)'); await sleep(300); await shot('files-upload-390');
  328. await page.close();
  329. }
  330. // the pagination: 89 pages; the ticket's three shapes
  331. check('home lists the pagination', home.includes('id="open-pagination"'));
  332. check('pagination README is served', (await fetch(BASE + '/pagination/README.md')).ok);
  333. await page.goto(BASE + '/pagination');
  334. await page.waitForSelector('#pagination-items');
  335. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  336. await sleep(500);
  337. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  338. const clickPg = (t) => ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === ${JSON.stringify(t)}).click()`);
  339. const waitPg = (t) => page.waitFor(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ') === ${JSON.stringify(t)}`, { label: 'pagination ' + t });
  340. check('pagination: first page shows 1 2 3 4 … 89 Next', (await pg()) === '1 2 3 4 … 89 Next', await pg());
  341. await clickPg('4'); await waitPg('Previous 1 2 3 4 5 … 89 Next');
  342. check('pagination: page 4 fills a one-page gap: Previous 1 2 3 4 5 … 89 Next', true);
  343. 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');
  344. await waitPg('Previous 1 … 6 7 8 … 89 Next');
  345. check('pagination: middle shows first, last, current ± 1', true);
  346. check('pagination: current page is marked', (await ev(`document.querySelector('#pagination-items li.current button').textContent`)) === '7');
  347. await ev(`document.querySelector('#pagination-items li.gap button').click()`); await sleep(300);
  348. check('pagination: a click on … does nothing', (await pg()) === 'Previous 1 … 6 7 8 … 89 Next');
  349. await clickPg('Previous'); await waitPg('Previous 1 … 5 6 7 … 89 Next');
  350. check('pagination: Previous goes back one page', true);
  351. await clickPg('89'); await waitPg('Previous 1 … 86 87 88 89');
  352. check('pagination: last page shows Previous 1 … 86 87 88 89, no Next', true);
  353. await clickPg('1'); await waitPg('1 2 3 4 … 89 Next');
  354. check('pagination: back on page 1 no Previous', true);
  355. // ticket #16 (mission 005): the host is told the target page on every click — real pointer clicks, keyboard Enter / Space, a script's
  356. // click(); Previous / Next / numbers / the first and last page; nothing for … or the current page. The demo hands `onPage = heardPage`.
  357. {
  358. await page.goto(BASE + '/pagination');
  359. await page.waitForSelector('#pagination-items');
  360. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  361. await sleep(500);
  362. const pg = () => ev(`[...document.querySelectorAll('#pagination-items button')].map(b => b.textContent).join(' ')`);
  363. const heard = () => ev(`(document.getElementById('pagination-heard') || {}).textContent`);
  364. 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`; };
  365. const told = (want) => page.waitFor(`(document.getElementById('pagination-heard') || {}).textContent === ${JSON.stringify(want)}`, { label: 'host told ' + want, timeout: 3000 }).then(() => true, () => false);
  366. 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); };
  367. 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); };
  368. check('#16: the host has heard nothing before a click', (await heard()) === 'none yet', await heard());
  369. 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()]));
  370. 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()]));
  371. 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()]));
  372. 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()]));
  373. 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()]));
  374. 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()]));
  375. const g = await sel('…'); try { await page.click(g, { timeout: 2000 }); } catch {} await sleep(400);
  376. 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()]));
  377. const c = await sel('1'); try { await page.click(c, { timeout: 2000 }); } catch {} await sleep(400);
  378. check('#16: a click on the current page tells nothing', (await heard()) === 'page 1', await heard());
  379. check('#16: keyboard Enter on 3 tells page 3', await pressOn('3', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  380. check('#16: keyboard Space on Next tells page 4', await pressOn('Next', ' ', 'page 4'), JSON.stringify([await heard(), await pg()]));
  381. check('#16: keyboard Enter on Previous tells page 3', await pressOn('Previous', 'Enter', 'page 3'), JSON.stringify([await heard(), await pg()]));
  382. 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`));
  383. await ev(`[...document.querySelectorAll('#pagination-items button')].find(b => b.textContent === '89').click()`);
  384. check('#16: a script click() on 89 tells page 89', await told('page 89'), await heard());
  385. 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(' ')`));
  386. check('#16: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  387. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  388. await sleep(300); await shot('pagination-390');
  389. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  390. await sleep(200);
  391. }
  392. await shot('pagination');
  393. check('no console errors on the pagination page', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  394. // the Markdown editor: two on one page, real typing and real clicks
  395. check('home lists the Markdown editor', home.includes('id="open-md-editor"'));
  396. const mdr = await fetch(BASE + '/md-editor/README.md');
  397. check('Markdown editor README is served as Markdown', mdr.ok && /markdown/.test(mdr.headers.get('content-type')) && (await mdr.text()).includes('Markdown editor'));
  398. 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());
  399. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  400. await page.goto(BASE + '/md-editor');
  401. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  402. const ED = 'md-editor:nth-of-type(1)';
  403. const md1 = (q) => `document.querySelectorAll('md-editor')[0].${q}`;
  404. const md2 = (q) => `document.querySelectorAll('md-editor')[1].${q}`;
  405. const val1 = () => ev(md1(`querySelector('input.value').value`));
  406. const val2 = () => ev(md2(`querySelector('input.value').value`));
  407. const art1 = () => ev(md1(`querySelector('article').innerHTML`));
  408. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  409. 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());
  410. 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());
  411. check('the canonical form of the value equals it (round trip)', await ev(md1(`mdCanon`) + ` === ` + md1(`querySelector('input.value').value`)));
  412. check('the second editor is empty and shows its placeholder', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('.placeholder')).display`)) === 'block');
  413. 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 }); };
  414. const typeText = async (t) => { for (const ch of t) await key(ch, '', undefined, ch); };
  415. const enter = () => key('Enter', 'Enter', 13, '\r');
  416. // type into the second editor: heading, bold, code, list
  417. await page.click('md-editor:nth-of-type(2) article');
  418. check('the placeholder goes away when it has text', true);
  419. await typeText('# Title'); await typeText(' '); await typeText('here'); await enter();
  420. await typeText('a **bold** and `code` x'); await enter();
  421. check('typing "# " makes a heading while you type', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  422. const html2 = await ev(md2(`querySelector('article').innerHTML`));
  423. check('typing **x** and `x` formats them', /<strong>bold<\/strong>/.test(html2) && /<code>code<\/code>/.test(html2), html2);
  424. await typeText('- '); await sleep(100);
  425. check('typing "- " makes a list', (await ev(md2(`querySelector('article ul')`) + ' !== null')));
  426. await typeText('item one'); await enter(); await typeText('item two');
  427. await sleep(400);
  428. const v2 = await val2();
  429. 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));
  430. check('the demo shows that value below the editor', (await ev(`document.getElementById('md-value-summary').textContent`)) === v2);
  431. check('the first editor was not touched by typing in the second', (await val1()).startsWith('# Hello'));
  432. check('the editor content survives re-renders of the page (same article element)', (await ev(md2(`querySelector('article h1')`) + ' !== null')));
  433. // toolbar: select the first list item in the first editor, Bold, then Undo
  434. 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)})()`);
  435. await selectIn(0, 'li:nth-child(1)');
  436. await page.click('md-editor:nth-of-type(1) nav button.bold'); await sleep(250);
  437. check('toolbar Bold: the selection is **bold** in the value', (await val1()).endsWith('- **first**\n- second'), await val1());
  438. await page.click('md-editor:nth-of-type(1) nav button.undo'); await sleep(250);
  439. check('toolbar Undo takes it back', (await val1()).endsWith('- first\n- second'), await val1());
  440. await selectIn(0, 'h1');
  441. await page.click('md-editor:nth-of-type(1) nav button.heading'); await sleep(250);
  442. check('toolbar heading button: H1 becomes H2', (await val1()).startsWith('## Hello'), await val1());
  443. await selectIn(0, 'ul');
  444. await page.click('md-editor:nth-of-type(1) nav button.ol'); await sleep(250);
  445. check('toolbar numbered list: the bullets become 1. 2.', (await val1()).endsWith('1. first\n2. second'), await val1());
  446. await selectIn(0, 'p');
  447. await page.click('md-editor:nth-of-type(1) nav button.pre'); await sleep(250);
  448. check('toolbar code block: the paragraph becomes a fenced block', /```\nSome .*\n```/.test(await val1()), await val1());
  449. // link: Ctrl+K opens the small form, Apply
  450. 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()})()`);
  451. await page.click('md-editor:nth-of-type(2) nav button.link'); await sleep(250);
  452. check('the link form opens', (await ev(`getComputedStyle(document.querySelectorAll('md-editor')[1].querySelector('link-form')).display`)) === 'flex');
  453. await ev(md2(`querySelector('link-form input').focus()`));
  454. await typeText('https://example.org/x'); await enter(); await sleep(300);
  455. check('a link is added: [text](url) in the value', (await val2()).includes('# [Title here](https://example.org/x)'), await val2());
  456. 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:'); })());
  457. // paste Markdown in: formatted, plain text; html in it stays text
  458. 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}))})()`);
  459. await sleep(300);
  460. const a1 = await art1();
  461. check('pasted Markdown shows formatted', /<h2>Pasted<\/h2><p>hello <strong>there<\/strong> /.test(a1), a1);
  462. check('pasted HTML stays text (no element made from it)', !/<b>x<\/b>/.test(a1) && (await val1()).includes('\\<b>x\\</b>'), a1);
  463. // the Markdown source switch
  464. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  465. 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');
  466. 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 }))`);
  467. await sleep(200);
  468. 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()));
  469. await page.click('md-editor:nth-of-type(1) footer button'); await sleep(300);
  470. 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());
  471. // the form posts both editors by name
  472. await page.click('#md-form button[type=submit]'); await sleep(800);
  473. const url = new URL(await ev('location.href'));
  474. 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);
  475. await shot('md-editor');
  476. 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());
  477. // typed Markdown shortcuts are CONSUMED: the marker disappears, only the formatting stays (real keys, one character at a time)
  478. await page.goto(BASE + '/md-editor');
  479. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  480. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  481. 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); };
  482. const typeR = async (t) => { for (const ch of t) await keyR(ch, ch === ' ' ? 'Space' : '', ch === ' ' ? 32 : undefined, ch); };
  483. const enterR = () => keyR('Enter', 'Enter', 13, '\r');
  484. // ticket #17 (mission 005): backslash + r in loaded Markdown stays — it is text (C:\root), not a carriage return; typed in the source
  485. // view with real keys, loaded back into the visual editor, written as Markdown and loaded once more. A REAL carriage return (a Windows
  486. // clipboard's CR LF) goes.
  487. {
  488. const S2 = 'md-editor:nth-of-type(2)';
  489. const text2 = () => ev(md2(`querySelector('article').textContent`));
  490. await page.click(S2 + ' footer button'); await sleep(300);
  491. await page.focus(S2 + ' textarea');
  492. await typeR('Path C:\\root\\new and \\r\\n stay'); await sleep(200);
  493. await page.click(S2 + ' footer button'); await sleep(400);
  494. 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()));
  495. const v17 = await val2();
  496. 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));
  497. await page.click(S2 + ' footer button'); await sleep(300);
  498. await page.click(S2 + ' footer button'); await sleep(400);
  499. 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()]));
  500. 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 })); })()`);
  501. await sleep(400);
  502. const v17b = await val2();
  503. 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));
  504. check('#17: no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  505. await page.goto(BASE + '/md-editor');
  506. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  507. await page.waitFor(md1(`querySelector('article h1')`) + ' !== null', { label: 'the value shows formatted' });
  508. }
  509. 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); };
  510. const valR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('input.value').value`);
  511. const artR = (i) => ev(`document.querySelectorAll('md-editor')[${i}].querySelector('article').innerHTML`);
  512. await page.click('md-editor:nth-of-type(2) article');
  513. await typeR('# Heading'); await sleep(200);
  514. 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)]));
  515. await wipe(1);
  516. await typeR('# Again'); await sleep(200);
  517. check('typing "# " after the editor was emptied (an empty heading is left): "# Again", not "# # Again"', (await valR(1)) === '# Again', JSON.stringify(await valR(1)));
  518. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  519. await typeR('- one'); await enterR(); await typeR('- two'); await sleep(200);
  520. 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)]));
  521. await enterR(); await typeR('1. three'); await sleep(200);
  522. 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)));
  523. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  524. await typeR('1. a'); await enterR(); await typeR('2. b'); await sleep(200);
  525. 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)));
  526. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  527. await typeR('# One'); await enterR(); await typeR('text'); await enterR(); await typeR('## Two'); await sleep(200);
  528. 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)]));
  529. check('no console errors while typing shortcuts', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  530. // ==== mission 004 (creator notes#5): GITHUB PIPE TABLES in the Markdown editor — the behaviour of notes' md-editor.js (9acc27f),
  531. // pure Hybriel. The demo's third editor ("plan") starts with a table; the second is typed into with real keys, one at a time.
  532. await page.goto(BASE + '/md-editor');
  533. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  534. 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' });
  535. // 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
  536. const evq = (e) => ev(e).catch(() => null);
  537. 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.';
  538. const tShape = (i) => ev(`(() => { const t = document.querySelectorAll('md-editor')[${i}].querySelector('article table'); if (!t) return null;
  539. return { rows: [...t.querySelectorAll('tr')].map(tr => [...tr.children].map(c => c.tagName.toLowerCase() + ':' + c.innerHTML.replaceAll('\\u200b', ''))),
  540. align: [...t.querySelector('tr').children].map(c => (c.getAttribute('data-align') || '') + '/' + getComputedStyle(c).textAlign),
  541. before: t.previousElementSibling && t.previousElementSibling.outerHTML, after: t.nextElementSibling && t.nextElementSibling.outerHTML } })()`);
  542. const s0 = await tShape(2).catch(() => null);
  543. 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',
  544. 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']])
  545. && 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));
  546. check('tables: an untouched table is the same Markdown byte for byte', (await valR(2)) === PLAN, JSON.stringify(await valR(2)));
  547. await evq(`(() => { const a = document.querySelectorAll('md-editor')[2].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a.querySelector('table').nextElementSibling); s.collapseToEnd(); })()`);
  548. await typeR(' More.'); await sleep(200);
  549. 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)));
  550. // one cell edited: only that row changes in the Markdown (written in the canonical padded form, the other cells the same)
  551. 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(); })()`);
  552. await typeR('!'); await sleep(200);
  553. const v3 = await valR(2);
  554. const mdCells = (l) => l.split(/(?<!\\)\|/).slice(1, -1).map(c => c.trim());
  555. const tl3 = v3.split('\n').filter(l => l.startsWith('|'));
  556. check('tables: editing one cell changes only that cell (the table is written in the canonical form, every other cell the same)',
  557. 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']])
  558. && new Set(tl3.map(l => l.length)).size === 1, JSON.stringify(v3));
  559. // typing a table with real keys in the (emptied) second editor
  560. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  561. const tab = (shift) => keyR('Tab', 'Tab', 9, undefined, shift ? 8 : 0);
  562. 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) })()`);
  563. await typeR('Before the table'); await enterR();
  564. await typeR('| Item | Qty | Note \\| x |'); await enterR();
  565. await typeR('|:---|:---:|---:|'); await enterR(); await sleep(200);
  566. const s1 = await tShape(1);
  567. 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',
  568. 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()]));
  569. await typeR('**milk**'); await tab(); await typeR('`2`'); await tab(); await typeR('a|b'); await enterR();
  570. 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());
  571. await typeR('bread'); await tab(); await typeR('1'); await tab(); await typeR('wholegrain-sourdough-with-seeds-and-a-very-long-name'); await enterR();
  572. await enterR(); await sleep(150);
  573. 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)]));
  574. await typeR('after the table'); await enterR(); await typeR('a | b stays text'); await sleep(300);
  575. const s2 = await tShape(1);
  576. check('tables: the typed cells — **bold**, `code`, a typed pipe, a long word; the alignment of the delimiter row',
  577. 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']])
  578. && s2.align.join(' ') === 'left/left center/center right/right', JSON.stringify(s2));
  579. 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>'
  580. && (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)]));
  581. const W = [8, 3, 52], prow = (cells) => '| ' + cells.map((c, k) => c.padEnd(W[k])).join(' | ') + ' |';
  582. const TYPED = ['Before the table', '', prow(['Item', 'Qty', 'Note \\| x']), '| :' + '-'.repeat(7) + ' | :-: | ' + '-'.repeat(51) + ': |', prow(['**milk**', '`2`', 'a\\|b']),
  583. prow(['bread', '1', 'wholegrain-sourdough-with-seeds-and-a-very-long-name']), '', 'after the table', '', 'a | b stays text'].join('\n');
  584. 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)));
  585. // Shift+Tab back; Tab in the last cell adds a row
  586. 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(); })()`);
  587. await tab(true);
  588. check('tables: Shift+Tab moves to the cell before (here: the last header cell)', (await caretCell()) === 'TH2', await caretCell());
  589. 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(); })()`);
  590. await tab(); await typeR('x'); await sleep(150);
  591. 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)));
  592. // Backspace / Delete never merge a table with the text around it
  593. 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); })()`);
  594. const before1 = await valR(1);
  595. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  596. 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()]));
  597. 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); })()`);
  598. await keyR('Delete', 'Delete', 46); await sleep(150);
  599. 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)));
  600. await evq(`(() => { const a = document.querySelectorAll('md-editor')[1].querySelector('article'); const c = a.querySelector('th'); const s = getSelection(); s.collapse(c.firstChild, 0); })()`);
  601. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  602. 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)));
  603. // a selection from the paragraph before into the table: the text is cut, the selected cells emptied, the table stays
  604. 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); })()`);
  605. await keyR('Backspace', 'Backspace', 8); await sleep(150);
  606. const s3 = await tShape(1);
  607. check('tables: Backspace on a selection from the text into a table cuts the text, empties the selected cells, keeps the table (nothing merged)',
  608. 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));
  609. // the Markdown source switch and back: the same table
  610. const v4 = await valR(1);
  611. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  612. await page.click('md-editor:nth-of-type(2) footer button'); await sleep(300);
  613. 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]));
  614. // a pasted HTML table (a spreadsheet, a web page) becomes a table: its cells' text, align / text-align, the widest row
  615. await evq(`(() => { const a = document.querySelectorAll('md-editor')[0].querySelector('article'); a.focus(); const s = getSelection(); s.selectAllChildren(a); s.collapseToEnd();
  616. 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');
  617. a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true })); })()`);
  618. await sleep(400);
  619. 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',
  620. (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)));
  621. // pasted Markdown with a table in it (plain text) becomes a table too
  622. await wipe(1); await keyR('Backspace', 'Backspace', 8);
  623. 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 })); })()`);
  624. await sleep(300);
  625. 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)]));
  626. 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());
  627. // the look at 1280 and on a phone: thin grey lines, no colour; a wide table scrolls inside its box, the page does not
  628. await page.goto(BASE + '/md-editor');
  629. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  630. await page.waitFor(`document.querySelectorAll('md-editor')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  631. const look = await evq(`(() => { const c = getComputedStyle(document.querySelectorAll('md-editor')[2].querySelector('article td')); return c.borderTopWidth + ' ' + c.borderTopStyle + ' ' + c.borderTopColor })()`);
  632. check('tables: thin grey cell lines (1px solid #999 in the base look)', look === '1px solid rgb(153, 153, 153)', look);
  633. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  634. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  635. await shot('md-editor-table-1280');
  636. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  637. await page.goto(BASE + '/md-editor');
  638. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  639. await page.waitFor(`document.querySelectorAll('md-editor')[2].querySelector('article table') !== null`, { label: 'table shown' }).catch(() => null);
  640. 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 } })()`)) || {};
  641. 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));
  642. await ev(`document.querySelectorAll('md-editor')[2].scrollIntoView()`); await sleep(200);
  643. await shot('md-editor-table-390');
  644. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  645. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  646. await page.goto(BASE + '/md-editor'); await sleep(800);
  647. check('the Markdown editor fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  648. await shot('md-editor-narrow');
  649. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  650. // ticket #9: files and images in the Markdown editor (drop, paste, choose) go through emit, with progress, and land in the text
  651. {
  652. await page.goto(BASE + '/md-editor');
  653. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  654. await sleep(600);
  655. const PNG = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
  656. 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' }));`;
  657. 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 })); })()`);
  658. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("doc.pdf")', { timeout: 30000, label: 'files uploaded' });
  659. const v = await ev(md2(`querySelector('input.value').value`));
  660. 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));
  661. 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);
  662. 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))`));
  663. 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]')));
  664. check('progress rows are gone afterwards', (await ev(md2(`querySelector('ul.files').children.length`))) === 0);
  665. const url = v.match(/\]\((\/md-editor\/files\/[\w.-]+\.pdf)\)/)[1];
  666. const got = await fetch(BASE + url);
  667. 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') || ''));
  668. // a pasted image lands too, at the caret
  669. 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 })); })()`);
  670. await page.waitFor(md1(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'pasted image' });
  671. check('a pasted image is added too', true);
  672. // an image in typed-in Markdown is drawn; only http(s) and site paths are images
  673. 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 })); })()`);
  674. await sleep(300);
  675. const srcs = await ev(`JSON.stringify([...document.querySelectorAll('md-editor')[1].querySelectorAll('article img')].map(i => i.getAttribute('src')))`);
  676. check('javascript: and data: images are not made', !srcs.includes('javascript') && !srcs.includes('data:') && srcs.includes('/x.png'), srcs);
  677. // 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
  678. {
  679. const one = mkFiles.replace("dt.items.add(new File([png], 'two.png', { type: 'image/png' }));", '').replace(/dt\.items\.add\(new File\(\[big\][^;]*;/, '');
  680. const fire = {
  681. drop: `a.dispatchEvent(new DragEvent('drop', { dataTransfer: dt, bubbles: true, cancelable: true, clientX: 0, clientY: 0 }));`,
  682. paste: `a.dispatchEvent(new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true }));`,
  683. choose: `const inp = ed.querySelector('input.pick'); inp.files = dt.files; inp.dispatchEvent(new Event('change', { bubbles: true }));`,
  684. };
  685. for (const way of ['drop', 'paste', 'choose']) {
  686. for (const caret of ['in item', 'none']) {
  687. 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 })); })()`);
  688. await sleep(300);
  689. 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', ''));
  690. await page.waitFor(md2(`querySelector('input.value').value`) + '.includes("![one.png]")', { timeout: 30000, label: 'list ' + way });
  691. const lv = await ev(md2(`querySelector('input.value').value`));
  692. 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));
  693. }
  694. }
  695. }
  696. check('no console errors on files/images', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  697. await shot('md-editor-files');
  698. }
  699. // the code editor: real keys, real typing
  700. {
  701. check('home lists the code editor', home.includes('id="open-code-editor"'));
  702. const cer = await fetch(BASE + '/code-editor/README.md');
  703. check('Code editor README is served as Markdown', cer.ok && /markdown/.test(cer.headers.get('content-type')) && (await cer.text()).includes('Code editor'));
  704. check('no .js of its own in components/code-editor', !execSync(`find ${join(APP, 'components/code-editor')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  705. await page.send('Emulation.setDeviceMetricsOverride', { width: 1000, height: 1000, deviceScaleFactor: 1, mobile: false });
  706. await page.goto(BASE + '/code-editor');
  707. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  708. const CE = (i, q) => `document.querySelectorAll('code-editor')[${i}].${q}`;
  709. const cval = (i) => ev(CE(i, `querySelector('input.value').value`));
  710. const ctext = (i) => ev(CE(i, `querySelector('article').textContent`));
  711. const cgut = (i) => ev(CE(i, `querySelector('code-gutter').textContent`));
  712. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  713. check('Hybriel code is highlighted: comment, keyword, string, function', await ev(`['comment','keyword','string','function'].every(k => ${CE(0, `querySelector('article .tok-' + k)`)} !== null)`));
  714. check('JavaScript is highlighted too: number, comment, string', await ev(`['comment','string','number','keyword'].every(k => ${CE(1, `querySelector('article .tok-' + k)`)} !== null)`));
  715. 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`));
  716. 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)));
  717. check('the value is the plain text (no markup)', (await cval(0)).startsWith('// a Hybriel component\nString title') && !(await cval(0)).includes('<span'));
  718. 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 }); };
  719. const ctype = async (t) => { for (const ch of t) { if (ch === '\n') await ckey('Enter', 'Enter', 13, '\r'); else await ckey(ch, '', undefined, ch); } };
  720. const CTRL = 2, SHIFT = 8;
  721. const tab = (shift) => ckey('Tab', 'Tab', 9, undefined, shift ? SHIFT : 0);
  722. const undo = () => ckey('z', 'KeyZ', 90, undefined, CTRL);
  723. const redo = () => ckey('z', 'KeyZ', 90, undefined, CTRL | SHIFT);
  724. // put the caret at text offsets (start..end) of editor i and focus it
  725. 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)})()`);
  726. await caret(0, (await cval(0)).length);
  727. await ctype('\nlet n = 5');
  728. 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)));
  729. 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')})()`));
  730. check('the demo shows that text below the editor', (await ev(`document.getElementById('code-value-hybriel').textContent`)) === (await cval(0)));
  731. check('the other editor was not touched', (await cval(1)).startsWith('function add(a, b) {'));
  732. // Tab / Shift+Tab on one line
  733. await ctype('\n'); await tab(false); await ctype('x');
  734. check('Tab inserts a tab character', (await cval(0)).endsWith('let n = 5\n\tx'), JSON.stringify((await cval(0)).slice(-14)));
  735. await tab(true);
  736. check('Shift+Tab removes it again', (await cval(0)).endsWith('let n = 5\nx'), JSON.stringify((await cval(0)).slice(-14)));
  737. // Enter keeps the indent; { closes itself; Enter between the braces opens an indented line
  738. await ctype('\n'); await tab(false); await ctype('if (a) {');
  739. check('typing { adds the closing }', (await cval(0)).endsWith('\tif (a) {}'), JSON.stringify((await cval(0)).slice(-14)));
  740. await ctype('\n');
  741. 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)));
  742. await ctype('y'); await ctype('\n');
  743. 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)));
  744. // typing the closer steps over it; a quote closes itself
  745. await ckey('Backspace', 'Backspace', 8); await ckey('Backspace', 'Backspace', 8); await ctype('call("a"');
  746. 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)));
  747. // undo / redo: back through typing, then forward again
  748. const before = await cval(0);
  749. await undo(); await sleep(50);
  750. const u1 = await cval(0);
  751. check('Ctrl+Z undoes the last change', u1 !== before && u1.length < before.length + 4, JSON.stringify(u1.slice(-20)));
  752. await undo(); await undo(); await sleep(50);
  753. const u3 = await cval(0);
  754. check('Ctrl+Z again goes further back', u3.length < u1.length, JSON.stringify(u3.slice(-20)));
  755. await redo(); await redo(); await redo(); await sleep(50);
  756. check('Ctrl+Shift+Z redoes them: the text is back', (await cval(0)) === before, JSON.stringify((await cval(0)).slice(-20)));
  757. await ckey('y', 'KeyY', 89, undefined, CTRL);
  758. 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'); })());
  759. check('the line numbers follow undo', (await cgut(0)) === '1\n2\n3\n4\n5\n6\n7\n8\n9\n10', JSON.stringify(await cgut(0)));
  760. // several lines selected: Tab indents all, Shift+Tab outdents all
  761. const v0 = await cval(0);
  762. await caret(0, 0, v0.length);
  763. await tab(false);
  764. 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)));
  765. await tab(true);
  766. check('Shift+Tab outdents them all again', (await cval(0)) === v0, JSON.stringify((await cval(0)).slice(0, 60)));
  767. // the second editor indents with two spaces
  768. const w0 = await cval(1);
  769. await caret(1, 0); await tab(false);
  770. check('spaces = 2: Tab inserts two spaces', (await cval(1)) === ' ' + w0, JSON.stringify((await cval(1)).slice(0, 30)));
  771. await tab(true);
  772. check('spaces = 2: Shift+Tab removes them', (await cval(1)) === w0);
  773. // text inserted as a whole (paste): several lines, highlighted, numbered
  774. await caret(1, (await cval(1)).length);
  775. 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}))})()`);
  776. await sleep(150);
  777. 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)));
  778. // the form posts both by name
  779. await page.click('#code-form button[type=submit]'); await sleep(800);
  780. const curl = new URL(await ev('location.href'));
  781. 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));
  782. // the code is only ever text: broken / hostile code shows literally, the page structure stays, nothing runs
  783. await page.goto(BASE + '/code-editor');
  784. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  785. await page.waitFor(CE(0, `querySelector('article .tok-keyword')`) + ' !== null', { label: 'the code is highlighted' });
  786. 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`);
  787. const shape0 = await shape();
  788. await caret(1, (await cval(1)).length);
  789. await ctype('\nif (x) {');
  790. await sleep(300);
  791. check('unbalanced code renders inside the field as typed', (await cval(1)).includes('if (x) {}') && (await shape()) === shape0, await shape() + ' vs ' + shape0);
  792. await ctype('\n'); await ctype('}');
  793. 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)));
  794. await ev(`window.__pwned = undefined`);
  795. await ctype('\n</div><b>x');
  796. await ctype('\n<img src=x onerror=window.__pwned=1>');
  797. await sleep(500);
  798. 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);
  799. 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>'));
  800. check('typed code did not run (window.__pwned stays undefined)', (await ev(`typeof window.__pwned`)) === 'undefined');
  801. await page.goto(BASE + '/code-editor'); await sleep(800);
  802. await page.goto(BASE + '/code-editor'); await sleep(800);
  803. await shot('code-editor');
  804. 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());
  805. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  806. await page.goto(BASE + '/code-editor'); await sleep(800);
  807. check('the code editor page fits at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  808. await shot('code-editor-narrow');
  809. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  810. }
  811. // 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
  812. {
  813. check('home lists the modal', home.includes('id="open-modal"'));
  814. const mor = await fetch(BASE + '/modal/README.md');
  815. check('modal README is served as Markdown', mor.ok && /markdown/.test(mor.headers.get('content-type')) && (await mor.text()).includes('# Modal'));
  816. check('no .js of its own in components/modal', !execSync(`find ${join(APP, 'components/modal')} -name '*.js' -o -name '*.mjs'`).toString().trim());
  817. const modalRun = async (w, h, mobile, tag) => {
  818. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile });
  819. await page.goto(BASE + '/modal');
  820. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  821. await sleep(500);
  822. const at = async (x, y) => {
  823. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' });
  824. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 });
  825. await sleep(60);
  826. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x, y, button: 'left', clickCount: 1 });
  827. await sleep(300);
  828. };
  829. 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); };
  830. 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); };
  831. const openIds = () => ev(`[...document.querySelectorAll('dialog[open]')].map(d => d.id).join()`);
  832. const last = () => ev(`document.getElementById('modal-last').textContent`);
  833. const active = () => ev(`document.activeElement.id || document.activeElement.className || document.activeElement.tagName`);
  834. const inside = (id) => ev(`document.getElementById(${JSON.stringify(id)}).contains(document.activeElement)`);
  835. // a corner of the dim background, outside every window
  836. const bg = async () => at(4, h - 4);
  837. check(`modal ${tag}: closed at first (no dialog open)`, (await openIds()) === '' && (await ev(`getComputedStyle(document.getElementById('info')).display`)) === 'none');
  838. // open by the page's button: title, content, focus inside, page inert behind
  839. await on('#open-info');
  840. 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`)));
  841. check(`modal ${tag}: the focus is inside when it opens`, await inside('info'), await active());
  842. const box = await ev(`JSON.stringify(document.getElementById('info').getBoundingClientRect())`);
  843. const b = JSON.parse(box);
  844. check(`modal ${tag}: the window is inside the screen`, b.left >= 0 && b.top >= 0 && b.right <= w && b.bottom <= h, box);
  845. 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')`));
  846. await shot(`modal-open-${w}`);
  847. // Esc
  848. await mkey('Escape', 'Escape', 27);
  849. 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()}`);
  850. // ×
  851. await on('#open-info'); await on('#info .modal-x');
  852. 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()}`);
  853. // the dim background
  854. await on('#open-info'); await bg();
  855. 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()}`);
  856. // a press inside the window that ends on the background (a text selection dragged out) does not close it
  857. await on('#open-info');
  858. const p = await ev(`(() => { const r = document.querySelector('#info modal-body p').getBoundingClientRect(); return { x: r.x + 5, y: r.y + 5 }; })()`);
  859. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: p.x, y: p.y, button: 'none' });
  860. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', x: p.x, y: p.y, button: 'left', clickCount: 1 });
  861. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 4, y: h - 4, button: 'left' });
  862. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 4, y: h - 4, button: 'left', clickCount: 1 });
  863. await sleep(300);
  864. check(`modal ${tag}: a press started inside and let go on the background keeps it open`, (await openIds()) === 'info');
  865. await mkey('Escape', 'Escape', 27);
  866. // footer buttons: the value is the reason
  867. await on('#open-confirm');
  868. check(`modal ${tag}: footer buttons are shown`, (await ev(`[...document.querySelectorAll('#confirm footer button')].map(b => b.textContent).join()`)) === 'Cancel,Delete');
  869. check(`modal ${tag}: footer buttons have no border (creator's rule)`, await ev(`[...document.querySelectorAll('#confirm button')].every(b => getComputedStyle(b).borderTopWidth === '0px')`));
  870. await on('#confirm footer button[value=ok]');
  871. 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()}`);
  872. await on('#open-confirm'); await on('#confirm footer button[value=cancel]');
  873. check(`modal ${tag}: Cancel closes it with "cancel"`, (await last()) === 'confirm: cancel');
  874. // backdrop close switched off; focus goes round inside with Tab / Shift+Tab
  875. await on('#open-form'); await bg();
  876. check(`modal ${tag}: backdropClose = "false": a click on the background leaves it open`, (await openIds()) === 'form' && (await last()) === 'confirm: cancel' && await inside('form'));
  877. const seen = [];
  878. for (let i = 0; i < 9; i++) { await mkey('Tab', 'Tab', 9); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  879. check(`modal ${tag}: Tab ×9 never leaves the window`, seen.every(s => s === 'in'), seen.join());
  880. await ev(`document.getElementById('modal-save').focus()`); await mkey('Tab', 'Tab', 9);
  881. check(`modal ${tag}: Tab on the last control goes round to the first (×)`, (await active()) === 'modal-x', await active());
  882. await mkey('Tab', 'Tab', 9, 8);
  883. check(`modal ${tag}: Shift+Tab on the first goes round to the last (Save)`, (await active()) === 'modal-save', await active());
  884. for (let i = 0; i < 6; i++) { await mkey('Tab', 'Tab', 9, 8); seen.push((await inside('form')) ? 'in' : 'OUT:' + (await active())); }
  885. check(`modal ${tag}: Shift+Tab never leaves the window`, seen.every(s => s === 'in'), seen.join());
  886. await ev(`document.getElementById('modal-name').focus()`);
  887. await page.send('Input.insertText', { text: 'Ada' }); await sleep(150);
  888. await shot(`modal-form-${w}`);
  889. // the page closes it itself, with its own reason
  890. await on('#modal-save');
  891. 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()}`);
  892. // no scroll behind: a long page scrolled down stays where it is; the long window scrolls itself
  893. await ev(`(() => { const d = document.createElement('div'); d.id = 'gate-tall'; d.style.height = '3000px'; document.querySelector('main').appendChild(d); scrollTo(0, 200); })()`);
  894. await sleep(100);
  895. await ev(`document.getElementById('open-long').click()`); await sleep(300);
  896. const y0 = await ev('scrollY');
  897. check(`modal ${tag}: while open the page cannot scroll (html overflow hidden)`, (await ev(`getComputedStyle(document.documentElement).overflow`)) === 'hidden');
  898. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: 4, y: h - 4, deltaX: 0, deltaY: 600 }); await sleep(400);
  899. 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 }; })()`);
  900. await page.send('Input.dispatchMouseEvent', { type: 'mouseWheel', x: mb.x, y: mb.y, deltaX: 0, deltaY: 600 }); await sleep(400);
  901. check(`modal ${tag}: the wheel does not scroll the page behind`, (await ev('scrollY')) === y0, `${y0} → ${await ev('scrollY')}`);
  902. 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`)));
  903. await shot(`modal-long-${w}`);
  904. await mkey('Escape', 'Escape', 27);
  905. check(`modal ${tag}: after closing the page scrolls again`, (await ev(`getComputedStyle(document.documentElement).overflow`)) !== 'hidden' && (await last()) === 'long: escape');
  906. await ev(`document.getElementById('gate-tall').remove(); scrollTo(0, 0)`); await sleep(100);
  907. check(`modal ${tag}: no horizontal overflow`, await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  908. await shot(`modal-closed-${w}`);
  909. 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());
  910. };
  911. await modalRun(1280, 900, false, '1280 px');
  912. await modalRun(390, 800, true, '390 px');
  913. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  914. }
  915. await shot('wide');
  916. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  917. await sleep(300);
  918. check('no horizontal overflow at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  919. await shot('narrow');
  920. // ==== ticket #15: THE BASE LOOK — black, white and the greys of shared/base.hl, no WorldAPI colours, no decorative frames.
  921. // (1) every colour written in a component's public file is a base value (or black with alpha for a shadow);
  922. // (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
  923. // EVERY element's computed colour, background, visible border, outline, caret, accent colour (and the modal's ::backdrop) is a grey
  924. // (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.
  925. const baseSrc = readFileSync(join(APP, 'shared/base.hl'), 'utf8');
  926. const baseValues = [...baseSrc.matchAll(/^static \w+ = var\('(#[0-9a-f]+)'\)/gm)].map(m => m[1]);
  927. check('base look: shared/base.hl names black, white and four greys', baseValues.join(' ') === '#000 #555 #999 #ddd #f2f2f2 #fff', baseValues.join(' '));
  928. const publicFiles = ['month-view/month-view.hl', 'month-view/clock.hl', 'date-picker/date-picker.hl', 'range-picker/range-picker.hl', 'pagination/pagination.hl',
  929. 'md-editor/md-editor.hl', 'code-editor/code-editor.hl', 'file-upload/file-upload.hl', 'files-upload/files-upload.hl', 'modal/modal.hl'];
  930. const foreign = [];
  931. for (const pf of publicFiles) {
  932. readFileSync(join(APP, 'components', pf), 'utf8').split('\n').forEach((line, i) => {
  933. if (/^\s*\/\//.test(line)) return;
  934. for (const m of line.matchAll(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)/g))
  935. if (!baseValues.includes(m[0]) && !/^rgba\(0, 0, 0, \.\d+\)$/.test(m[0])) foreign.push(`${pf}:${i + 1} ${m[0]}`);
  936. });
  937. }
  938. check('base look: every colour in the 10 public component files is a base value (no WorldAPI palette fallback)', foreign.length === 0, foreign.join(', '));
  939. const bwProbe = `(() => {
  940. 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]); };
  941. const bad = [], frames = [];
  942. const name = el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string' ? '.' + el.className.trim().replace(/\\s+/g, '.') : '');
  943. const comp = 'month-view, date-picker, range-picker, pagination, md-editor, code-editor, file-upload, files-upload, modal-dialog';
  944. for (const el of document.querySelectorAll('*')) {
  945. const cs = getComputedStyle(el);
  946. const props = ['color', 'backgroundColor', 'caretColor', 'accentColor', 'textDecorationColor'];
  947. 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');
  948. if (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) props.push('outlineColor');
  949. for (const p of props) if (cs[p] !== 'auto' && !grey(cs[p])) bad.push(name(el) + ' ' + p + ' ' + cs[p]);
  950. if (/^(rgba?|.* rgba?)\\(/.test(cs.boxShadow) && !(cs.boxShadow.match(/rgba?\\([^)]*\\)/g) || []).every(grey)) bad.push(name(el) + ' boxShadow ' + cs.boxShadow);
  951. if (el.tagName === 'DIALOG') { const b = getComputedStyle(el, '::backdrop').backgroundColor; if (!grey(b)) bad.push('dialog::backdrop ' + b); }
  952. // a table's cell lines are functional (mission 004), like the drop zone's
  953. if (el.closest(comp) && !el.closest('drop-zone') && !el.matches('md-editor article th, md-editor article td'))
  954. for (const side of ['Top', 'Right', 'Bottom', 'Left'])
  955. 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; }
  956. }
  957. const root = getComputedStyle(document.documentElement);
  958. const tokens = ['--color-text', '--color-background', '--color-accent', '--color-surface', '--color-border', '--orange'].filter(t => root.getPropertyValue(t).trim() !== '');
  959. const body = getComputedStyle(document.body);
  960. 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)' };
  961. })()`;
  962. const bwPages = ['/', '/month-view', '/date-picker', '/range-picker', '/pagination', '/md-editor', '/code-editor', '/file-upload', '/files-upload', '/modal'];
  963. for (const w of [1280, 390]) {
  964. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: w < 600 ? 844 : 900, deviceScaleFactor: 1, mobile: w < 600 });
  965. const results = [];
  966. for (const p of bwPages) {
  967. await page.goto(BASE + p);
  968. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated ' + p });
  969. await sleep(300);
  970. const r = await ev(bwProbe);
  971. results.push([p, r]);
  972. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  973. writeFileSync(join(SCRATCH, `gate-bw-${p === '/' ? 'home' : p.slice(1)}-${w}.png`), Buffer.from(data, 'base64'));
  974. }
  975. // the floating parts: the date picker's popup open, the modal open (its window and the dimmed page)
  976. await page.goto(BASE + '/date-picker');
  977. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  978. await page.click('date-picker input');
  979. await page.waitFor(`getComputedStyle(document.querySelector('date-picker picker-popup')).display !== 'none'`, { label: 'bw popup open' });
  980. results.push(['/date-picker (popup open)', await ev(bwProbe)]);
  981. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-date-picker-open-${w}.png`), Buffer.from(data, 'base64')); }
  982. await page.goto(BASE + '/modal');
  983. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  984. await page.click('.modal-openers button');
  985. await page.waitFor(`!!document.querySelector('modal-dialog > dialog[open]')`, { label: 'bw modal open' });
  986. await sleep(200);
  987. results.push(['/modal (open)', await ev(bwProbe)]);
  988. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-bw-modal-open-${w}.png`), Buffer.from(data, 'base64')); }
  989. 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])));
  990. 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(' '));
  991. check(`base look ${w}px: every rendered colour on the home, the 9 demos, 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])));
  992. 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])));
  993. }
  994. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  995. // ==== mission 046: THE INSTALLABLE APP — hl:web's own manifest + service worker (project.hl appIcons /
  996. // offline = [ Index ]), as tracker.worldapi.org#10. The manifest and every icon over HTTP; Chrome's own verdict
  997. // (installability, manifest parse); the worker registered for the whole app; then OFFLINE: the tab loses the
  998. // network (the note appears), the server is stopped too (CDP's offline emulation does not reach the service worker's
  999. // own fetches, so only a dead server proves the cache), and `/` still opens: header + the note + the home list. A
  1000. // demo page gets hl:web's "Unavailable offline" page. A separate 390 px tab, so its expected socket errors stay out
  1001. // of the main tab's console checks. Phone screenshots: .scratch/gate-pwa-phone-{online,offline}.png.
  1002. const html = await (await fetch(BASE + '/')).text();
  1003. const mhref = (html.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1004. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (base black, #15)',
  1005. mhref === '/__hl/manifest.webmanifest' && html.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  1006. && html.includes('<link rel="icon" href="/icons/favicon.svg">') && html.includes('<meta name="theme-color" content="#000">'), html.slice(0, 900));
  1007. const mres = await fetch(BASE + mhref);
  1008. const man = await mres.json();
  1009. 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)',
  1010. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'Hybriel components' && man.short_name === 'Components' && man.start_url === '/' && man.scope === '/'
  1011. && man.display === 'standalone' && man.theme_color === '#000' && man.background_color === '#fff', JSON.stringify(man));
  1012. const iconOk = [];
  1013. for (const ic of man.icons || []) {
  1014. const ir = await fetch(BASE + ic.src);
  1015. const b = Buffer.from(await ir.arrayBuffer());
  1016. 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]));
  1017. }
  1018. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  1019. 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));
  1020. const touch = await fetch(BASE + '/icons/apple-touch-icon.png');
  1021. const touchBytes = Buffer.from(await touch.arrayBuffer());
  1022. const fav = await fetch(BASE + '/icons/favicon.svg');
  1023. const favText = await fav.text();
  1024. const ico = await fetch(BASE + '/favicon.ico');
  1025. const icoBytes = Buffer.from(await ico.arrayBuffer());
  1026. 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',
  1027. 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')
  1028. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  1029. await page.goto('about:blank'); // the server goes down below: the main tab must not sit on a page meanwhile
  1030. const app = await browser.newPage();
  1031. const aev = (e) => app.evaluate(e);
  1032. const ashot = async (name) => { const { data } = await app.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  1033. const appHydrated = () => app.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 15000, label: 'app tab hydrated' });
  1034. await app.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1035. await app.goto(BASE + '/');
  1036. await appHydrated();
  1037. await app.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { timeout: 15000, label: 'service worker active' });
  1038. await app.waitFor(`!!navigator.serviceWorker.controller`, { timeout: 10000, label: 'page controlled by the worker' });
  1039. const inst = await app.send('Page.getInstallabilityErrors');
  1040. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  1041. const am = await app.send('Page.getAppManifest');
  1042. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, JSON.stringify(am.errors));
  1043. check('pwa: hl:web\'s service worker is registered for the whole app (scope /) and controls the page',
  1044. (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')));
  1045. check('pwa: online, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1046. check('pwa: no horizontal overflow at 390 px', await aev('document.documentElement.scrollWidth <= window.innerWidth'));
  1047. await ashot('pwa-phone-online');
  1048. await app.setOffline(true);
  1049. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 5000, label: 'offline note (live)' }).catch(() => {});
  1050. 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.');
  1051. await stopServer();
  1052. let down = false;
  1053. try { await fetch(BASE + '/'); } catch { down = true; }
  1054. await app.goto(BASE + '/');
  1055. await app.waitFor(`!!document.querySelector('#offline')`, { timeout: 8000, label: 'offline note after reload' }).catch(() => {});
  1056. 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',
  1057. down && (await aev(`document.querySelector('application-header .brand') ? document.querySelector('application-header .brand').textContent : ''`)) === 'Hybriel components'
  1058. && (await aev(`!!document.querySelector('#offline')`)) && (await aev(`document.querySelectorAll('#components li').length`)) === 9
  1059. && (await aev(`getComputedStyle(document.querySelector('application-header')).backgroundColor`)) === 'rgb(0, 0, 0)', 'server down: ' + down);
  1060. await ashot('pwa-phone-offline');
  1061. await app.goto(BASE + '/month-view');
  1062. 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');
  1063. await app.setOffline(false);
  1064. await startServer();
  1065. await app.goto(BASE + '/');
  1066. await appHydrated();
  1067. await app.waitFor(`!document.querySelector('#offline')`, { timeout: 5000, label: 'note gone' }).catch(() => {});
  1068. check('back online: / from the server again, no offline note', !(await aev(`!!document.querySelector('#offline')`)));
  1069. await app.close();
  1070. }
  1071. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  1072. await stop();
  1073. console.log(`${passes} passed, ${failures} failed`);
  1074. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 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
  • 3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre
  • 6b27c0f0components #17 (mission 005) 1/4: md-editor keeps backslash + r — parseInto dropped the two characters '\r' (C:\root -> C:oot) instead of a real carriage return; CR now decoded from JSON (String.fromCharCode does not parse in a member), real CRs also go from pasted plain text; 5 gate checks (3 fail on the old md-editor.hl)mre
  • 1a5dc327mission brief w5mre
  • a567b579components (mission 004) 3/3: docs (README Hybriel a832f73b + tables, STATUS, LOG), report reports/004-md-editor-tables.mdmre
  • 70fe7ab5components (mission 004) 2/3: GitHub pipe tables in the Hybriel MdEditor (creator notes#5; behaviour of notes md-editor.js 9acc27f, no JavaScript) — parse/render (header, :--/:-:/--: alignment, \| in cells and code, inline Markdown in cells, outer pipes optional), padded writer, unchanged table byte for byte, typing | a | b | Enter |---|---| Enter makes a table, Tab/Shift+Tab, Enter new row, Enter in empty last row leaves, Backspace/Delete never merge, selection across a table empties cells, pasted HTML table -> table, thin #999 lines, wide table scrolls in its box; demo third editor 'plan'; gate 252/0 (22 new table checks, 20 fail on the old md-editor.hl)mre
  • f2adb3f3components (mission 004) 1/3: Hybriel master a832f73b (incremental build cache, HL_CACHE_DIR, #151) — bin/hybriel sha256 e1b53f7ce687f5afbe3db34bcda69958f56e730571e4841923c9c8eb3d272db9 built from git archive a832f73b (HL_NO_PLUGINS=1 native/build.sh), the same nine plugins; container: HL_CACHE_DIR=/cache on volume hybriel-cache, /tmp tmpfs; tests wait COMPONENTS_COLD_MS (120 s) for every start; deploy.sh DEPLOY_URL_WAIT 120 s; gate 230/0 coldmre
  • 91bd8a0dmission brief (w4)mre
  • 3bc905c5components #15 (mission 003) 2/2: docs (README Look, STATUS, LOG), reportmre
  • 5a98d77ecomponents #15 (mission 003) 1/2: black/white base look — greys for nuances, no WorldAPI fallbacks, no decorative frames; site + icon black/white; gate 230/0mre
  • 3f93d716components code order (mission 002) 4/4: docs, tests/letcount.py, tests/same-output*, reportmre
  • e747cfa0components code order (mission 002) 3/4: let only where reassigned (257 dropped, 0 never-reassigned left); gate 220/0, layouts gate 73/0, same outputmre
  • 172914a3components code order (mission 002) 2/4: lib/uploads.hl (demo upload storage), thin demo handlers, project.hl map; gate 220/0, same outputmre
  • d29f35b1components code order (mission 002) 1/4: styles.hl -> components/styles.hl; gate 220/0, same outputmre
  • 09945750components: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, http1 773de63e); gate 220/0mre
  • ede4d19acomponents: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 220/0mre
  • 2bb9a935components: Hybriel master 8efba065 (re-vendor round 069: #126 memory, #48 lambda copy)mre
  • e4f01768antcolony#40: mission references point to the moved missionsmre
  • d32b44e2antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 0fb80b57components: Hybriel master ff51cf46 (re-vendor round)mre