Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79d49181a6 | ||
|
|
f2be0df17a |
@@ -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);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.3 KiB |
@@ -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() {
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
|
||||
@@ -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 (
|
||||
<div className="offline-banner" role="status">
|
||||
<span className="warn-tri" aria-hidden="true" />
|
||||
<span>
|
||||
<span className="offline-banner-title">Нет сети: показана сохранённая версия</span>
|
||||
<span className="offline-banner-text">
|
||||
{synced ? `от ${formatDateTime(synced)} · ` : ''}обновится при подключении
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Зелёная метка «Офлайн» у статьи, которая есть в кеше. */
|
||||
export function OfflinePill({ long }: { long?: boolean }) {
|
||||
return (
|
||||
<span className="pill-offline">
|
||||
<span className="dot dot--sm" aria-hidden="true" />
|
||||
{long ? 'Доступно офлайн' : 'Офлайн'}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="offline-row offline-row--done">
|
||||
<span className="dot" aria-hidden="true" />
|
||||
<span className="offline-row-text">Сохранено для офлайна · {formatBytes(state.bytes)}</span>
|
||||
<button type="button" className="offline-row-btn" onClick={start}>
|
||||
Обновить
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (state.kind === 'loading') {
|
||||
return (
|
||||
<div className="offline-row" role="status">
|
||||
<span className="offline-row-text">
|
||||
Загрузка {state.pct}%
|
||||
<span className="progress">
|
||||
<span style={{ width: `${state.pct}%` }} />
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<button type="button" className="btn btn--outline btn--lg btn--block" onClick={start}>
|
||||
{failed ? 'Не скачалось: нет сети. Повторить' : 'Скачать раздел для офлайна'}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Карточка раздела на экране «Офлайн-разделы». */
|
||||
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 (
|
||||
<div className="off-card">
|
||||
<div className="off-card-head">
|
||||
<CodeTag code={section.code} />
|
||||
<span className="off-card-name">{section.name}</span>
|
||||
<span className="off-card-size">{formatBytes(state.kind === 'done' ? state.bytes : bytes)}</span>
|
||||
</div>
|
||||
{state.kind === 'done' ? (
|
||||
<div className="off-card-done">
|
||||
<span className="dot" aria-hidden="true" />
|
||||
<span className="offline-row-text">Сохранено · {formatDateTime(state.at)}</span>
|
||||
<button type="button" className="offline-row-btn" onClick={start}>
|
||||
Обновить
|
||||
</button>
|
||||
</div>
|
||||
) : state.kind === 'loading' ? (
|
||||
<div className="off-card-loading" role="status">
|
||||
<span className="progress progress--lg">
|
||||
<span style={{ width: `${state.pct}%` }} />
|
||||
</span>
|
||||
<span className="off-card-pct">Загрузка {state.pct}%</span>
|
||||
</div>
|
||||
) : (
|
||||
<button type="button" className="btn btn--outline btn--block off-card-btn" onClick={start}>
|
||||
{failed ? 'Не скачалось: нет сети. Повторить' : 'Скачать раздел для офлайна'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 }) {
|
||||
<NavLink to="/favorites" className="tree-link tree-link--top">
|
||||
Избранное
|
||||
</NavLink>
|
||||
<NavLink to="/offline" className="tree-link tree-link--top">
|
||||
Офлайн-разделы
|
||||
</NavLink>
|
||||
{nav.sections.map((s) => (
|
||||
<div key={s.id} className="tree-group">
|
||||
<Link to={`/s/${s.slug}`} className="tree-head">
|
||||
@@ -127,6 +131,7 @@ export function Screen({
|
||||
<div className="shell">
|
||||
<Sidebar />
|
||||
<div className="shell-main">
|
||||
<OfflineBanner />
|
||||
<main className={wide ? 'screen screen--wide' : 'screen'}>{children}</main>
|
||||
</div>
|
||||
{bar ?? (tab ? <TabBar active={tab} /> : null)}
|
||||
|
||||
@@ -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<T>(path: string, init?: RequestInit & { json?: unknown
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const treeQuery = { queryKey: ['tree'] as const, queryFn: () => api<TreeResponse>('/tree') };
|
||||
export const treeQuery = {
|
||||
queryKey: ['tree'] as const,
|
||||
queryFn: async () => {
|
||||
const tree = await api<TreeResponse>('/tree');
|
||||
markSynced();
|
||||
return tree;
|
||||
},
|
||||
};
|
||||
|
||||
export const articleQuery = (slug: string) => ({
|
||||
queryKey: ['article', slug] as const,
|
||||
|
||||
@@ -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<string, SavedSection>;
|
||||
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<number | null>(SYNCED, null)[0];
|
||||
}
|
||||
|
||||
// ---------- Ход скачивания (живёт в памяти, общий для всех экранов) ----------
|
||||
type Progress = Record<string, number>; // 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<SavedMap>(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<number> {
|
||||
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<boolean> {
|
||||
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<SavedMap>(SAVED, { ...getStored<SavedMap>(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<SavedMap>(SAVED, {});
|
||||
if (!cacheSupported()) return;
|
||||
await Promise.all([caches.delete(API_CACHE), caches.delete(IMG_CACHE)]).catch(() => undefined);
|
||||
}
|
||||
@@ -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(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -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 ? <Link to={`/s/${section.slug}`}>{section.name}</Link> : null} /{' '}
|
||||
<strong>{nav.short(art)}</strong>
|
||||
</div>
|
||||
<span id="article-offline-slot-desk" />
|
||||
{cached ? <OfflinePill long /> : null}
|
||||
<button type="button" className="btn btn--ghost" onClick={() => fav.toggle(slug)} aria-pressed={isFav}>
|
||||
{isFav ? '★ В избранном' : '☆ В избранное'}
|
||||
</button>
|
||||
@@ -192,14 +195,13 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
<IconPrint size={20} />
|
||||
Печать / PDF
|
||||
</button>
|
||||
<span id="article-edit-slot" />
|
||||
</div>
|
||||
|
||||
<div className="art-layout">
|
||||
<article className="art">
|
||||
<div className="topline art-topline">
|
||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||
<span id="article-offline-slot" />
|
||||
{cached ? <OfflinePill /> : null}
|
||||
</div>
|
||||
<div className="art-over">{section?.name}</div>
|
||||
<h1 className="art-title">{art.title}</h1>
|
||||
|
||||
@@ -180,6 +180,19 @@ export function HomePage() {
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{/* В макете этих ссылок нет: без них с телефона не попасть на экран офлайн-разделов */}
|
||||
<nav className="list home-more" aria-label="Ещё">
|
||||
<Link to="/offline" className="list-row">
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">Офлайн-разделы</span>
|
||||
<span className="list-row-sub">Скачать заранее, если на объекте нет связи</span>
|
||||
</span>
|
||||
<span className="list-row-chev" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
</nav>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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 (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
<ThemeButton />
|
||||
</div>
|
||||
<h1 className="off-title">Офлайн-разделы</h1>
|
||||
<p className="cheat-intro">Скачайте разделы заранее: в подвалах и паркингах связи часто нет.</p>
|
||||
{!cacheSupported() ? (
|
||||
<Notice title="Браузер не поддерживает офлайн">
|
||||
Откройте сайт по https в обычной вкладке Chrome или Safari.
|
||||
</Notice>
|
||||
) : (
|
||||
nav.sections.map((s) => <SectionOfflineCard key={s.id} section={s} />)
|
||||
)}
|
||||
<p className="off-note">
|
||||
Главная, шпаргалка и статьи, которые вы уже открывали, сохраняются сами. Исходные PDF офлайн недоступны.
|
||||
</p>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -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() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Сюда на этапе 5 встаёт строка «Сохранено для офлайна» */}
|
||||
<div id="section-offline-slot" data-section={section.id} />
|
||||
{cacheSupported() ? <SectionOfflineRow section={section} /> : null}
|
||||
|
||||
<div className="art-cards">
|
||||
{section.articles.map((a, i) => (
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+60
-1
@@ -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
|
||||
|
||||
@@ -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);
|
||||
Reference in New Issue
Block a user