calendar
All repositories: gitoria
11.3 KB
// 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// reused), real taps (touch at 390) / clicks (1280), dark and light. Not a gate: prints PASS/FAIL, writes screenshots.// node tests/e2e-reminder-place.mjs <old|new> <port> <sid> <shotDir> <targetId> <cdpPort> <pushLog>// 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// (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>).// old: the month view as it was (before screenshots). new: the month view, the menu, the reminder settings, "Send a test notification".import { writeFileSync, readFileSync, existsSync } from 'node:fs';import { createECDH, randomBytes } from 'node:crypto';const [mode, port, sid, shotDir, tid, cdpPort, pushLog] = process.argv.slice(2);const BASE = `http://127.0.0.1:${port}`, FPORT = Number(port) + 2, sleep = ms => new Promise(r => setTimeout(r, ms)), J = JSON.stringify;const list = await (await fetch(`http://127.0.0.1:${cdpPort}/json/list`)).json();const tgt = list.find(t => t.id === tid);const ws = new WebSocket(tgt.webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${cdpPort}`)); await new Promise(r => ws.onopen = r);let id = 0; const pend = new Map();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); } };const send = (method, params = {}) => new Promise((ok, bad) => { const i = ++id; pend.set(i, [ok, bad]); ws.send(J({ id: i, method, params })); });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; };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; };const results = []; const check = (n, ok, d = '') => { results.push([n, !!ok]); console.log((ok ? 'PASS ' : 'FAIL ') + n + (ok ? '' : ' ' + d)); };let W = 390, tag = '';const shot = async name => { const r = await send('Page.captureScreenshot', { format: 'png' }); writeFileSync(`${shotDir}/${mode}-${tag}-${name}.png`, Buffer.from(r.data, 'base64')); };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 }; })()`);const tap = async sel => { await sleep(150); const r = await centre(sel); if (!r) throw new Error('no ' + sel); await sleep(150);if (W === 390) { await send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x: r.x, y: r.y }] }); await send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] }); }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 }); };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 }; })()`);const oneState = x => (x.ask && !x.test && !x.off) || (!x.ask && x.test && x.off);await send('Page.enable'); await send('Runtime.enable'); await send('Network.enable');await send('Target.activateTarget', { targetId: tid }).catch(() => {}); await send('Page.bringToFront');let scriptId = null;async function run(width, scheme, grant) {W = width; tag = `${width}-${scheme}`; console.log(`\n== ${mode} ${tag}${grant ? '' : ' (no permission yet)'}`);await send('Emulation.setDeviceMetricsOverride', { width, height: width === 390 ? 844 : 900, deviceScaleFactor: width === 390 ? 2 : 1, mobile: width === 390 });await send('Emulation.setTouchEmulationEnabled', { enabled: width === 390, maxTouchPoints: 5 });await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: scheme }] });await send('Network.setCookie', { name: 'calendarsid', value: sid, url: BASE, httpOnly: true });await send('Storage.clearDataForOrigin', { origin: BASE, storageTypes: 'service_workers,cache_storage,local_storage' }).catch(() => {});await send('Browser.resetPermissions').catch(() => {});if (grant) await send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] }).catch(e => console.log('grant', e.message));const ua = createECDH('prime256v1'); ua.generateKeys();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') } };if (scriptId) await send('Page.removeScriptToEvaluateOnNewDocument', { identifier: scriptId }).catch(() => {});scriptId = (await send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => { const want = ${J(want)}; const key = '__held_' + ${J(tag + mode)}; let held = sessionStorage.getItem(key) === '1';const mk = () => ({ endpoint: want.endpoint, toJSON: () => want, unsubscribe: () => { sessionStorage.removeItem(key); held = false; return Promise.resolve(true); } });PushManager.prototype.subscribe = function () { sessionStorage.setItem(key, '1'); held = true; return Promise.resolve(mk()); };PushManager.prototype.getSubscription = function () { return Promise.resolve(held ? mk() : null); }; })();` })).identifier;await send('Page.navigate', { url: BASE + '/' });await waitFor(`!!document.querySelector('#month-days li')`, 'month');await waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated', 60000);await waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, 'sw', 30000);await sleep(1500);await shot('month'); // NOT touched: the first lookconst 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);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 }; })()`);console.log(' month view flow', J(flow));if (mode === 'old') { await tap('#month-title'); await sleep(1800); await shot('month-touched'); return; }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));await shot('month-header');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); })()`));await tap('#settings-open');check(`${tag} the button opens the reminder settings`, await waitFor(`document.querySelector('#settingseditor').matches(':popover-open')`, 'settings open'));await sleep(700);await sleep(300);const first = await vis();if (!grant) {await shot('settings-top');await ev(`document.querySelector('#notify-ask').scrollIntoView({ block: 'center' })`); await sleep(300); await shot('notifications');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));return;}await shot('settings-top');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)); }await ev(`document.querySelector('#push-test').scrollIntoView({ block: 'center' })`); await sleep(400); await shot('notifications');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));const before = existsSync(pushLog) ? readFileSync(pushLog, 'utf8').split('\n').filter(Boolean).length : 0;await tap('#push-test');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));await sleep(300); await shot('sent');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; }check(`${tag} the fake push service got the test push (${got})`, got === 1);await tap('#push-test'); await sleep(1200); await shot('ratelimit');check(`${tag} a second test within 30 s is refused`, /wait 30 seconds/.test(await ev(`document.querySelector('#push-state').textContent`)));await ev(`document.querySelector('#settingseditor').scrollTo(0, 0); document.querySelector('#settingseditor form').scrollTo(0, 0)`);await tap('#set-cancel'); await sleep(400);check(`${tag} Cancel closes the dialog`, !(await ev(`document.querySelector('#settingseditor').matches(':popover-open')`)));await tap('#settings-open'); await waitFor(`document.querySelector('#settingseditor').matches(':popover-open')`, 'reopen'); await sleep(600);for (const type of ['rawKeyDown', 'keyUp']) await send('Input.dispatchKeyEvent', { type, key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27 });await sleep(400);check(`${tag} Escape closes the dialog`, !(await ev(`document.querySelector('#settingseditor').matches(':popover-open')`)));}try {for (const w of [390, 1280]) for (const s of ['dark', 'light']) await run(w, s, true);if (mode === 'new') await run(390, 'dark', false);} catch (e) { check('E2E ran', false, String(e && e.stack || e)); }await send('Emulation.clearDeviceMetricsOverride').catch(() => {}); await send('Emulation.setEmulatedMedia', { features: [] }).catch(() => {}); await send('Emulation.setTouchEmulationEnabled', { enabled: false }).catch(() => {});if (scriptId) await send('Page.removeScriptToEvaluateOnNewDocument', { identifier: scriptId }).catch(() => {});console.log(`\n${results.filter(r => r[1]).length} passed, ${results.filter(r => !r[1]).length} failed`);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