gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainf9b8f918Merge branch 'calendar-vendor-day61' into mainAtlasmain/tests/e2e-reminder-place.mjs

11.3 KB

  1. // tests/e2e-reminder-place.mjs (calendar C13): where the notification controls live, in a REAL browser (lisbeth's test Chrome over CDP, ONE existing tab
  2. // reused), real taps (touch at 390) / clicks (1280), dark and light. Not a gate: prints PASS/FAIL, writes screenshots.
  3. // node tests/e2e-reminder-place.mjs <old|new> <port> <sid> <shotDir> <targetId> <cdpPort> <pushLog>
  4. // The app: tests/e2e-reminder-place-app.mjs (a COPY of a backup, a fake push service on <port>+2). The page's browser `PushManager.subscribe` is replaced
  5. // (as in tests/push.mjs) by one that answers a subscription made here; the server's push to it goes to the fake service (<pushLog>).
  6. // old: the month view as it was (before screenshots). new: the month view, the menu, the reminder settings, "Send a test notification".
  7. import { writeFileSync, readFileSync, existsSync } from 'node:fs';
  8. import { createECDH, randomBytes } from 'node:crypto';
  9. const [mode, port, sid, shotDir, tid, cdpPort, pushLog] = process.argv.slice(2);
  10. const BASE = `http://127.0.0.1:${port}`, FPORT = Number(port) + 2, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;
  11. const list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();
  12. const tgt = list.find(t => t.id === tid);
  13. const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);
  14. let id = 0; const pend = new Map();
  15. ws.onmessage = m => { const d = JSON.parse(m.data); if (d.id && pend.has(d.id)) { const [ok, bad] = pend.get(d.id); pend.delete(d.id); d.error ? bad(new Error(J(d.error))) : ok(d.result); } };
  16. const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });
  17. const ev = async x => { const r = await send('Runtime.evaluate', { expression: x, awaitPromise: true, returnByValue: true }); if (r.exceptionDetails) throw new Error(J(r.exceptionDetails).slice(0, 300)); return r.result.value; };
  18. const waitFor = async (x, label, t = 25000) => { for (const end = Date.now() + t; Date.now() < end;) { if (await ev(x).catch(() => false)) return true; await sleep(150); } console.log(' TIMEOUT', label); return false; };
  19. const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };
  20. let W = 390, tag = '';
  21. const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${tag}-${name}.png`, Buffer.from(r.data, 'base64')); };
  22. const centre = sel => ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const r = e.getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2, w: r.width, h: r.height }; })()`);
  23. const tap = async sel => { await sleep(150); const r = await centre(sel); if (!r) throw new Error('no ' + sel); await sleep(150);
  24. if (W === 390) { await send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: r.x, y: r.y }] }); await send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); }
  25. else for (const [type, extra] of [['mouseMoved', {}], ['mousePressed', { button: 'left', clickCount: 1 }], ['mouseReleased', { button: 'left', clickCount: 1 }]]) await send('Input.dispatchMouseEvent', { type, x: r.x, y: r.y, ...extra }); };
  26. const vis = () => ev(`(() => { const v = (id) => { const e = document.querySelector(id); return !!e && !e.classList.contains('hidden') && e.getBoundingClientRect().height > 0; }; const h = (id) => { const e = document.querySelector(id); return e ? Math.round(e.getBoundingClientRect().height) : 0; }; return { ask: v('#notify-ask'), test: v('#push-test'), off: v('#push-off'), blocked: v('#notify-blocked'), testH: h('#push-test'), offH: h('#push-off'), askH: h('#notify-ask'), text: (document.querySelector('#push-state') || {}).textContent }; })()`);
  27. const oneState = x => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off);
  28. await send('Page.enable'); await send('Runtime.enable'); await send('Network.enable');
  29. await send('Target.activateTarget', { targetId: tid }).catch(() => {}); await send('Page.bringToFront');
  30. let scriptId = null;
  31. async function run(width, scheme, grant) {
  32. W = width; tag = `${width}-${scheme}`; console.log(`\n== ${mode} ${tag}${grant ? '' : ' (no permission yet)'}`);
  33. await send('Emulation.setDeviceMetricsOverride', { width, height: width === 390 ? 844 : 900, deviceScaleFactor: width === 390 ? 2 : 1, mobile: width === 390 });
  34. await send('Emulation.setTouchEmulationEnabled', { enabled: width === 390, maxTouchPoints: 5 });
  35. await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });
  36. await send('Network.setCookie', { name: 'calendarsid', value: sid, url: BASE, httpOnly: true });
  37. await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});
  38. await send('Browser.resetPermissions').catch(() => {});
  39. if (grant) await send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(e => console.log('grant', e.message));
  40. const ua = createECDH('prime256v1'); ua.generateKeys();
  41. const want = { endpoint: `http://127.0.0.1:${FPORT}/ok/${mode}-${tag}-${Date.now()}`, expirationTime: null, keys: { p256dh: ua.getPublicKey().toString('base64url'), auth: randomBytes(16).toString('base64url') } };
  42. if (scriptId) await send('Page.removeScriptToEvaluateOnNewDocument', { identifier: scriptId }).catch(() => {});
  43. scriptId = (await send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { const want = ${J(want)}; const key = '__held_' + ${J(tag + mode)}; let held = sessionStorage.getItem(key) === '1';
  44. const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { sessionStorage.removeItem(key); held = false; return Promise.resolve(true); } });
  45. PushManager.prototype.subscribe = function () { sessionStorage.setItem(key, '1'); held = true; return Promise.resolve(mk()); };
  46. PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); }; })();` })).identifier;
  47. await send('Page.navigate', { url: BASE + '/' });
  48. await waitFor(`!!document.querySelector('#month-days li')`, 'month');
  49. await waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated', 60000);
  50. await waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, 'sw', 30000);
  51. await sleep(1500);
  52. await shot('month'); // NOT touched: the first look
  53. const flow = await ev(`(() => { const mv = document.querySelector('month-view'); const shown = [...mv.children].filter(e => getComputedStyle(e).position !== 'fixed' && getComputedStyle(e).display !== 'none' && e.getBoundingClientRect().height > 0);
  54. const h = mv.querySelector('header').getBoundingClientRect(), g = document.querySelector('#month-days').getBoundingClientRect(); return { tags: shown.map(e => e.tagName.toLowerCase() + (e.id ? '#' + e.id : '')), gridGap: Math.round(g.top - h.bottom), scrollW: document.documentElement.scrollWidth, innerW: window.innerWidth }; })()`);
  55. console.log(' month view flow', J(flow));
  56. if (mode === 'old') { await tap('#month-title'); await sleep(1800); await shot('month-touched'); return; }
  57. check(`${tag} the month view is header + weekdays + grid, nothing else (grid ${flow.gridGap} px below the header)`, J(flow.tags) === '["header","ol#month-weekdays","ol#month-days"]' && flow.gridGap <= 80 && flow.scrollW <= flow.innerW, J(flow));
  58. await shot('month-header');
  59. check(`${tag} the month header has "Reminder settings" (44 px tap)`, await ev(`(() => { const b = document.querySelector('#month-view #settings-open, header #settings-open'); return !!b && b.getBoundingClientRect().height >= 43.5 && /Reminder settings/.test(b.textContent); })()`));
  60. await tap('#settings-open');
  61. check(`${tag} the button opens the reminder settings`, await waitFor(`document.querySelector('#settingseditor').matches(':popover-open')`, 'settings open'));
  62. await sleep(700);
  63. await sleep(300);
  64. const first = await vis();
  65. if (!grant) {
  66. await shot('settings-top');
  67. await ev(`document.querySelector('#notify-ask').scrollIntoView({ block: 'center' })`); await sleep(300); await shot('notifications');
  68. check(`${tag} no permission yet, nothing touched before: only "Turn on notifications" (${first.askH} px), no test / off`, first.ask && !first.test && !first.off && !first.blocked && first.askH >= 44, J(first));
  69. return;
  70. }
  71. await shot('settings-top');
  72. let v = first; for (let i = 0; i < 100 && !(v.test && v.off); i++) { await sleep(200); v = await vis(); check(`${tag} (poll) one consistent state`, oneState(v) || (!v.ask && !v.test && !v.off), J(v)); }
  73. await ev(`document.querySelector('#push-test').scrollIntoView({ block: 'center' })`); await sleep(400); await shot('notifications');
  74. check(`${tag} the section shows the state text, test + off (44 px taps), no "Turn on"`, !v.ask && v.test && v.off && (W !== 390 || (v.testH >= 44 && v.offH >= 44)) && /also reach this device/.test(v.text || ''), J(v));
  75. const before = existsSync(pushLog) ? readFileSync(pushLog, 'utf8').split('\n').filter(Boolean).length : 0;
  76. await tap('#push-test');
  77. check(`${tag} "Send a test notification" is answered on the page`, await waitFor(`/on its way/.test(document.querySelector('#push-state').textContent)`, 'on its way', 8000));
  78. await sleep(300); await shot('sent');
  79. let got = 0; for (let i = 0; i < 40 && got < 1; i++) { await sleep(1000); got = (existsSync(pushLog) ? readFileSync(pushLog, 'utf8').split('\n').filter(Boolean).length : 0) - before; }
  80. check(`${tag} the fake push service got the test push (${got})`, got === 1);
  81. await tap('#push-test'); await sleep(1200); await shot('ratelimit');
  82. check(`${tag} a second test within 30 s is refused`, /wait 30 seconds/.test(await ev(`document.querySelector('#push-state').textContent`)));
  83. await ev(`document.querySelector('#settingseditor').scrollTo(0, 0); document.querySelector('#settingseditor form').scrollTo(0, 0)`);
  84. await tap('#set-cancel'); await sleep(400);
  85. check(`${tag} Cancel closes the dialog`, !(await ev(`document.querySelector('#settingseditor').matches(':popover-open')`)));
  86. await tap('#settings-open'); await waitFor(`document.querySelector('#settingseditor').matches(':popover-open')`, 'reopen'); await sleep(600);
  87. for (const type of ['rawKeyDown', 'keyUp']) await send('Input.dispatchKeyEvent', { type, key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });
  88. await sleep(400);
  89. check(`${tag} Escape closes the dialog`, !(await ev(`document.querySelector('#settingseditor').matches(':popover-open')`)));
  90. }
  91. try {
  92. for (const w of [390, 1280]) for (const s of ['dark', 'light']) await run(w, s, true);
  93. if (mode === 'new') await run(390, 'dark', false);
  94. } catch (e) { check('E2E ran', false, String(e && e.stack || e)); }
  95. await send('Emulation.clearDeviceMetricsOverride').catch(() => {}); await send('Emulation.setEmulatedMedia', { features: [] }).catch(() => {}); await send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});
  96. if (scriptId) await send('Page.removeScriptToEvaluateOnNewDocument', { identifier: scriptId }).catch(() => {});
  97. console.log(`\n${results.filter(r => r[1]).length} passed, ${results.filter(r => !r[1]).length} failed`);
  98. process.exit(results.some(r => !r[1]) ? 1 : 0);

Branches

Latest commits

  • f9b8f918Merge branch 'calendar-vendor-day61' into mainAtlas
  • 66341793|||PR Vendor Hybriel day61Atlas
  • 36fc596bMerge branch 'vendor-day59' into mainAtlas
  • b37cc1da|||PR Vendor Hybriel day59Atlas
  • 05665102Merge branch 'vendor-day56' into mainAtlas
  • 687296fb|||PR Vendor Hybriel day56Atlas
  • a6166d4eMerge branch 'hl-standard-3' into mainAtlas
  • 6d0eb3b0|||PR Calendar day add buttons only when signed in (Kunibert minor)Atlas
  • add4b499|||PR Make calendar day actions keyboard accessibleAtlas
  • 79e49b4dMerge branch 'hl-standard' into mainAtlas
  • e9fec7bb|||PR HL-STANDARD clean-up: typed parameters, plain locals, by-reference cacheAtlas
  • eff166a4Re-vendor complete Hybriel plugins and runtime to day44mre
  • cef81394Wait for the DST fixture page instead of an unused socketmre
  • 42434f47Check lazy-session cookies after login with a stored anonymous fixturemre
  • 728e84e3Re-vendor complete Hybriel day41 plugin directoriesmre
  • cbd7ff43Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 59d1da0acalendar: plain declarations instead of needless let in 9 files (calendar#17): 49 declarations that are never reassigned; reassigned ones and the timer closure's p stay letmre
  • f5415cf9calendar: the Style blocks in the language's nested form (calendar#16): rules named after the View's own elements with their children nested, pseudo-classes and @media nested, merged duplicate select rule; same CSS, shots identical in Chrome at 4 sizesmre
  • edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
  • bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre