winzik/tools/webshot/livecheck.cjs
David Nurdin 23966a2d07 Web sites: reliable live reload between the browser and the IDE
The reload container (docker/web-dev/live.js, browser-sync) now publishes the site's port itself, so the page's socket can connect
(the old proxy ws option moved it to an unpublished port: the tab never followed). The IDE tells it each saved file (POST /__jumphp/notify),
so it works without file events (Docker Desktop also polls); CSS is injected without a reload, anything else reloads once.
Status bar item Live: N (browser tabs connected), open the site at the live-reload address, turn it off ('live': 'off' in web.json).
bin/jumphp web:live, LiveReload (IDE) + tests, end-to-end test with headless Chrome on a Symfony site, docs, 14 languages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-16 10:31:20 +01:00

78 lines
4.7 KiB
JavaScript

// Headless Chrome check of a site's live reload (tools/tests/live-reload.test.sh), what the IDE's save does:
// node livecheck.cjs <live-reload url> <site folder> [notify|watch]
// Opens the page, then edits files of the site and checks what the tab does:
// - a CSS rule changes: the computed style changes WITHOUT a reload (a mark set on the window survives, the scroll stays),
// - a Twig template changes: the page reloads with the new text,
// - a controller changes: the page reloads with the new text.
// "notify": each edit is followed by the IDE's notice (POST /__jumphp/notify, like ide/src/Web/LiveReload.php);
// "watch": the edits only (the watcher in the container sees them).
const puppeteer = require('puppeteer');
const fs = require('fs');
const http = require('http');
const [url, site, mode = 'notify'] = process.argv.slice(2);
const base = new URL(url);
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const post = (files) => new Promise((resolve, reject) => {
const body = JSON.stringify({ files });
const req = http.request({ host: base.hostname, port: base.port, path: '/__jumphp/notify', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } },
(res) => { let t = ''; res.on('data', (c) => { t += c; }); res.on('end', () => resolve(t)); });
req.on('error', reject); req.end(body);
});
const get = (path) => new Promise((resolve, reject) => {
http.get({ host: base.hostname, port: base.port, path }, (res) => { let t = ''; res.on('data', (c) => { t += c; }); res.on('end', () => resolve(JSON.parse(t))); }).on('error', reject);
});
const edit = async (file, from, to) => {
const p = `${site}/${file}`;
const text = fs.readFileSync(p, 'utf8');
if (!text.includes(from)) throw new Error(`${file}: "${from}" not found`);
fs.writeFileSync(p, text.replace(from, to));
if (mode === 'notify') await post([file]);
};
const until = async (fn, what, ms = 15000) => {
const t = Date.now();
while (Date.now() - t < ms) { try { if (await fn()) return Date.now() - t; } catch (e) { /* navigating */ } await sleep(100); }
throw new Error(`timeout: ${what}`);
};
(async () => {
const results = [];
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'ok ' : 'FAIL'} ${name}${detail ? ' (' + detail + ')' : ''}`); };
const browser = await puppeteer.launch({ headless: 'new', args: ['--no-sandbox'] });
try {
const page = await browser.newPage();
await page.setViewport({ width: 900, height: 600 });
await page.goto(url, { waitUntil: 'networkidle0' });
await page.evaluate(() => { window.scrollTo(0, 400); window.__mark = 'kept'; });
await until(async () => (await get('/__jumphp/status')).clients >= 1, 'the tab connects to the live reload');
const status = await get('/__jumphp/status');
check('the tab is counted by the live reload', status.clients >= 1, `clients=${status.clients}`);
const colour = () => page.evaluate(() => getComputedStyle(document.querySelector('h1')).color);
check('initial style is red', (await colour()) === 'rgb(255, 0, 0)');
// CSS: injected, no reload
await edit('public/css/app.css', 'rgb(255, 0, 0)', 'rgb(0, 0, 255)');
const t1 = await until(async () => (await colour()) === 'rgb(0, 0, 255)', 'the CSS rule is injected');
const kept = await page.evaluate(() => ({ mark: window.__mark, y: Math.round(window.scrollY) }));
check('CSS change applied without a reload', kept.mark === 'kept', `${t1} ms`);
check('scroll kept', kept.y === 400, `y=${kept.y}`);
// Twig: reload
await edit('templates/home.html.twig', 'template-v1', 'template-v2');
const t2 = await until(async () => (await page.$eval('#t', (e) => e.textContent)) === 'template-v2', 'the Twig change reloads the page');
check('Twig change reloads the page with the new text', (await page.evaluate(() => window.__mark)) === undefined, `${t2} ms`);
// PHP controller: reload
await edit('src/Controller/HomeController.php', 'controller-v1', 'controller-v2');
const t3 = await until(async () => (await page.$eval('#w', (e) => e.textContent)) === 'controller-v2', 'the controller change reloads the page');
check('controller change reloads the page with the new text', true, `${t3} ms`);
const after = await get('/__jumphp/status');
check('one injection, one reload per edit (no double reload)', mode === 'notify' ? after.injects === 1 && after.reloads === 2 : after.injects >= 1 && after.reloads >= 2, `injects=${after.injects} reloads=${after.reloads}`);
} catch (e) {
console.log('FAIL ' + e.message);
results.push(false);
}
await browser.close();
process.exit(results.length && results.every(Boolean) ? 0 : 1);
})();