- vite-plugin-pwa: манифест, иконки, app shell в precache, автообновление - статьи и картинки кешируются при открытии (stale-while-revalidate) - «Скачать раздел для офлайна» с прогрессом, экран «Офлайн-разделы» - баннер «Нет сети: показана сохранённая версия от …», метка «Офлайн» у статьи - scripts/check-offline.mjs: проверка в режиме без сети Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
89 lines
4.8 KiB
JavaScript
89 lines
4.8 KiB
JavaScript
// Проверка офлайна: открываем сайт, скачиваем раздел, отключаем сеть и убеждаемся,
|
|
// что главная, шпаргалка, открытая и скачанная статьи показываются вместе с картинками.
|
|
// Запуск: node scripts/check-offline.mjs [адрес сайта]. KB_EMAIL / KB_PASSWORD: вход.
|
|
import { chromium } from 'playwright-core';
|
|
|
|
const base = process.argv[2] ?? 'http://localhost:8200';
|
|
const shot = process.argv[3];
|
|
const browser = await chromium.launch({ channel: 'chrome' });
|
|
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true });
|
|
const page = await ctx.newPage();
|
|
let failed = 0;
|
|
const check = (ok, text) => {
|
|
if (!ok) failed++;
|
|
console.log(`${ok ? 'ok ' : 'FAIL'} ${text}`);
|
|
};
|
|
|
|
if (process.env.KB_EMAIL) {
|
|
const res = await page.request.post(`${base}/api/auth/login`, {
|
|
headers: { 'X-Requested-With': 'kb' },
|
|
data: { email: process.env.KB_EMAIL, password: process.env.KB_PASSWORD, remember: true },
|
|
});
|
|
if (!res.ok()) throw new Error(`Не удалось войти: ${res.status()}`);
|
|
}
|
|
|
|
// 1. Онлайн: первая загрузка ставит service worker
|
|
await page.goto(base + '/', { waitUntil: 'networkidle' });
|
|
await page.evaluate(() => navigator.serviceWorker.ready);
|
|
await page.reload({ waitUntil: 'networkidle' }); // теперь страницей управляет service worker
|
|
await page.waitForSelector('.cheat-card');
|
|
|
|
// 2. Открываем одну статью (должна закешироваться сама) и шпаргалку
|
|
await page.goto(base + '/a/stoyka-vezda-silovoe', { waitUntil: 'networkidle' });
|
|
await page.waitForSelector('.kb-body');
|
|
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
|
|
await page.waitForTimeout(1500);
|
|
await page.goto(base + '/cheatsheet', { waitUntil: 'networkidle' });
|
|
|
|
// 3. Скачиваем раздел «Оптика» кнопкой
|
|
await page.goto(base + '/s/optika-vok', { waitUntil: 'networkidle' });
|
|
await page.click('text=Скачать раздел для офлайна');
|
|
await page.waitForSelector('.offline-row--done', { timeout: 120_000 });
|
|
check(true, 'раздел скачан: ' + (await page.textContent('.offline-row--done')).trim());
|
|
|
|
// 4. Режим «самолёт»
|
|
await ctx.setOffline(true);
|
|
|
|
const brokenImages = () =>
|
|
page.evaluate(async () => {
|
|
window.scrollTo(0, document.body.scrollHeight);
|
|
await new Promise((r) => setTimeout(r, 1200));
|
|
const imgs = [...document.querySelectorAll('.kb-fig-img')];
|
|
imgs.forEach((i) => (i.loading = 'eager'));
|
|
await new Promise((r) => setTimeout(r, 1200));
|
|
return {
|
|
total: imgs.length + document.querySelectorAll('.kb-fig-miss').length,
|
|
broken: document.querySelectorAll('.kb-fig-miss').length + imgs.filter((i) => i.complete && !i.naturalWidth).length,
|
|
};
|
|
});
|
|
|
|
await page.goto(base + '/', { waitUntil: 'load' });
|
|
check(await page.locator('.cheat-card').isVisible(), 'офлайн: главная открылась');
|
|
check(await page.locator('.offline-banner').isVisible(), 'офлайн: баннер «Нет сети» показан');
|
|
if (shot) await page.screenshot({ path: `${shot}/offline-home.png` });
|
|
|
|
await page.goto(base + '/cheatsheet', { waitUntil: 'load' });
|
|
await page.waitForSelector('.cs-ban', { timeout: 5000 }).catch(() => {});
|
|
check((await page.locator('.cs-ban').count()) > 0, 'офлайн: шпаргалка открылась');
|
|
|
|
await page.goto(base + '/a/stoyka-vezda-silovoe', { waitUntil: 'load' });
|
|
await page.waitForSelector('.kb-body', { timeout: 5000 }).catch(() => {});
|
|
let img = await brokenImages();
|
|
check((await page.locator('.kb-key').count()) > 0 && img.broken === 0, `офлайн: ранее открытая статья, картинок ${img.total}, битых ${img.broken}`);
|
|
|
|
await page.goto(base + '/a/uzly-krepleniya-vok', { waitUntil: 'load' });
|
|
await page.waitForSelector('.kb-body', { timeout: 5000 }).catch(() => {});
|
|
img = await brokenImages();
|
|
check((await page.locator('.kb-key').count()) > 0 && img.broken === 0, `офлайн: статья из скачанного раздела (не открывалась), картинок ${img.total}, битых ${img.broken}`);
|
|
|
|
await page.goto(base + '/a/kreplenie-tablo', { waitUntil: 'load' });
|
|
await page.waitForTimeout(1500);
|
|
check(await page.locator('.notice').isVisible(), 'офлайн: несохранённая статья показывает понятное сообщение');
|
|
|
|
await page.goto(base + '/offline', { waitUntil: 'load' });
|
|
if (shot) await page.screenshot({ path: `${shot}/offline-sections.png` });
|
|
|
|
await browser.close();
|
|
console.log(failed ? `\nНе прошло: ${failed}` : '\nОфлайн работает');
|
|
process.exit(failed ? 1 : 0);
|