gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb37cc1dab37cc1da|||PR Vendor Hybriel day59Atlasb37cc1da/tests/browser.mjs

59.1 KB

  1. // tests/browser.mjs — THE GATE of calendar.worldapi.org: its own server on its own storage, its OWN ident (a copy of
  2. // ident's code without .env, codes to a mail sink: tests/identkit.mjs), real headless Chrome.
  3. // node tests/browser.mjs (CALENDAR_GATE_PORT server, default 8700; CALENDAR_GATE_IDENT_PORT ident, default 8701;
  4. // CALENDAR_GATE_CHROME "8702-8709" = Chrome debug ports)
  5. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  6. import { spawn } from 'node:child_process';
  7. import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { launchBrowser } from './cdp.mjs';
  11. import { startIdent } from './identkit.mjs';
  12. // GATE_CLOCK=HH:MM (calendar mission 002): run the gate as if the local clock showed that time today — this process and
  13. // every page get Date shifted by the same amount (the server keeps its real clock; it only takes the UTC day for `soon`,
  14. // a −2…+9 day window). The reminder checks depend on the time of day; run them at 00:30 05:40 12:00 19:59 20:01 23:30.
  15. const CLOCK_SHIFT = (() => {
  16. const m = /^(\d\d):(\d\d)$/.exec(process.env.GATE_CLOCK || ''); if (!m) return 0;
  17. const n = new Date(); return new Date(n.getFullYear(), n.getMonth(), n.getDate(), Number(m[1]), Number(m[2])).getTime() - n.getTime();
  18. })();
  19. const CLOCK_SCRIPT = `(() => { const R = Date; class D extends R { constructor(...a) { if (a.length) super(...a); else super(R.now() + ${CLOCK_SHIFT}); } static now() { return R.now() + ${CLOCK_SHIFT}; } } globalThis.Date = D; })();`;
  20. if (CLOCK_SHIFT) (0, eval)(CLOCK_SCRIPT);
  21. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  22. const HERE = dirname(fileURLToPath(import.meta.url));
  23. const APP = resolve(HERE, '..');
  24. const PORT = Number(process.env.CALENDAR_GATE_PORT || 8700);
  25. const [CH_FROM, CH_TO] = (process.env.CALENDAR_GATE_CHROME || '8702-8709').split('-').map(Number);
  26. const IDENT_PORT = Number(process.env.CALENDAR_GATE_IDENT_PORT || 8701);
  27. const BASE = `http://127.0.0.1:${PORT}`;
  28. const STORE = join(APP, '.scratch', 'gate-store');
  29. const IDENT_DIR = process.env.CALENDAR_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  30. let ident = null;
  31. const SCRATCH = join(APP, '.scratch');
  32. const SESSIONS = join(SCRATCH, 'gate-sessions');
  33. rmSync(SESSIONS, { recursive: true, force: true });
  34. rmSync(STORE, { recursive: true, force: true });
  35. mkdirSync(SESSIONS, { recursive: true });
  36. // IW (creator 2026-10-24, "you removed the ident widget from all sites"): ident's <ident-selector> stands in the header, VISIBLE, top right — signed
  37. // out and signed in, on the phone and on the desktop. Returns 'ok' or what is wrong (hidden by an ancestor, no box, outside the viewport, not in the
  38. // header, not on the right, covered by something else).
  39. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  40. for (let e = s; e && e !== document.documentElement; e = e.parentElement) { const c = getComputedStyle(e); if (c.display === 'none') return 'display:none on ' + e.tagName; if (c.visibility === 'hidden') return 'visibility:hidden on ' + e.tagName; if (+c.opacity === 0) return 'opacity 0 on ' + e.tagName; }
  41. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  42. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  43. if (b.left < 0 || b.top < 0 || b.right > innerWidth + 0.5 || b.bottom > innerHeight) return 'outside the viewport ' + JSON.stringify([b.left, b.top, b.right, b.bottom]);
  44. if (b.top < h.top - 1 || b.bottom > h.bottom + 1) return 'not inside the header row ' + JSON.stringify([b.top, b.bottom, h.top, h.bottom]);
  45. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  46. const top = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); if (!top || !top.closest('ident-selector')) return 'covered by ' + (top && top.tagName);
  47. return 'ok'; })()`;
  48. let failures = 0, passes = 0;
  49. function check(label, ok, detail = '') {
  50. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  51. if (ok) passes++; else failures++;
  52. }
  53. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  54. let spawnServer = null, log = '', server = null, browser = null, lastPage = null;
  55. async function stop() {
  56. if (ident) { try { await ident.stop(); } catch {} ident = null; }
  57. if (browser) { try { await browser.close(); } catch {} browser = null; }
  58. if (server) {
  59. try { server.kill('SIGTERM'); } catch {}
  60. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  61. server = null;
  62. }
  63. }
  64. async function main() {
  65. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  66. const alice = await ident.signIn('[email protected]');
  67. const bob = await ident.signIn('[email protected]');
  68. // the reminder steps count every reminder of the next 7 days: they get an identity of their own, so alice's events from
  69. // the events steps (the all-day "Vacation" on the 20th–22nd plans 2 more from the 12th 20:00 to the 19th 23:00) do not count
  70. const carol = await ident.signIn('[email protected]');
  71. const APPKEY = await ident.registerApp(alice, 'calendar (gate)', [BASE]);
  72. check('ident: our own ident runs (a copy without .env), the calendar is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  73. spawnServer = () => {
  74. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, CALENDAR_PORT: String(PORT), CALENDAR_SESSIONS: SESSIONS + '/', CALENDAR_STORAGE: join(STORE, 'mpackdb'), CALENDAR_WATCH: '0',
  75. CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret }, stdio: ['ignore', 'pipe', 'pipe'] });
  76. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  77. };
  78. spawnServer();
  79. for (let i = 0; ; i++) {
  80. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  81. if (i > 600) throw new Error('server did not come up\n' + log);
  82. await sleep(250);
  83. }
  84. // the app's first page is the month view, rendered on the server: 6 weeks of 7 days, one today
  85. const home = await (await fetch(BASE + '/')).text();
  86. check('server renders 42 days and one today', (home.match(/<li class=/g) || []).length === 42 && (home.match(/class="today"/g) || []).length === 1);
  87. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  88. const page = await browser.newPage();
  89. lastPage = page;
  90. if (CLOCK_SHIFT) await page.addInitScript(CLOCK_SCRIPT);
  91. const SLOW = 3;
  92. const goto = page.goto.bind(page);
  93. page.goto = (u, o = {}) => goto(u, { ...o, timeout: 15000 * SLOW });
  94. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  95. await page.goto(BASE + '/');
  96. await page.waitForSelector('#month-title');
  97. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  98. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  99. const ev = (e) => page.evaluate(e);
  100. const title = () => ev('document.querySelector("#month-title").textContent');
  101. 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()); })()`);
  102. const expectTitle = (y, m) => ev(`new Intl.DateTimeFormat(navigator.language, { month: 'long' }).format(new Date(Date.UTC(${y}, ${m - 1}, 15, 12))) + ' ${y}'`);
  103. const [ty, tm] = localToday.split('-').map(Number);
  104. // ticket #6: the FIRST render (no mouse yet) already has the names, in the language of the request, when the server knows it
  105. const firstDays = await ev('[...document.querySelectorAll("#month-weekdays li")].map(l => l.textContent).join(" ")');
  106. const wantDays = await ev(`[1,2,3,4,5,6,7].map(i => new Intl.DateTimeFormat(navigator.language, { weekday: 'short' }).format(new Date(Date.UTC(2024, 0, i, 12)))).join(' ')`);
  107. if (/^(en|de|fr|es|it|nl|pt)/.test(await ev('navigator.language'))) check('first page already shows the weekday names in the browser language', firstDays === wantDays, firstDays + ' / ' + wantDays);
  108. // the browser reads its today and language on the FIRST pointer event. When the server's day is the browser's and it already drew
  109. // the names, that must not re-run show() (the month's repaint, with a calLoad round trip when signed in: the answer lands while the
  110. // user pages or taps and put the month back, lisbeth's Chrome 1280 px). Seen as the title's text being rewritten: 3c5604f rewrites it
  111. // twice per first pointer event, this fork once (the one left is hybriel's own repaint of the handler, not show()).
  112. const serverDay = await ev(`(() => { const t = document.querySelector('li.today time'); return t ? t.getAttribute('datetime') : ''; })()`);
  113. await ev(`window.__rewrites = 0; new MutationObserver(m => { window.__rewrites += m.length; }).observe(document.querySelector('#month-title'), { subtree: true, childList: true, characterData: true })`);
  114. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 400, y: 300 }); // a real user's pointer reaches the month view
  115. if (serverDay === localToday && firstDays === wantDays) {
  116. await sleep(2500);
  117. const n = await ev('window.__rewrites');
  118. check('the first pointer event does not run show() again when the server already drew the month right', n <= 1, 'title rewritten ' + n + ' times');
  119. }
  120. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === (${JSON.stringify(await expectTitle(ty, tm))}).toLowerCase()`, { label: 'title in the browser language' });
  121. check('title is the current month and year in the browser language', true);
  122. check('today is marked (browser date)', (await ev(`document.querySelector('li.today time').getAttribute('datetime')`)) === localToday, localToday);
  123. check('42 days, 6 weeks', (await ev('document.querySelectorAll("#month-days li").length')) === 42);
  124. const t0 = await title();
  125. // next / prev
  126. await page.click('#month-next');
  127. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(t0)}`, { label: 'next month' });
  128. const nm = tm === 12 ? 1 : tm + 1, ny = tm === 12 ? ty + 1 : ty;
  129. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify((await expectTitle(ny, nm)).toLowerCase())}`, { label: 'next month title' });
  130. check('next shows the next month', true);
  131. await page.click('#month-prev');
  132. await page.waitFor(`document.querySelector("#month-title").textContent === ${JSON.stringify(t0)}`, { label: 'prev month' });
  133. check('prev returns to the month, today marked again', (await ev('document.querySelectorAll("li.today").length')) === 1);
  134. // sync of components.hybriel 4922f9c (SY): prev / next are 44 px targets (the month view's buttons were 36 px high at 1280)
  135. const navBoxes = await ev(`['#month-prev', '#month-next'].map(s => { const r = document.querySelector(s).getBoundingClientRect(); return Math.round(r.width) + 'x' + Math.round(r.height); })`);
  136. check('prev / next are 44 px targets', navBoxes.every(b => b.split('x').every(n => Number(n) >= 44)), JSON.stringify(navBoxes));
  137. // walk to February 2028 (leap year) and check its days and its first weekday (Tuesday)
  138. let guard = 0;
  139. const feb28 = (await expectTitle(2028, 2)).toLowerCase();
  140. while ((await title()).toLowerCase() !== feb28 && guard++ < 40) {
  141. const before = await title();
  142. await page.click('#month-next');
  143. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging' });
  144. }
  145. 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 }; })()`);
  146. check('Feb 2028: 29 days, the 1st is a Tuesday (column 2)', feb.n === 29 && feb.col === 1, JSON.stringify(feb));
  147. // year rollover: go back to December 2027 and January 2028 by prev
  148. await page.click('#month-prev');
  149. await page.click('#month-prev');
  150. const dec27 = (await expectTitle(2027, 12)).toLowerCase();
  151. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify(dec27)}`, { label: 'back to December' });
  152. 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 }))()`);
  153. check('Dec 2027: 31 days, the 1st is a Wednesday', dec.n === 31 && dec.col === 2, JSON.stringify(dec));
  154. check('no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  155. await languagePart();
  156. await shot('wide');
  157. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  158. await sleep(300);
  159. check('no horizontal overflow at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  160. await shot('narrow');
  161. if (!process.env.GATE_SKIP_EVENTS) await eventsPart(page, { alice, bob, APPKEY });
  162. await remindersPart(page, { carol, APPKEY });
  163. }
  164. // ---- ticket calendar#2: login with ident, private events ------------------------------------------------------
  165. async function eventsPart(page, { alice, bob, APPKEY }) {
  166. const ev = (e) => page.evaluate(e);
  167. const J = JSON.stringify;
  168. // (a user's pointer reaches the month view first, and takes a moment before the click: the month view reads the browser then)
  169. const hydrated = async () => {
  170. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  171. const at = await page.evaluate(`(() => { const r = document.querySelector('#month-title').getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);
  172. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: at.x, y: at.y });
  173. await sleep(700);
  174. };
  175. const setField = (sel, v) => ev(`(() => { const e = document.querySelector(${J(sel)}); e.value = ${J(v)}; e.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  176. const pad = (n) => String(n).padStart(2, '0');
  177. const now = new Date();
  178. const ym = `${now.getFullYear()}-${pad(now.getMonth() + 1)}`;
  179. const day = (d) => `${ym}-${pad(d)}`;
  180. const cell = (d) => `#month-days li:has(time[datetime="${day(d)}"])`;
  181. const evTexts = (d) => ev(`[...document.querySelectorAll(${J(cell(d) + ' button.event')})].map(b => b.textContent)`);
  182. const editorOpen = () => ev(`document.querySelector('#eventeditor').classList.contains('open')`);
  183. const emitRaw = async (cookie, event, payload) => {
  184. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event, payload }) });
  185. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  186. return j && j.value !== undefined ? j.value : t;
  187. };
  188. // Log out sits in the theme's user menu (mission 006): a real click on the user icon opens it, then Log out
  189. const logOut = async () => {
  190. await sleep(200);
  191. await page.click('#logout');
  192. };
  193. const loginAs = async (who) => {
  194. const code = await ident.selectorCode(who, APPKEY, BASE);
  195. await page.goto(BASE + '/login/callback?ident_code=' + code);
  196. await page.waitForSelector('#logout');
  197. await hydrated();
  198. };
  199. const cookieOf = async () => (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  200. // signed out: no login, no editor, the faces refuse
  201. await page.goto(BASE + '/');
  202. await hydrated();
  203. check('signed out: the selector stands in the header and NOTHING beside it (no second "Log in with ident" button), no Log out', (await ev(`!!document.querySelector('application-header #selector.out')`)) && !(await ev(`!!document.querySelector('#loginbutton') || !!document.querySelector('a[href*="/login?key="]')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  204. for (const [w, h] of [[390, 844], [1280, 900]]) {
  205. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(300);
  206. check(`IW ${w}px signed out: ident's selector stands visible at the top right of the header`, (await page.evaluate(SELECTOR_IN_HEADER)) === 'ok', await page.evaluate(SELECTOR_IN_HEADER));
  207. }
  208. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true }); await sleep(300);
  209. await page.click(cell(15));
  210. await sleep(500);
  211. check('signed out: clicking a day opens no editor', !(await editorOpen()));
  212. const refused = await emitRaw('', 'calSave', [{ title: 'x', allDay: false, startDate: day(15), startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  213. check('signed out: the server refuses to save an event', refused && refused.error === 'log in with ident first', J(refused));
  214. let r = await fetch(BASE + '/login/callback', { redirect: 'manual' });
  215. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  216. // log in as alice, add an event on the 15th
  217. await loginAs(alice);
  218. check('logged in: "Log out" shows', await ev(`!!document.querySelector('#logout')`));
  219. for (const [w, h] of [[390, 844], [1280, 900]]) {
  220. await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(300);
  221. check(`IW ${w}px signed in: ident's selector stands visible at the top right of the header and shows it is logged in`, (await page.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await page.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await page.evaluate(SELECTOR_IN_HEADER));
  222. check(`IW ${w}px signed in: Log out is reachable (the user menu opens by a real click and shows it, 44 px high, inside the screen)`, await page.evaluate('(() => { const b = document.querySelector("#logout").getBoundingClientRect(); return b.width > 0 && b.height >= 44 && b.bottom <= innerHeight && b.right <= innerWidth; })()'));
  223. }
  224. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true }); await sleep(300);
  225. await page.click(cell(15));
  226. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens' });
  227. await page.waitFor(`document.querySelector('#f-startdate').value === ${J(day(15))}`, { label: 'form shows the clicked date' });
  228. check('a click on a day opens the editor at that date', (await ev(`document.querySelector('#f-startdate').value`)) === day(15), await ev(`JSON.stringify([...document.querySelectorAll('#eventform input, #eventform textarea')].map(i => i.id + '=' + i.value))`));
  229. await page.click('#f-title');
  230. await page.type('#f-title', 'Dentist');
  231. await setField('#f-starttime', '18:00');
  232. await setField('#f-endtime', '19:00');
  233. await setField('#f-place', 'Dr. Huber');
  234. await setField('#f-notes', 'Bring the insurance card');
  235. check('typing into the title kept its focus and text', (await ev(`document.querySelector('#f-title').value`)) === 'Dentist');
  236. await page.click('#event-save');
  237. await page.waitFor(`document.querySelectorAll(${J(cell(15) + ' button.event')}).length === 1`, { label: 'event shows on its day' });
  238. check('the event shows on that day with its time', J(await evTexts(15)) === '["18:00 Dentist"]', J(await evTexts(15)));
  239. check('the editor closed after saving', !(await editorOpen()));
  240. // it survives a reload (server render for the signed-in user)
  241. await page.goto(BASE + '/');
  242. await hydrated();
  243. await page.waitFor(`document.querySelectorAll(${J(cell(15) + ' button.event')}).length === 1`, { label: 'event after reload' });
  244. check('after a reload the event is still there', J(await evTexts(15)) === '["18:00 Dentist"]');
  245. const html = await (await fetch(BASE + '/', { headers: { cookie: await cookieOf() } })).text();
  246. check('the server renders the event into the page for its owner', html.includes('18:00 Dentist'));
  247. check('a visitor without login gets no event in the page', !(await (await fetch(BASE + '/')).text()).includes('Dentist'));
  248. // F2/F3: real Tab/Enter must reach a day's add action and its event chip.
  249. const key = async (key, code) => {
  250. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key, code, text: key === 'Enter' ? '\r' : undefined, windowsVirtualKeyCode: key === 'Tab' ? 9 : 13 });
  251. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code, windowsVirtualKeyCode: key === 'Tab' ? 9 : 13 });
  252. };
  253. const tabTo = async (selector) => {
  254. await page.focus('#settings-open');
  255. for (let i = 0; i < 55; i++) {
  256. await key('Tab', 'Tab');
  257. if (await ev(`document.activeElement.matches(${J(selector)})`)) return true;
  258. }
  259. return false;
  260. };
  261. for (const [width, height] of [[390, 844], [1280, 800]]) {
  262. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  263. await ev('window.scrollTo(0, 0)');
  264. await sleep(300);
  265. const { data } = await page.send('Page.captureScreenshot', { format: 'png' });
  266. writeFileSync(join(SCRATCH, `gate-actions-${width}.png`), Buffer.from(data, 'base64'));
  267. await page.click(cell(14) + ' time');
  268. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`);
  269. check(`${width}px: day click opens an empty editor for its date`, await ev(`document.querySelector('#f-startdate').value === ${J(day(14))} && document.querySelector('#f-title').value === ''`));
  270. await page.click('#event-cancel');
  271. const dayReached = await tabTo(cell(15) + ' button.day-add');
  272. check(`${width}px: Tab reaches the day add button`, dayReached);
  273. if (dayReached) {
  274. await key('Enter', 'Enter');
  275. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`);
  276. check(`${width}px: Enter adds on the focused date, beside an existing chip`, await ev(`document.querySelector('#f-startdate').value === ${J(day(15))} && document.querySelector('#f-title').value === '' && document.querySelector('#formheading').textContent === 'New event'`));
  277. await page.click('#event-cancel');
  278. }
  279. const chipReached = await tabTo(cell(15) + ' button.event');
  280. check(`${width}px: Tab reaches the event chip`, chipReached);
  281. if (chipReached) {
  282. await key('Enter', 'Enter');
  283. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`);
  284. check(`${width}px: Enter opens the focused event editor`, await ev(`document.querySelector('#f-title').value === 'Dentist' && document.querySelector('#formheading').textContent === 'Edit event'`));
  285. await page.click('#event-cancel');
  286. }
  287. }
  288. // edit
  289. const aliceEventId = await ev(`document.querySelector(${J(cell(15) + ' button.event')}).value`);
  290. await page.click(cell(15) + ' button.event');
  291. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens to edit' });
  292. check('a click on an event opens it with its values', (await ev(`[document.querySelector('#f-title').value, document.querySelector('#f-starttime').value, document.querySelector('#f-endtime').value, document.querySelector('#f-place').value, document.querySelector('#f-notes').value].join('|')`)) === 'Dentist|18:00|19:00|Dr. Huber|Bring the insurance card');
  293. await setField('#f-title', 'Dentist (moved)');
  294. await setField('#f-startdate', day(16));
  295. await setField('#f-enddate', day(16));
  296. await page.click('#event-save');
  297. await page.waitFor(`document.querySelectorAll(${J(cell(16) + ' button.event')}).length === 1`, { label: 'event moved' });
  298. check('editing moves and renames the event', J(await evTexts(16)) === '["18:00 Dentist (moved)"]' && (await evTexts(15)).length === 0, J([await evTexts(15), await evTexts(16)]));
  299. // all-day, several days
  300. await page.click(cell(20));
  301. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens (all day)' });
  302. await page.click('#kind-allday');
  303. await page.click('#f-title');
  304. await page.type('#f-title', 'Vacation');
  305. await setField('#f-enddate', day(22));
  306. check('all-day hides the time fields', !(await ev(`(() => { const e = document.querySelector('#f-starttime'); return e.offsetWidth > 0; })()`)));
  307. await page.click('#event-save');
  308. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'three all-day days' });
  309. check('an all-day event of three days shows on each day', J([await evTexts(20), await evTexts(21), await evTexts(22), await evTexts(23)]) === '[["Vacation"],["Vacation"],["Vacation"],[]]');
  310. // validation: the end before the start is refused with a message, nothing changes
  311. await page.click(cell(25));
  312. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens (bad)' });
  313. await page.click('#f-title');
  314. await page.type('#f-title', 'Backwards');
  315. await setField('#f-starttime', '10:00');
  316. await setField('#f-endtime', '09:00');
  317. await page.click('#event-save');
  318. await page.waitFor(`document.querySelector('#formerror').textContent.length > 0`, { label: 'error shows' });
  319. check('an end before the start is refused with a message', (await ev(`document.querySelector('#formerror').textContent`)).includes('before the start') && (await evTexts(25)).length === 0 && (await editorOpen()));
  320. await page.click('#event-cancel');
  321. check('cancel closes the editor', !(await editorOpen()));
  322. // paging loads the events of that month
  323. await page.click('#month-next');
  324. await page.waitFor(`document.querySelector('#month-title').textContent !== ${J(await ev(`document.querySelector('#month-title').textContent`))}`, { label: 'next month' });
  325. await page.click('#month-prev');
  326. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'events back after paging' });
  327. check('paging away and back shows the events again', true);
  328. // private: bob sees nothing of alice's and cannot change or delete them
  329. const aliceCookie = await cookieOf();
  330. await logOut();
  331. await page.waitForSelector('application-header #selector.out');
  332. await sleep(300);
  333. await page.goto(BASE + '/');
  334. await hydrated();
  335. check('after log out no event shows', (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 0);
  336. await loginAs(bob);
  337. await page.goto(BASE + '/');
  338. await hydrated();
  339. await sleep(500);
  340. check("another identity does not see alice's events", (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 0);
  341. const bobCookie = await cookieOf();
  342. const del = await emitRaw(bobCookie, 'calDelete', [aliceEventId, day(1), day(28)]);
  343. check("another identity cannot delete alice's event", del && del.error === 'no such event', J(del));
  344. const chg = await emitRaw(bobCookie, 'calSave', [{ id: aliceEventId, title: 'hacked', allDay: false, startDate: day(16), startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  345. check("another identity cannot change alice's event", chg && chg.error === 'no such event', J(chg));
  346. const rows = await emitRaw(bobCookie, 'calLoad', [day(1), day(28)]);
  347. check('another identity loads no events', rows && Array.isArray(rows.events) && rows.events.length === 0, J(rows));
  348. // validWindow / soonOf are plain (non-static) members of calendar.hl called from server faces (hybriel #115/#116, mission 048)
  349. const badWin = await emitRaw(bobCookie, 'calLoad', ['nope', day(28)]);
  350. check('the server refuses a window that is not two dates', badWin && badWin.error === 'not a date', J(badWin));
  351. const bad = await emitRaw(bobCookie, 'calSave', [{ title: '', allDay: false, startDate: 'nope', startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  352. check('the server validates an event strictly', bad && typeof bad.error === 'string' && bad.error.length > 0, J(bad));
  353. // alice again: her events are all there; delete one
  354. await logOut();
  355. await page.waitForSelector('application-header #selector.out');
  356. await sleep(300);
  357. await loginAs(alice);
  358. await page.goto(BASE + '/');
  359. await hydrated();
  360. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'alice events back' });
  361. check('logging in again shows her events', J(await evTexts(16)) === '["18:00 Dentist (moved)"]');
  362. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, 'gate-events-wide.png'), Buffer.from(data, 'base64')); }
  363. await page.click(cell(16) + ' button.event');
  364. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens to delete' });
  365. await page.click('#event-delete');
  366. await page.waitFor(`document.querySelectorAll(${J(cell(16) + ' button.event')}).length === 0`, { label: 'event deleted' });
  367. check('delete removes the event', (await evTexts(16)).length === 0 && !(await editorOpen()) && (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 3);
  368. await page.goto(BASE + '/');
  369. await hydrated();
  370. await sleep(500);
  371. check('the deleted event stays gone after a reload', (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 3);
  372. // SIGNED IN, with events: the first pointer event over the month view must not send calLoad again (mission 006 race: the browser's
  373. // read of its today re-ran show(), whose calLoad answer landed late and put the month back after the user had paged on).
  374. // Seen on the wire (captured frames): 3c5604f sends one more calLoad per first pointer event, this fork none. Then the month
  375. // the user paged to must stay: the next month, with the server's answers held back 1.2 s by the page's own socket wrapper.
  376. await page.captureWs();
  377. await page.goto(BASE + '/');
  378. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated (race check)' });
  379. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 3`, { label: 'events on the signed-in page (race check)' });
  380. await sleep(1500); // everything the page does on its own has settled
  381. // the server draws its UTC day as today; the browser's first pointer event repaints the month for ITS today when that differs
  382. // (00:00–02:00 CEST: UTC is still yesterday) — one more calLoad then is the repaint, not the race this check is about
  383. const dayDiffers = await ev(`(() => { const t = document.querySelector('li.today time'); const n = new Date(), p = x => String(x).padStart(2, '0'); return !t || t.getAttribute('datetime') !== n.getFullYear() + '-' + p(n.getMonth() + 1) + '-' + p(n.getDate()); })()`);
  384. const loadsBefore = (await page.wsSent()).filter(f => f.includes('calLoad')).length;
  385. const titleBefore = await ev('document.querySelector("#month-title").textContent');
  386. await ev(`window.__titles = []; new MutationObserver(() => window.__titles.push(document.querySelector('#month-title').textContent)).observe(document.querySelector('#month-title'), { subtree: true, childList: true, characterData: true })`);
  387. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 400, y: 300 });
  388. await page.click('#month-next');
  389. await page.waitFor(`document.querySelector("#month-title").textContent !== ${J(titleBefore)}`, { label: 'next month (race check)' });
  390. const pagedTitle = await ev('document.querySelector("#month-title").textContent');
  391. await sleep(2500); // a late answer of a re-run show() would land here
  392. const loadsAfter = (await page.wsSent()).filter(f => f.includes('calLoad')).length;
  393. const titleAfter = await ev('document.querySelector("#month-title").textContent');
  394. check('signed in: the first pointer event runs no calLoad of its own (only the paging one)', loadsAfter - loadsBefore === (dayDiffers ? 2 : 1), (dayDiffers ? '(server day ≠ browser day) ' : '') + 'calLoad frames sent: ' + (loadsAfter - loadsBefore));
  395. const seen = await ev('window.__titles');
  396. check('signed in: the month the user paged to stays after the late answer (the title never goes back)', titleAfter === pagedTitle && titleAfter !== titleBefore && seen.lastIndexOf(titleBefore) < seen.indexOf(pagedTitle), J([titleBefore, pagedTitle, titleAfter, seen]));
  397. await page.click('#month-prev');
  398. await page.waitFor(`document.querySelector("#month-title").textContent === ${J(titleBefore)}`, { label: 'back to this month (race check)' });
  399. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  400. await sleep(300);
  401. // C13: the month view is the month header, the weekday row and the day grid — no notification / reminder controls between them
  402. // (caramboleyo: "putting buttons somewhere unrelated into the interface"); they live in the reminder settings dialog (user menu)
  403. 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);
  404. const h = mv.querySelector('header').getBoundingClientRect(), g = document.querySelector('#month-days').getBoundingClientRect(), w = document.querySelector('#month-weekdays').getBoundingClientRect();
  405. return { tags: shown.map(e => e.tagName.toLowerCase() + (e.id ? '#' + e.id : '')), gridGap: Math.round(g.top - h.bottom), weekdaysGap: Math.round(w.top - h.bottom), buttons: [...mv.querySelectorAll('button')].filter(b => !b.closest('event-editor') && !b.closest('#month-days') && b.getBoundingClientRect().height > 0).map(b => b.id || b.textContent) }; })()`);
  406. check('month view at 390 px: only the month header, the weekday row and the day grid', J(flow.tags) === '["header","ol#month-weekdays","ol#month-days"]' && flow.buttons.length === 3 && flow.buttons.every(b => /^(month-(prev|next)|settings-open)$/.test(b)), J(flow));
  407. check('month view at 390 px: the grid starts within 80 px of the month header (the reminder bar used to push it ~330 px down)', flow.gridGap <= 80, J(flow));
  408. // calendar#14: at 390 px the month name and the Reminder settings button did not fit one row, so the name broke into two lines
  409. // ("Oktobe / r 2026"). The name stays on one line, every header control is on screen at once, and nothing overlaps.
  410. const head = await ev(`(() => { const t = document.querySelector('#month-title'), r = t.getBoundingClientRect(), fs = parseFloat(getComputedStyle(t).fontSize);
  411. const boxes = [...document.querySelectorAll('#month-prev, #month-title, #month-next, #settings-open')].map(e => { const b = e.getBoundingClientRect(); return { id: e.id, l: Math.round(b.left), r: Math.round(b.right), t: Math.round(b.top), b: Math.round(b.bottom) }; });
  412. const overlap = boxes.some((a, i) => boxes.some((c, j) => j > i && a.l < c.r - 1 && c.l < a.r - 1 && a.t < c.b - 1 && c.t < a.b - 1));
  413. return { oneLine: r.height <= fs * 1.8, titleLines: Math.round(r.height / fs * 10) / 10, overlap, inside: boxes.every(b => b.l >= 0 && b.r <= innerWidth), shown: boxes.length === 4, boxes }; })()`);
  414. check('month view at 390 px: the month name stays on one line (it broke into "Oktobe / r 2026")', head.oneLine, J(head));
  415. check('month view at 390 px: prev, month name, next and Reminder settings are all on screen at once and none overlaps another', head.shown && head.inside && !head.overlap, J(head));
  416. await page.click(cell(9));
  417. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens on a phone' });
  418. await sleep(200);
  419. const { data } = await page.send('Page.captureScreenshot', { format: 'png' });
  420. writeFileSync(join(SCRATCH, 'gate-editor-narrow.png'), Buffer.from(data, 'base64'));
  421. check('the editor fits a phone (no horizontal overflow)', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  422. // THE INSTALLABLE APP (ticket #3): manifest (served as manifest JSON, installable fields), icons, link, theme colour
  423. const mhref = await (async () => { const h = await (await fetch(BASE + '/')).text(); const m = h.match(/<link rel="manifest" href="([^"]+)"/); return m ? m[1] : null; })();
  424. check('the page head links the manifest', !!mhref, String(mhref));
  425. const mres = await fetch(BASE + (mhref || '/manifest.webmanifest'));
  426. const man = await mres.json();
  427. check('manifest is served as a web manifest with start_url, standalone display, name', /manifest\+json/.test(mres.headers.get('content-type') || '') && man.start_url === '/' && man.display === 'standalone' && !!man.name);
  428. const sizes = [];
  429. for (const ic of man.icons) { const r = await fetch(BASE + ic.src); const b = Buffer.from(await r.arrayBuffer()); sizes.push(r.ok && ic.type === 'image/png' && b.readUInt32BE(16) === Number(ic.sizes.split('x')[0])); }
  430. check('every icon of the manifest is a real PNG of its declared size (192 and 512, any and maskable)', sizes.length === 4 && sizes.every(Boolean) && man.icons.some(i => i.sizes === '512x512' && i.purpose === 'maskable'));
  431. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  432. await page.goto(BASE + '/');
  433. await hydrated();
  434. // installable: Chrome finds the manifest, and hl:web's own service worker (offline = [ Calendar ]) is registered
  435. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && (r.active || r.installing || r.waiting)))`, { label: 'service worker registered' }).catch(() => {});
  436. await sleep(1500);
  437. const inst = await page.send('Page.getInstallabilityErrors');
  438. check('Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  439. check('a service worker is registered for the whole app', await ev(`navigator.serviceWorker.getRegistration().then(r => !!r && new URL(r.scope).pathname === '/')`));
  440. check('the page carries the theme colour', (await ev(`document.querySelector('meta[name="theme-color"]').getAttribute('content')`)) === 'rgb(15, 20, 25)'); // mission 006: the header colour (tokens darker), was #191e23
  441. check('no console errors during the event steps', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  442. }
  443. // ---- calendar#6 through hybriel #105: the page reads `headers['accept-language']` (no framework patch) ------------------
  444. // A fresh tab per language; its Accept-Language is set by CDP and the BROWSER's own language (Intl locale and
  445. // navigator.language) is set to the OTHER one, so
  446. // the names can only come from the request header. First page (no pointer yet), then two pages forward and one back
  447. // with a real pointer: the names stay in the header's language.
  448. async function languagePart() {
  449. const NAMES = {
  450. de: { months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], days: 'Mo Di Mi Do Fr Sa So' },
  451. en: { months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], days: 'Mon Tue Wed Thu Fri Sat Sun' },
  452. };
  453. for (const [lang, header, other] of [['de', 'de-DE,de;q=0.9,en;q=0.8', 'en-US'], ['en', 'en-US,en;q=0.9,de;q=0.8', 'de-DE']]) {
  454. const p = await browser.newPage();
  455. try {
  456. if (CLOCK_SHIFT) await p.addInitScript(CLOCK_SCRIPT);
  457. await p.send('Network.enable');
  458. await p.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': header } });
  459. await p.send('Emulation.setLocaleOverride', { locale: other });
  460. // navigator.language follows the machine (German on Loreana), not the override: pin it to the other language too
  461. await p.addInitScript(`Object.defineProperty(Navigator.prototype, 'language', { get: () => ${JSON.stringify(other)} }); Object.defineProperty(Navigator.prototype, 'languages', { get: () => [${JSON.stringify(other)}] });`);
  462. await p.goto(BASE + '/', { timeout: 45000 });
  463. await p.waitForSelector('#month-title');
  464. await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated (' + lang + ')' });
  465. const t = NAMES[lang];
  466. const seen = async () => ({ title: await p.evaluate('document.querySelector("#month-title").textContent'), days: await p.evaluate('[...document.querySelectorAll("#month-weekdays li")].map(l => l.textContent).join(" ")') });
  467. const monthOf = (title) => t.months.indexOf(title.replace(/ \d{4}$/, ''));
  468. const first = await seen();
  469. const m0 = monthOf(first.title);
  470. const own = await p.evaluate('navigator.language + " / Intl " + Intl.DateTimeFormat().resolvedOptions().locale');
  471. check(`language ${lang}: first page (browser itself: ${own}) has ${lang} names`, m0 >= 0 && first.days === t.days && !own.startsWith(lang) && own.endsWith('Intl ' + other), JSON.stringify(first) + ' ' + own);
  472. // the server's own document (before any script): the names are in it
  473. const html = await (await fetch(BASE + '/', { headers: { 'accept-language': header } })).text();
  474. const days = [...html.matchAll(/<li>([^<]*)<\/li>/g)].map(x => x[1]).slice(0, 7).join(' ');
  475. check(`language ${lang}: the server's HTML for Accept-Language ${header} carries ${lang} weekday names`, days === t.days, days);
  476. const steps = [['#month-next', 1], ['#month-next', 2], ['#month-prev', 1]];
  477. let ok = true, trail = [];
  478. for (const [btn, off] of steps) {
  479. const before = (await seen()).title;
  480. await p.click(btn); // a real pointer: the browser's own language would be read now if the server had not known one
  481. await p.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging ' + lang });
  482. const now = await seen();
  483. trail.push(now.title + ' / ' + now.days);
  484. if (monthOf(now.title) !== (m0 + off) % 12 || now.days !== t.days) ok = false;
  485. }
  486. check(`language ${lang}: after paging (next, next, prev) the names are still ${lang}`, ok, trail.join(' | '));
  487. } finally { await p.close(); }
  488. }
  489. }
  490. // ---- ticket calendar#4: reminders and notifications, also offline -------------------------------------------------
  491. async function remindersPart(page, { carol, APPKEY }) {
  492. const ev = (e) => page.evaluate(e);
  493. const J = JSON.stringify;
  494. const pad = (n) => String(n).padStart(2, '0');
  495. const hydrated = async () => {
  496. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  497. const at = await page.evaluate(`(() => { const r = document.querySelector('#month-title').getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);
  498. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: at.x, y: at.y });
  499. await sleep(700);
  500. };
  501. const setField = (sel, v, type = 'input') => ev(`(() => { const e = document.querySelector(${J(sel)}); e.value = ${J(v)}; e.dispatchEvent(new Event(${J(type)}, { bubbles: true })); })()`);
  502. const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  503. const timeOf = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
  504. const shown = () => ev(`document.querySelector('#notify-planned').textContent`);
  505. const notices = () => ev(`navigator.serviceWorker.getRegistration().then(r => r.getNotifications()).then(l => l.map(n => n.title + '|' + n.body))`);
  506. const cell = (d) => `#month-days li:has(time[datetime="${dateOf(d)}"])`;
  507. const openEditorOn = async (start) => {
  508. await page.click(cell(start) + ' time'); // the day number: an event chip in the middle would edit that event
  509. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens' });
  510. await setField('#f-startdate', dateOf(start));
  511. await setField('#f-starttime', timeOf(start));
  512. await setField('#f-enddate', '');
  513. await setField('#f-endtime', '');
  514. const t = await ev(`document.querySelector('#f-title').value`);
  515. check('a new event starts with an empty title', t === '', J(t));
  516. };
  517. const addEvent = async (name, start, own) => {
  518. await openEditorOn(start);
  519. await setField('#f-title', name);
  520. if (own) {
  521. await page.click('#rem-own');
  522. await ev(`document.querySelectorAll('#rem-rows reminder-row button').forEach((b, i) => { if (i > 0) b.click(); })`);
  523. await sleep(300);
  524. await setField('#rem-rows reminder-row select', 'minutes', 'change');
  525. await setField('#rem-rows reminder-row input[type=number]', String(own), 'change');
  526. }
  527. await page.click('#event-save');
  528. await page.waitFor(`!document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor closed after save', timeout: 15000 });
  529. };
  530. const wanted = async (titles, ms) => {
  531. const t0 = Date.now(); let got = [];
  532. while (Date.now() - t0 < ms) { got = await notices(); if (titles.every(t => got.some(g => g.startsWith(t + '|')))) return got; await sleep(2000); }
  533. return got;
  534. };
  535. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] });
  536. const code = await ident.selectorCode(carol, APPKEY, BASE);
  537. await page.goto(BASE + '/login/callback?ident_code=' + code);
  538. await page.waitForSelector('#logout');
  539. await hydrated();
  540. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 30000 });
  541. check('reminders: notifications are allowed, so no "Turn on notifications" button', await ev(`document.querySelector('#notify-ask').classList.contains('hidden')`) && await ev(`document.querySelector('#notify-blocked').classList.contains('hidden')`));
  542. // THE CALENDAR SETTINGS: the defaults are 1 hour before and the day before at 20:00
  543. await sleep(500); await page.click('#settings-open');
  544. await page.waitFor(`document.querySelector('#settingseditor').matches(':popover-open') && document.querySelectorAll('#set-rows reminder-row').length === 2`, { label: 'settings open with two rows' });
  545. const rowsOf = (sel) => ev(`[...document.querySelectorAll(${J(sel + ' reminder-row')})].map(r => [r.querySelector('input[type=number]').value, r.querySelector('select').value, r.querySelector('input[type=time]').value].join(' '))`);
  546. const first = await rowsOf('#set-rows');
  547. check('settings: the default reminders are 1 hour before and the day before at 20:00', first[0] === '1 hours 09:00' && first[1] === '1 days 20:00', J(first));
  548. // calendar#11: at 390 px the dialog's rows are readable — one row per reminder (the rows do not share a line), every select
  549. // and field wide enough to read ("days before, at" needs ~150 px), 44 px taps, inside the panel, nothing overlapping
  550. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  551. await sleep(400);
  552. const rowGeom = (sel) => ev(`(() => { const f = document.querySelector(${J(sel)}).closest('form').getBoundingClientRect();
  553. const rows = [...document.querySelectorAll(${J(sel + ' reminder-row')})].map(r => { const b = r.getBoundingClientRect();
  554. const kids = [...r.querySelectorAll('input,select,button')].filter(e => e.offsetParent).map(e => { const c = e.getBoundingClientRect(); return { tag: e.tagName.toLowerCase() + ':' + (e.type || ''), x: c.x, y: c.y, w: c.width, h: c.height, r: c.right, b: c.bottom }; });
  555. return { x: b.x, y: b.y, r: b.right, b: b.bottom, kids }; });
  556. return { form: { x: f.x, r: f.right }, rows }; })()`);
  557. const rowsProblem = (g) => {
  558. const bad = [];
  559. g.rows.forEach((r, i) => {
  560. if (i && r.y < g.rows[i - 1].b - 0.5) bad.push('row ' + i + ' overlaps the row above');
  561. if (r.x < g.form.x - 0.5 || r.r > g.form.r + 0.5) bad.push('row ' + i + ' outside the panel');
  562. r.kids.forEach((k, j) => {
  563. if (k.h < 43.5 || k.w < 43.5) bad.push('row ' + i + ' ' + k.tag + ' ' + Math.round(k.w) + '×' + Math.round(k.h) + ' under a 44 px tap');
  564. if (k.tag === 'select:select-one' && k.w < 150) bad.push('row ' + i + ' select only ' + Math.round(k.w) + ' px wide');
  565. if (k.tag === 'input:time' && k.w < 100) bad.push('row ' + i + ' time only ' + Math.round(k.w) + ' px wide');
  566. if (k.r > r.r + 0.5 || k.x < r.x - 0.5) bad.push('row ' + i + ' ' + k.tag + ' clipped by its row');
  567. r.kids.slice(j + 1).forEach(o => { if (k.x < o.r - 0.5 && o.x < k.r - 0.5 && k.y < o.b - 0.5 && o.y < k.b - 0.5) bad.push('row ' + i + ' ' + k.tag + ' overlaps ' + o.tag); });
  568. });
  569. });
  570. return bad;
  571. };
  572. const gs = await rowGeom('#set-rows');
  573. check('settings at 390 px: two reminder rows, one under the other, the rows span the panel (calendar#11)', gs.rows.length === 2 && gs.rows[1].y > gs.rows[0].b - 0.5 && gs.rows.every(r => r.r - r.x > 250), J(gs.rows.map(r => [r.x, r.y, r.r, r.b].map(Math.round))));
  574. check('settings at 390 px: selects at least 150 px wide, fields and × 44 px taps, nothing overlapping or clipped', rowsProblem(gs).length === 0, J(rowsProblem(gs)) + ' ' + J(gs.rows));
  575. await page.click('#set-cancel');
  576. // the event editor's own reminders use the same rows (they stood in the same narrow columns)
  577. await page.click('#month-days li:nth-child(20)');
  578. await page.waitFor(`document.querySelector('#rem-own')`, { label: 'editor for the 390 px rows' });
  579. await page.click('#rem-own');
  580. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length >= 1`, { label: 'own rows' });
  581. await page.click('#rem-add'); await sleep(300);
  582. const ge = await rowGeom('#rem-rows');
  583. check('event editor at 390 px: own reminder rows readable too (one per line, selects ≥ 150 px, 44 px taps)', ge.rows.length >= 2 && ge.rows[1].y > ge.rows[0].b - 0.5 && rowsProblem(ge).length === 0, J(rowsProblem(ge)) + ' ' + J(ge.rows));
  584. await page.click('#event-cancel');
  585. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  586. await sleep(300);
  587. // THE TICKET'S FIRST TEST: an event 70 minutes from now — with the defaults, one reminder (1 hour before) is planned
  588. const in70 = new Date(Date.now() + 70 * 60000);
  589. await addEvent('Bus to the lake', in70);
  590. const dayBefore = new Date(in70.getFullYear(), in70.getMonth(), in70.getDate() - 1, 20, 0, 0).getTime() > Date.now() ? 1 : 0;
  591. await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { label: 'reminders planned' });
  592. const want = 1 + dayBefore;
  593. check('an event 70 minutes ahead gets the default reminders planned', (await shown()) === (want === 1 ? '1 reminder set for the next 7 days' : want + ' reminders set for the next 7 days'), await shown());
  594. // an event in another time zone: 30 minutes ahead in Tokyo → its 1-hour reminder is already past, whatever this browser's zone
  595. const tokyo = (t) => new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Tokyo', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(t).replace(' ', 'T');
  596. const browserZone = await ev('Intl.DateTimeFormat().resolvedOptions().timeZone');
  597. const tk = tokyo(new Date(Date.now() + 30 * 60000));
  598. const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  599. const win = [dateOf(new Date(Date.now() - 86400000)), dateOf(new Date(Date.now() + 86400000 * 5))];
  600. const emitRaw = async (event, payload) => {
  601. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event, payload }) });
  602. const j = JSON.parse(await r.text()); return j.value;
  603. };
  604. if (browserZone !== 'Asia/Tokyo') { // (its day-before reminder, at 20:00 the Tokyo day before, is always past too)
  605. const saved = await emitRaw('calSave', [{ title: 'Tokyo call', allDay: false, startDate: tk.slice(0, 10), startTime: tk.slice(11, 16), endDate: '', endTime: '', place: '', notes: '', zone: 'Asia/Tokyo', custom: false, reminders: [] }, win[0], win[1]]);
  606. await page.goto(BASE + '/');
  607. await hydrated();
  608. await sleep(500);
  609. check('a time zone is honoured: 30 minutes ahead in Tokyo has no 1-hour reminder left', (await shown()) === (want === 1 ? '1 reminder set for the next 7 days' : want + ' reminders set for the next 7 days') && !saved.error, (await shown()) + ' ' + J(saved && saved.error));
  610. } else { console.log('skip Tokyo zone check (browser in Tokyo)'); }
  611. // OWN REMINDERS: switch to "Own", the calendar's two rows are the start; drop one; it is kept
  612. const later = new Date(Date.now() + 5 * 3600000);
  613. await openEditorOn(later);
  614. await setField('#f-title', 'Own reminders');
  615. check('the editor offers "Calendar\'s" reminders first, in words', (await ev(`document.querySelector('#rem-default-text').textContent`)) === '1 hour before, the day before at 20:00');
  616. await page.click('#rem-own');
  617. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 2`, { label: 'own rows start from the calendar\'s' });
  618. await page.click('#rem-add');
  619. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 3`, { label: 'row added' });
  620. await setField('#rem-rows reminder-row:nth-child(3) input[type=number]', '15', 'change');
  621. await ev(`document.querySelector('#rem-rows reminder-row:nth-child(2) button').click()`);
  622. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 2`, { label: 'row removed' });
  623. const own = await rowsOf('#rem-rows');
  624. check('own reminders: add, change and remove a row', own[0] === '1 hours 09:00' && own[1] === '15 minutes 09:00', J(own));
  625. await page.click('#event-save');
  626. await page.waitFor(`!document.querySelector('#eventeditor').classList.contains('open')`, { label: 'saved' });
  627. await page.goto(BASE + '/');
  628. await hydrated();
  629. await page.click(`${cell(later)} button.event:last-child`).catch(() => {});
  630. await sleep(300);
  631. const evList = await emitRaw('calLoad', [win[0], win[1]]);
  632. const stored = (evList.events || []).find(e => e.title === 'Own reminders');
  633. check('the server keeps the own reminders as WorldAPI $reminders rows', stored && stored.custom === true && stored.rows.length === 2 && stored.rows[1].unit === 'minutes' && stored.rows[1].n === '15', J(stored));
  634. const plain = (evList.events || []).find(e => e.title === 'Bus to the lake');
  635. check('an event without its own reminders inherits (custom = false)', plain && plain.custom === false, J(evList.events));
  636. check('calLoad answers the soon list (soonOf, a plain member called from a face)', Array.isArray(evList.soon) && evList.soon.length > 0, J(evList.soon));
  637. const bad = await emitRaw('calSave', [{ title: 'x', allDay: false, startDate: dateOf(later), startTime: '10:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC', custom: true, reminders: [{ unit: 'minutes', n: '-5', time: '' }] }, win[0], win[1]]);
  638. check('a bad reminder is refused by the server', bad && bad.error, J(bad));
  639. const badSet = await emitRaw('calSettingsSave', [[{ unit: 'weeks', n: '1', time: '' }]]);
  640. check('bad default reminders are refused', badSet && badSet.error, J(badSet));
  641. // SETTINGS SAVED: only "1 minute before"
  642. await page.goto(BASE + '/');
  643. await hydrated();
  644. await sleep(500); await page.click('#settings-open');
  645. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 2`, { label: 'settings rows' });
  646. await ev(`document.querySelector('#set-rows reminder-row:nth-child(2) button').click()`);
  647. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 1`, { label: 'one row' });
  648. await setField('#set-rows reminder-row select', 'minutes', 'change');
  649. await setField('#set-rows reminder-row input[type=number]', '1', 'change');
  650. await page.click('#set-save');
  651. await page.waitFor(`!document.querySelector('#settingseditor').matches(':popover-open')`, { label: 'settings saved' });
  652. await page.goto(BASE + '/');
  653. await hydrated();
  654. await sleep(500); await page.click('#settings-open');
  655. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 1`, { label: 'settings reload' });
  656. check('settings are kept: 1 minute before', J(await rowsOf('#set-rows')) === '["1 minutes 09:00"]', J(await rowsOf('#set-rows')));
  657. await page.click('#set-cancel');
  658. // NOTIFICATIONS ON TIME: A inherits (1 minute before the start), B has its own (2 minutes before)
  659. await addEvent('Inherits the default', new Date(Date.now() + 3 * 60000));
  660. await addEvent('Has its own reminder', new Date(Date.now() + 4 * 60000), 2);
  661. check('reminders are planned for both', Number((await shown()).split(' ')[0]) >= 4, await shown());
  662. const got = await wanted(['Inherits the default', 'Has its own reminder'], 240000);
  663. check('the notifications came on time, the default one saying "Starts in 1 minute"', got.includes('Inherits the default|Starts in 1 minute') && got.some(g => g.startsWith('Has its own reminder|Starts in 2 minutes')), J(got));
  664. // OFFLINE: the server is gone; an event with a reminder is added anyway and its notification still comes
  665. server.kill('SIGTERM');
  666. await new Promise(r => { server.once('exit', r); setTimeout(r, 3000); });
  667. await page.waitFor(`window.__hl.socket == null || window.__hl.socket.readyState !== 1`, { label: 'socket closed', timeout: 20000 });
  668. // the count only holds reminders still to come (the ones that fired are gone once the page counts again): the three
  669. // still waiting (Bus to the lake, the two of Own reminders) plus the new one; that it FIRES is the next check
  670. await addEvent('Added offline', new Date(Date.now() + 3 * 60000));
  671. check('offline: the event shows on its day and its reminder is planned', Number((await shown()).split(' ')[0]) >= 4, await shown());
  672. const got2 = await wanted(['Added offline'], 200000);
  673. check('offline: the notification still comes', got2.some(g => g.startsWith('Added offline|Starts in 1 minute')), J(got2));
  674. // back online: the queued save reaches the server
  675. spawnServer();
  676. let saved = false;
  677. for (let i = 0; i < 60 && !saved; i++) {
  678. await sleep(1500);
  679. try { const l = await emitRaw('calLoad', [win[0], win[1]]); saved = (l.events || []).some(e => e.title === 'Added offline'); } catch {}
  680. }
  681. check('back online: the event saved while offline reaches the server', saved);
  682. check('no console errors in the reminder steps', page.problems().filter(m => !/favicon|Failed to load resource|WebSocket|ERR_|calSave did not reach/.test(m.text)).length === 0, page.dumpConsole());
  683. }
  684. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  685. if (failures) console.log('---- server log (tail)\n' + log.slice(-3000) + (lastPage ? '\n---- browser console\n' + lastPage.dumpConsole() : ''));
  686. await stop();
  687. if (CLOCK_SHIFT) console.log('clock: GATE_CLOCK ' + process.env.GATE_CLOCK + ' (shift ' + Math.round(CLOCK_SHIFT / 60000) + ' min), now ' + new Date().toString());
  688. console.log(`${passes} passed, ${failures} failed`);
  689. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 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
  • 5d8579d7README: login.js stays by caramboleyo's explicit rulemre
  • cc759328Merge sb3-standby: calendar deploys through its standbymre
  • f2fcdc6dcalendar: a standby container (port 45015, profile standby, reminder clock off) and a /health page; deploy hands over through standby-swap.sh without a gapmre