diff --git a/apps/api/scripts/make-icons.mjs b/apps/api/scripts/make-icons.mjs
new file mode 100644
index 0000000..37fd75a
--- /dev/null
+++ b/apps/api/scripts/make-icons.mjs
@@ -0,0 +1,21 @@
+// Разовый скрипт: PNG-иконки PWA из apps/web/public/favicon.svg.
+// Запуск из apps/api (там установлен sharp): node scripts/make-icons.mjs
+import sharp from 'sharp';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const pub = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../web/public');
+const svg = path.join(pub, 'favicon.svg');
+const yellow = { r: 245, g: 196, b: 0, alpha: 1 };
+
+await sharp(svg, { density: 600 }).resize(192, 192).png().toFile(path.join(pub, 'icon-192.png'));
+await sharp(svg, { density: 600 }).resize(512, 512).png().toFile(path.join(pub, 'icon-512.png'));
+await sharp(svg, { density: 600 }).resize(180, 180).flatten({ background: yellow }).png().toFile(path.join(pub, 'apple-touch-icon.png'));
+// Maskable: значок с полями, чтобы Android мог обрезать его кругом
+await sharp(svg, { density: 600 })
+ .resize(360, 360)
+ .flatten({ background: yellow })
+ .extend({ top: 76, bottom: 76, left: 76, right: 76, background: yellow })
+ .png()
+ .toFile(path.join(pub, 'icon-maskable-512.png'));
+console.log('Иконки готовы:', pub);
diff --git a/apps/web/public/apple-touch-icon.png b/apps/web/public/apple-touch-icon.png
new file mode 100644
index 0000000..ac05fe7
Binary files /dev/null and b/apps/web/public/apple-touch-icon.png differ
diff --git a/apps/web/public/icon-192.png b/apps/web/public/icon-192.png
new file mode 100644
index 0000000..138eb4a
Binary files /dev/null and b/apps/web/public/icon-192.png differ
diff --git a/apps/web/public/icon-512.png b/apps/web/public/icon-512.png
new file mode 100644
index 0000000..678c394
Binary files /dev/null and b/apps/web/public/icon-512.png differ
diff --git a/apps/web/public/icon-maskable-512.png b/apps/web/public/icon-maskable-512.png
new file mode 100644
index 0000000..fa3f548
Binary files /dev/null and b/apps/web/public/icon-maskable-512.png differ
diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx
index b66a2bb..8531994 100644
--- a/apps/web/src/App.tsx
+++ b/apps/web/src/App.tsx
@@ -7,6 +7,7 @@ import { ArticlePage } from './pages/Article';
import { CheatSheetPage } from './pages/CheatSheet';
import { FavoritesPage } from './pages/Favorites';
import { HomePage } from './pages/Home';
+import { OfflinePage } from './pages/OfflinePage';
import { SearchPage } from './pages/Search';
import { SectionPage } from './pages/Section';
@@ -37,6 +38,7 @@ export function App() {
} />
} />
} />
+ } />
} />
} />
diff --git a/apps/web/src/components/Offline.tsx b/apps/web/src/components/Offline.tsx
new file mode 100644
index 0000000..8147a45
--- /dev/null
+++ b/apps/web/src/components/Offline.tsx
@@ -0,0 +1,114 @@
+import { useState } from 'react';
+import { formatBytes, formatDateTime } from '../lib/format';
+import { downloadSection, useLastSynced, useOnline, useSectionOffline } from '../lib/offline';
+import type { SectionView } from '../lib/tree';
+import { CodeTag } from './ui';
+
+/** Жёлтая полоса сверху, когда сети нет. */
+export function OfflineBanner() {
+ const online = useOnline();
+ const synced = useLastSynced();
+ if (online) return null;
+ return (
+
+
+
+ Нет сети: показана сохранённая версия
+
+ {synced ? `от ${formatDateTime(synced)} · ` : ''}обновится при подключении
+
+
+
+ );
+}
+
+/** Зелёная метка «Офлайн» у статьи, которая есть в кеше. */
+export function OfflinePill({ long }: { long?: boolean }) {
+ return (
+
+
+ {long ? 'Доступно офлайн' : 'Офлайн'}
+
+ );
+}
+
+function useDownload(section: SectionView) {
+ const [failed, setFailed] = useState(false);
+ const start = async () => {
+ setFailed(false);
+ setFailed(!(await downloadSection(section)));
+ };
+ return { failed, start };
+}
+
+/** Строка на экране раздела: «Сохранено для офлайна · 14 МБ · Обновить». */
+export function SectionOfflineRow({ section }: { section: SectionView }) {
+ const state = useSectionOffline(section.id);
+ const { failed, start } = useDownload(section);
+
+ if (state.kind === 'done') {
+ return (
+
+
+ Сохранено для офлайна · {formatBytes(state.bytes)}
+
+
+ );
+ }
+ if (state.kind === 'loading') {
+ return (
+
+
+ Загрузка {state.pct}%
+
+
+
+
+
+ );
+ }
+ return (
+
+ );
+}
+
+/** Карточка раздела на экране «Офлайн-разделы». */
+export function SectionOfflineCard({ section }: { section: SectionView }) {
+ const state = useSectionOffline(section.id);
+ const { failed, start } = useDownload(section);
+ const bytes = section.articles.reduce((n, a) => n + a.bytes, 0);
+
+ return (
+
+
+
+ {section.name}
+ {formatBytes(state.kind === 'done' ? state.bytes : bytes)}
+
+ {state.kind === 'done' ? (
+
+
+ Сохранено · {formatDateTime(state.at)}
+
+
+ ) : state.kind === 'loading' ? (
+
+
+
+
+ Загрузка {state.pct}%
+
+ ) : (
+
+ )}
+
+ );
+}
diff --git a/apps/web/src/components/Shell.tsx b/apps/web/src/components/Shell.tsx
index b4dcfb3..ab7ec24 100644
--- a/apps/web/src/components/Shell.tsx
+++ b/apps/web/src/components/Shell.tsx
@@ -4,6 +4,7 @@ import { Link, NavLink, useLocation } from 'react-router-dom';
import { THEME_LABEL, THEME_ORDER, useTheme } from '../lib/theme';
import { articleHref, useNav } from '../lib/tree';
import { IconDoc, IconHome, IconSearch, IconStar } from './Icons';
+import { OfflineBanner } from './Offline';
import { CodeTag } from './ui';
export type Tab = 'home' | 'search' | 'cheat' | 'fav';
@@ -67,6 +68,9 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
Избранное
+
+ Офлайн-разделы
+
{nav.sections.map((s) => (
@@ -127,6 +131,7 @@ export function Screen({
+
{children}
{bar ?? (tab ?
: null)}
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index f863893..831c387 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query';
import type { ArticleDto, TreeResponse } from '@kb/shared';
+import { markSynced } from './offline';
/** Ошибка ответа API: status нужен, чтобы отличать 401 (надо войти) от 404 и от «нет сети». */
export class ApiError extends Error {
@@ -37,7 +38,14 @@ export async function api
(path: string, init?: RequestInit & { json?: unknown
return data as T;
}
-export const treeQuery = { queryKey: ['tree'] as const, queryFn: () => api('/tree') };
+export const treeQuery = {
+ queryKey: ['tree'] as const,
+ queryFn: async () => {
+ const tree = await api('/tree');
+ markSynced();
+ return tree;
+ },
+};
export const articleQuery = (slug: string) => ({
queryKey: ['article', slug] as const,
diff --git a/apps/web/src/lib/offline.ts b/apps/web/src/lib/offline.ts
new file mode 100644
index 0000000..d696ba4
--- /dev/null
+++ b/apps/web/src/lib/offline.ts
@@ -0,0 +1,159 @@
+// Офлайн: скачивание разделов в кеш браузера, статус сети, проверка «статья сохранена».
+//
+// Кеши ведёт service worker (см. vite.config.ts): всё, что открывалось, он складывает сам.
+// «Скачать раздел» делает то же самое заранее: кладёт ответы API и картинки в те же кеши.
+
+import { useEffect, useState, useSyncExternalStore } from 'react';
+import type { ArticleDto } from '@kb/shared';
+import { getStored, setStored, useStored } from './store';
+import type { SectionView } from './tree';
+
+// Имена кешей должны совпадать с runtimeCaching в vite.config.ts
+export const API_CACHE = 'kb-api';
+export const IMG_CACHE = 'kb-img';
+
+const SAVED = 'kb-offline';
+const SYNCED = 'kb-synced';
+
+export interface SavedSection {
+ /** Когда скачали. */
+ at: number;
+ bytes: number;
+}
+type SavedMap = Record;
+const NONE: SavedMap = {};
+
+export const cacheSupported = () => typeof caches !== 'undefined';
+
+// ---------- Статус сети ----------
+function subscribeOnline(cb: () => void) {
+ window.addEventListener('online', cb);
+ window.addEventListener('offline', cb);
+ return () => {
+ window.removeEventListener('online', cb);
+ window.removeEventListener('offline', cb);
+ };
+}
+export function useOnline(): boolean {
+ return useSyncExternalStore(subscribeOnline, () => navigator.onLine);
+}
+
+/** Запомнить момент последней успешной загрузки данных с сервера (для баннера «версия от …»). */
+export function markSynced() {
+ if (navigator.onLine) setStored(SYNCED, Date.now());
+}
+export function useLastSynced(): number | null {
+ return useStored(SYNCED, null)[0];
+}
+
+// ---------- Ход скачивания (живёт в памяти, общий для всех экранов) ----------
+type Progress = Record; // sectionId → проценты
+let progress: Progress = {};
+const listeners = new Set<() => void>();
+function setProgress(id: string, pct: number | null) {
+ const next = { ...progress };
+ if (pct === null) delete next[id];
+ else next[id] = pct;
+ progress = next;
+ listeners.forEach((l) => l());
+}
+function subscribeProgress(l: () => void) {
+ listeners.add(l);
+ return () => listeners.delete(l);
+}
+
+export type OfflineState =
+ | { kind: 'idle' }
+ | { kind: 'loading'; pct: number }
+ | { kind: 'done'; at: number; bytes: number };
+
+export function useSectionOffline(sectionId: string): OfflineState {
+ const [saved] = useStored(SAVED, NONE);
+ const p = useSyncExternalStore(subscribeProgress, () => progress)[sectionId];
+ if (p !== undefined) return { kind: 'loading', pct: p };
+ const s = saved[sectionId];
+ return s ? { kind: 'done', ...s } : { kind: 'idle' };
+}
+
+async function fetchInto(cacheName: string, url: string): Promise {
+ const res = await fetch(url, { credentials: 'same-origin', headers: { 'X-Requested-With': 'kb' } });
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
+ const cache = await caches.open(cacheName);
+ const copy = res.clone();
+ await cache.put(url, res);
+ return (await copy.blob()).size;
+}
+
+/**
+ * Скачивает раздел: тексты статей и все их картинки (превью и полный размер).
+ * Возвращает false, если что-то не скачалось (нет сети).
+ */
+export async function downloadSection(section: SectionView): Promise {
+ if (!cacheSupported() || progress[section.id] !== undefined) return false;
+ setProgress(section.id, 0);
+ let bytes = 0;
+ try {
+ // Сначала статьи: из них узнаём список картинок
+ const images: string[] = [];
+ const cache = await caches.open(API_CACHE);
+ for (const a of section.articles) {
+ const url = `/api/articles/${encodeURIComponent(a.slug)}`;
+ const res = await fetch(url, { credentials: 'same-origin', headers: { 'X-Requested-With': 'kb' } });
+ if (!res.ok) throw new Error(`${url}: ${res.status}`);
+ const copy = res.clone();
+ await cache.put(url, res);
+ const art = (await copy.json()) as ArticleDto;
+ bytes += JSON.stringify(art).length;
+ images.push(...art.images.filter((u) => u.startsWith('/uploads/')));
+ }
+
+ const unique = [...new Set(images)];
+ let done = 0;
+ // По 4 картинки одновременно: быстрее, чем по одной, и не забивает слабую сеть
+ const queue = [...unique];
+ const worker = async () => {
+ for (let url = queue.shift(); url; url = queue.shift()) {
+ bytes += await fetchInto(IMG_CACHE, url);
+ done++;
+ setProgress(section.id, Math.round((done / unique.length) * 100));
+ }
+ };
+ await Promise.all(Array.from({ length: 4 }, worker));
+
+ setStored(SAVED, { ...getStored(SAVED, NONE), [section.id]: { at: Date.now(), bytes } });
+ return true;
+ } catch {
+ return false;
+ } finally {
+ setProgress(section.id, null);
+ }
+}
+
+/** Есть ли статья в кеше (открывалась раньше или скачана с разделом). */
+export function useIsCached(slug: string | undefined): boolean {
+ const [cached, setCached] = useState(false);
+ useEffect(() => {
+ let alive = true;
+ if (!slug || !cacheSupported()) return;
+ // Проверяем чуть позже загрузки: service worker кладёт ответ в кеш после того, как отдал его странице
+ const id = setTimeout(() => {
+ void caches
+ .open(API_CACHE)
+ .then((c) => c.match(`/api/articles/${encodeURIComponent(slug)}`))
+ .then((hit) => alive && setCached(!!hit))
+ .catch(() => undefined);
+ }, 1200);
+ return () => {
+ alive = false;
+ clearTimeout(id);
+ };
+ }, [slug]);
+ return cached;
+}
+
+/** Стереть сохранённые ответы API (при выходе из аккаунта: чужие данные не должны остаться на устройстве). */
+export async function clearPrivateCaches() {
+ setStored(SAVED, {});
+ if (!cacheSupported()) return;
+ await Promise.all([caches.delete(API_CACHE), caches.delete(IMG_CACHE)]).catch(() => undefined);
+}
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index ebc5baa..2be25b2 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -7,6 +7,7 @@ import '@fontsource-variable/onest/wght.css';
import './styles/tokens.css';
import './styles/app.css';
import './styles/article.css';
+import { registerSW } from 'virtual:pwa-register';
import { App } from './App';
import { ApiError } from './lib/api';
@@ -24,6 +25,9 @@ const queryClient = new QueryClient({
},
});
+// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
+registerSW({ immediate: true });
+
createRoot(document.getElementById('root')!).render(
diff --git a/apps/web/src/pages/Article.tsx b/apps/web/src/pages/Article.tsx
index 9d7907d..6c5c86e 100644
--- a/apps/web/src/pages/Article.tsx
+++ b/apps/web/src/pages/Article.tsx
@@ -3,6 +3,8 @@ import { Link, Navigate, useParams } from 'react-router-dom';
import { ArticleBody, type Figure } from '../components/ArticleBody';
import { IconList, IconPrint, IconStar, IconTheme, IconUp } from '../components/Icons';
import { Lightbox } from '../components/Lightbox';
+import { OfflinePill } from '../components/Offline';
+import { useIsCached } from '../lib/offline';
import { PrintSheet } from '../components/PrintSheet';
import { Screen } from '../components/Shell';
import { BackLink, Notice, Sheet, Skeleton } from '../components/ui';
@@ -51,6 +53,7 @@ function ArticleView({ slug }: { slug: string }) {
const fav = useFavorites();
const theme = useTheme();
const { scrolled, progress } = useReadProgress();
+ const cached = useIsCached(art?.slug);
const [tocOpen, setTocOpen] = useState(false);
const [printOpen, setPrintOpen] = useState(false);
const [lightbox, setLightbox] = useState<{ figures: Figure[]; start: number } | null>(null);
@@ -184,7 +187,7 @@ function ArticleView({ slug }: { slug: string }) {
{nav.space?.name} / {section ? {section.name} : null} /{' '}
{nav.short(art)}
-
+ {cached ?
: null}
@@ -192,14 +195,13 @@ function ArticleView({ slug }: { slug: string }) {
Печать / PDF
-
{section?.name ?? 'Главная'}
-
+ {cached ? : null}
{section?.name}
{art.title}
diff --git a/apps/web/src/pages/Home.tsx b/apps/web/src/pages/Home.tsx
index 087bb86..d2e36f6 100644
--- a/apps/web/src/pages/Home.tsx
+++ b/apps/web/src/pages/Home.tsx
@@ -180,6 +180,19 @@ export function HomePage() {
) : null}
+
+ {/* В макете этих ссылок нет: без них с телефона не попасть на экран офлайн-разделов */}
+
);
}
diff --git a/apps/web/src/pages/OfflinePage.tsx b/apps/web/src/pages/OfflinePage.tsx
new file mode 100644
index 0000000..e795bfe
--- /dev/null
+++ b/apps/web/src/pages/OfflinePage.tsx
@@ -0,0 +1,29 @@
+import { SectionOfflineCard } from '../components/Offline';
+import { Screen } from '../components/Shell';
+import { BackLink, Notice, ThemeButton } from '../components/ui';
+import { cacheSupported } from '../lib/offline';
+import { useNav } from '../lib/tree';
+
+export function OfflinePage() {
+ const nav = useNav();
+ return (
+
+
+ Главная
+
+
+ Офлайн-разделы
+ Скачайте разделы заранее: в подвалах и паркингах связи часто нет.
+ {!cacheSupported() ? (
+
+ Откройте сайт по https в обычной вкладке Chrome или Safari.
+
+ ) : (
+ nav.sections.map((s) => )
+ )}
+
+ Главная, шпаргалка и статьи, которые вы уже открывали, сохраняются сами. Исходные PDF офлайн недоступны.
+
+
+ );
+}
diff --git a/apps/web/src/pages/Section.tsx b/apps/web/src/pages/Section.tsx
index 008aed5..4cbc4ef 100644
--- a/apps/web/src/pages/Section.tsx
+++ b/apps/web/src/pages/Section.tsx
@@ -1,6 +1,8 @@
import { Link, useParams } from 'react-router-dom';
import { plural } from '@kb/shared';
+import { SectionOfflineRow } from '../components/Offline';
import { Screen } from '../components/Shell';
+import { cacheSupported } from '../lib/offline';
import { BackLink, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
import { num2 } from '../lib/format';
import { articleHref, useNav } from '../lib/tree';
@@ -42,8 +44,7 @@ export function SectionPage() {
- {/* Сюда на этапе 5 встаёт строка «Сохранено для офлайна» */}
-
+ {cacheSupported() ? : null}
{section.articles.map((a, i) => (
diff --git a/apps/web/src/styles/app.css b/apps/web/src/styles/app.css
index a00c039..0bc080b 100644
--- a/apps/web/src/styles/app.css
+++ b/apps/web/src/styles/app.css
@@ -2111,3 +2111,126 @@ mark {
flex-wrap: wrap;
}
}
+
+/* ---------- Офлайн ---------- */
+.offline-banner {
+ display: flex;
+ gap: var(--sp-6);
+ align-items: flex-start;
+ padding: calc(var(--sp-6) + env(safe-area-inset-top)) var(--sp-8) var(--sp-6);
+ background: var(--brand);
+ color: var(--brand-ink);
+}
+.offline-banner + .screen {
+ padding-top: var(--sp-6);
+}
+.offline-banner-title {
+ display: block;
+ font-weight: 700;
+ line-height: var(--lh-snug);
+}
+.offline-banner-text {
+ display: block;
+ font-size: var(--fs-14);
+}
+.warn-tri {
+ flex: none;
+ position: relative;
+ width: 0;
+ height: 0;
+ margin-top: var(--sp-1);
+ border-left: 12px solid transparent;
+ border-right: 12px solid transparent;
+ border-bottom: 20px solid var(--brand-ink);
+}
+.warn-tri::after {
+ content: '';
+ position: absolute;
+ left: -2px;
+ top: 6px;
+ width: 4px;
+ height: 8px;
+ background: var(--brand);
+}
+.progress {
+ display: block;
+ height: 4px;
+ margin-top: var(--sp-3);
+ border-radius: var(--r-xs);
+ background: var(--sf2);
+ overflow: hidden;
+}
+.progress span {
+ display: block;
+ height: 100%;
+ background: var(--grnS);
+ transition: width 0.2s;
+}
+.progress--lg {
+ height: 10px;
+ margin: 0;
+ border-radius: 5px;
+ border: var(--bw) solid var(--ln);
+}
+.off-title {
+ font-size: var(--fs-24);
+ font-weight: 700;
+}
+.off-note {
+ font-size: var(--fs-14);
+ color: var(--ink2);
+ line-height: var(--lh-normal);
+}
+.off-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--sp-5);
+ padding: var(--sp-7);
+ border: var(--bw) solid var(--ln);
+ border-radius: var(--r-card);
+ background: var(--sf);
+}
+.off-card-head {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-6);
+}
+.off-card-name {
+ flex: 1;
+ min-width: 0;
+ font-weight: 700;
+ line-height: var(--lh-snug);
+}
+.off-card-size,
+.off-card-pct {
+ font-size: var(--fs-13);
+ color: var(--ink2);
+}
+.off-card-done {
+ display: flex;
+ align-items: center;
+ gap: var(--sp-4);
+ min-height: var(--h-chip);
+ color: var(--grn);
+ font-size: var(--fs-15);
+ font-weight: 700;
+}
+.off-card-loading {
+ display: flex;
+ flex-direction: column;
+ gap: var(--sp-3);
+}
+.off-card-btn {
+ min-height: 52px;
+ border-radius: var(--r-btn);
+ font-size: var(--fs-16);
+ white-space: normal;
+}
+.btn--lg.btn--block {
+ white-space: normal;
+}
+@media (min-width: 1024px) {
+ .home-more {
+ display: none;
+ }
+}
diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts
index d305cdf..760f749 100644
--- a/apps/web/vite.config.ts
+++ b/apps/web/vite.config.ts
@@ -1,8 +1,67 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
+import { VitePWA } from 'vite-plugin-pwa';
export default defineConfig({
- plugins: [react()],
+ plugins: [
+ react(),
+ // PWA: сайт ставится на домашний экран и работает без сети.
+ VitePWA({
+ registerType: 'autoUpdate',
+ includeAssets: ['favicon.svg', 'apple-touch-icon.png', 'theme-init.js'],
+ manifest: {
+ name: 'Памятки монтажника',
+ short_name: 'Памятки',
+ description: 'Инструкции по монтажу: цифры, запреты, чек-листы. Работает без сети.',
+ lang: 'ru',
+ start_url: '/',
+ scope: '/',
+ display: 'standalone',
+ orientation: 'portrait',
+ background_color: '#0f1011',
+ theme_color: '#0f1011',
+ icons: [
+ { src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
+ { src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
+ { src: '/icon-maskable-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
+ ],
+ },
+ workbox: {
+ // App shell: весь интерфейс (JS, CSS, шрифты, иконки) кешируется при первой загрузке
+ globPatterns: ['**/*.{js,css,html,svg,png,woff2}'],
+ // Любой адрес сайта без сети открывает index.html из кеша (кроме API и файлов)
+ navigateFallback: '/index.html',
+ navigateFallbackDenylist: [/^\/api\//, /^\/uploads\//],
+ cleanupOutdatedCaches: true,
+ clientsClaim: true,
+ skipWaiting: true,
+ runtimeCaching: [
+ {
+ // Дерево и статьи: сразу отдаём сохранённое, в фоне обновляем (stale-while-revalidate).
+ // Имя кеша используется и в src/lib/offline.ts.
+ urlPattern: ({ url, request }) =>
+ request.method === 'GET' && (url.pathname === '/api/tree' || url.pathname.startsWith('/api/articles/')),
+ handler: 'StaleWhileRevalidate',
+ options: {
+ cacheName: 'kb-api',
+ cacheableResponse: { statuses: [200] },
+ expiration: { maxEntries: 600 },
+ },
+ },
+ {
+ // Картинки статей: так же
+ urlPattern: ({ url }) => url.pathname.startsWith('/uploads/') && url.pathname.endsWith('.webp'),
+ handler: 'StaleWhileRevalidate',
+ options: {
+ cacheName: 'kb-img',
+ cacheableResponse: { statuses: [200] },
+ expiration: { maxEntries: 3000, purgeOnQuotaError: true },
+ },
+ },
+ ],
+ },
+ }),
+ ],
server: {
port: 5180,
// В разработке запросы к API и картинкам уходят на локальный сервер API
diff --git a/scripts/check-offline.mjs b/scripts/check-offline.mjs
new file mode 100644
index 0000000..ff2bc73
--- /dev/null
+++ b/scripts/check-offline.mjs
@@ -0,0 +1,88 @@
+// Проверка офлайна: открываем сайт, скачиваем раздел, отключаем сеть и убеждаемся,
+// что главная, шпаргалка, открытая и скачанная статьи показываются вместе с картинками.
+// Запуск: 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);