Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f08158607 | ||
|
|
27cdca3967 | ||
|
|
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);
|
||||
+61
-3
@@ -1,9 +1,49 @@
|
||||
import express, { type ErrorRequestHandler } from 'express';
|
||||
import path from 'node:path';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';
|
||||
import { ZodError } from 'zod';
|
||||
import type { HealthResponse } from '@kb/shared';
|
||||
import { csrfGuard, loadUser } from './auth.js';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { authRouter } from './routes/auth.js';
|
||||
import { contentRouter } from './routes/content.js';
|
||||
import { meRouter } from './routes/me.js';
|
||||
|
||||
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
|
||||
const publicFiles = new Map<string, { ok: boolean; at: number }>();
|
||||
const PUBLIC_TTL = 60_000;
|
||||
|
||||
async function isPublicFile(rel: string): Promise<boolean> {
|
||||
const hit = publicFiles.get(rel);
|
||||
if (hit && Date.now() - hit.at < PUBLIC_TTL) return hit.ok;
|
||||
// Превью fig-1.480.webp относится к той же записи, что и fig-1.webp
|
||||
const assetPath = rel.replace(/\.480\.webp$/, '.webp');
|
||||
const open = { status: 'PUBLISHED', visibility: 'PUBLIC' } as const;
|
||||
const [asset, attachment] = await Promise.all([
|
||||
prisma.asset.findFirst({ where: { path: assetPath, article: open }, select: { id: true } }),
|
||||
prisma.attachment.findFirst({ where: { path: rel, article: open }, select: { id: true } }),
|
||||
]);
|
||||
const ok = !!asset || !!attachment;
|
||||
if (publicFiles.size > 5000) publicFiles.clear();
|
||||
publicFiles.set(rel, { ok, at: Date.now() });
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Файлы закрытых статей отдаём только вошедшим пользователям. */
|
||||
const uploadsGuard: RequestHandler = async (req, res, next) => {
|
||||
if (req.user) return next();
|
||||
let rel: string;
|
||||
try {
|
||||
rel = path.posix.normalize(decodeURIComponent(req.path)).replace(/^\/+/, '');
|
||||
} catch {
|
||||
res.status(400).json({ error: 'Некорректный адрес' });
|
||||
return;
|
||||
}
|
||||
if (await isPublicFile(rel)) return next();
|
||||
res.status(401).json({ error: 'Нужно войти' });
|
||||
};
|
||||
|
||||
export function createApp() {
|
||||
const app = express();
|
||||
@@ -12,6 +52,7 @@ export function createApp() {
|
||||
app.set('trust proxy', 2);
|
||||
app.disable('x-powered-by');
|
||||
app.use(express.json({ limit: '2mb' }));
|
||||
app.use(cookieParser());
|
||||
|
||||
// Healthcheck: проверяет и сам процесс, и соединение с БД.
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
@@ -20,16 +61,20 @@ export function createApp() {
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Загруженные файлы. Имена картинок не меняются при замене содержимого редко,
|
||||
// поэтому кешируем на сутки, а дальше браузер перепроверяет по ETag.
|
||||
app.use(loadUser);
|
||||
|
||||
// Загруженные файлы: кешируются на сутки, дальше браузер перепроверяет по ETag.
|
||||
app.use(
|
||||
'/uploads',
|
||||
uploadsGuard,
|
||||
express.static(env.UPLOADS_DIR, {
|
||||
index: false,
|
||||
dotfiles: 'deny',
|
||||
maxAge: '1d',
|
||||
setHeaders(res, file) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
// private: общие прокси не должны хранить файлы закрытых статей
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
// Исходники (PDF/DOCX) всегда скачиваются, а не открываются в браузере
|
||||
if (!/\.(webp|png|jpe?g|gif)$/i.test(file)) res.setHeader('Content-Disposition', 'attachment');
|
||||
},
|
||||
@@ -39,6 +84,9 @@ export function createApp() {
|
||||
res.status(404).json({ error: 'Файл не найден' });
|
||||
});
|
||||
|
||||
app.use('/api', csrfGuard);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/me', meRouter);
|
||||
app.use('/api', contentRouter);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
@@ -51,6 +99,16 @@ export function createApp() {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
return;
|
||||
}
|
||||
// Ошибка проверки входных данных (Zod): показываем первое понятное сообщение
|
||||
if (err instanceof ZodError) {
|
||||
const first = err.issues[0];
|
||||
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
|
||||
return;
|
||||
}
|
||||
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') {
|
||||
res.status(400).json({ error: 'Некорректный запрос' });
|
||||
return;
|
||||
}
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Сессии и проверка прав.
|
||||
//
|
||||
// Как это устроено:
|
||||
// - при входе создаём случайный токен, кладём его в httpOnly-cookie (JavaScript страницы его не видит),
|
||||
// а в БД сохраняем только SHA-256 от токена;
|
||||
// - на каждом запросе по cookie находим сессию и пользователя (req.user);
|
||||
// - requireAuth / requireRole стоят перед обработчиками: права проверяет сервер, а не только интерфейс.
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Role, User } from '@prisma/client';
|
||||
import type { UserDto } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
|
||||
export const COOKIE = 'kb_session';
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
export const REMEMBER_MS = 90 * DAY; // «Запомнить устройство»
|
||||
export const SHORT_MS = 1 * DAY; // без галочки: сутки, cookie живёт до закрытия браузера
|
||||
|
||||
// Добавляем свои поля в тип запроса Express (так это принято делать в его типах)
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: User;
|
||||
sessionId?: string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
|
||||
|
||||
export const toUserDto = (u: User): UserDto => ({ id: u.id, email: u.email, name: u.name, role: u.role });
|
||||
|
||||
export async function createSession(res: Response, user: User, remember: boolean, userAgent?: string) {
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
const ttl = remember ? REMEMBER_MS : SHORT_MS;
|
||||
await prisma.session.create({
|
||||
data: {
|
||||
tokenHash: sha256(token),
|
||||
userId: user.id,
|
||||
expiresAt: new Date(Date.now() + ttl),
|
||||
userAgent: userAgent?.slice(0, 300),
|
||||
},
|
||||
});
|
||||
res.cookie(COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: env.COOKIE_SECURE,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
// Без maxAge cookie сессионная: пропадает при закрытии браузера
|
||||
...(remember ? { maxAge: ttl } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function destroySession(req: Request, res: Response) {
|
||||
const token = req.cookies?.[COOKIE] as string | undefined;
|
||||
if (token) await prisma.session.deleteMany({ where: { tokenHash: sha256(token) } });
|
||||
res.clearCookie(COOKIE, { path: '/' });
|
||||
}
|
||||
|
||||
/** Находит пользователя по cookie. Не требует входа: просто заполняет req.user, если сессия жива. */
|
||||
export const loadUser: RequestHandler = async (req, _res, next) => {
|
||||
const token = req.cookies?.[COOKIE] as string | undefined;
|
||||
if (!token) return next();
|
||||
const session = await prisma.session.findUnique({ where: { tokenHash: sha256(token) }, include: { user: true } });
|
||||
if (!session || session.expiresAt < new Date() || session.user.blocked) return next();
|
||||
req.user = session.user;
|
||||
req.sessionId = session.id;
|
||||
// Отметку «был в сети» обновляем не чаще раза в 10 минут, чтобы не писать в БД на каждый запрос
|
||||
if (!session.user.lastSeenAt || Date.now() - session.user.lastSeenAt.getTime() > 10 * 60 * 1000) {
|
||||
void prisma.user.update({ where: { id: session.user.id }, data: { lastSeenAt: new Date() } }).catch(() => undefined);
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
export const requireAuth: RequestHandler = (req, _res, next) => {
|
||||
if (!req.user) throw new HttpError(401, 'Нужно войти');
|
||||
next();
|
||||
};
|
||||
|
||||
const RANK: Record<Role, number> = { VIEWER: 1, EDITOR: 2, ADMIN: 3 };
|
||||
|
||||
/** Доступ с роли и выше: requireRole('EDITOR') пускает редакторов и админов. */
|
||||
export const requireRole =
|
||||
(role: Role): RequestHandler =>
|
||||
(req, _res, next) => {
|
||||
if (!req.user) throw new HttpError(401, 'Нужно войти');
|
||||
if (RANK[req.user.role] < RANK[role]) throw new HttpError(403, 'Недостаточно прав');
|
||||
next();
|
||||
};
|
||||
|
||||
export const canEdit = (u?: User) => !!u && RANK[u.role] >= RANK.EDITOR;
|
||||
|
||||
/**
|
||||
* Защита от CSRF: на изменяющих запросах требуем заголовок X-Requested-With.
|
||||
* Чужой сайт не может отправить его из браузера пользователя без разрешения CORS,
|
||||
* а CORS у нас открыт только для своего домена.
|
||||
*/
|
||||
export function csrfGuard(req: Request, _res: Response, next: NextFunction) {
|
||||
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||
if (req.get('X-Requested-With') !== 'kb') throw new HttpError(403, 'Запрос отклонён');
|
||||
next();
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Router } from 'express';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { z } from 'zod';
|
||||
import { createSession, destroySession, requireAuth, toUserDto } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { hashPassword, verifyPassword } from '../services/password.js';
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
// Не больше 10 неудачных попыток входа с одного адреса за 15 минут
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 10,
|
||||
skipSuccessfulRequests: true,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Слишком много попыток входа. Подождите 15 минут.' },
|
||||
});
|
||||
|
||||
const inviteLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 30, standardHeaders: 'draft-7', legacyHeaders: false });
|
||||
|
||||
const email = z.string().trim().toLowerCase().email('Некорректная почта').max(200);
|
||||
const loginBody = z.object({ email, password: z.string().min(1).max(200), remember: z.boolean().default(false) });
|
||||
|
||||
// Заранее посчитанный хеш: если пользователя нет, всё равно тратим время на проверку пароля,
|
||||
// чтобы по скорости ответа нельзя было узнать, зарегистрирована ли почта.
|
||||
const dummyHash = hashPassword('not-a-real-password');
|
||||
|
||||
authRouter.post('/login', loginLimiter, async (req, res) => {
|
||||
const body = loginBody.parse(req.body);
|
||||
const user = await prisma.user.findUnique({ where: { email: body.email } });
|
||||
const ok = await verifyPassword(user?.passwordHash ?? (await dummyHash), body.password);
|
||||
if (!user || !ok) throw new HttpError(401, 'Неверная почта или пароль');
|
||||
if (user.blocked) throw new HttpError(403, 'Учётная запись заблокирована');
|
||||
await createSession(res, user, body.remember, req.get('user-agent'));
|
||||
res.json({ user: toUserDto(user) });
|
||||
});
|
||||
|
||||
authRouter.post('/logout', async (req, res) => {
|
||||
await destroySession(req, res);
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
authRouter.get('/me', requireAuth, (req, res) => {
|
||||
res.json({ user: toUserDto(req.user!) });
|
||||
});
|
||||
|
||||
// ---------- Приглашения ----------
|
||||
async function findInvite(token: string) {
|
||||
const invite = await prisma.invite.findUnique({ where: { token } });
|
||||
if (!invite || invite.usedAt || invite.expiresAt < new Date()) {
|
||||
throw new HttpError(404, 'Ссылка-приглашение недействительна или уже использована');
|
||||
}
|
||||
return invite;
|
||||
}
|
||||
|
||||
authRouter.get('/invite/:token', inviteLimiter, async (req, res) => {
|
||||
const invite = await findInvite(String(req.params.token));
|
||||
res.json({ role: invite.role, expiresAt: invite.expiresAt.toISOString() });
|
||||
});
|
||||
|
||||
const acceptBody = z.object({
|
||||
email,
|
||||
name: z.string().trim().min(2, 'Укажите имя').max(100),
|
||||
password: z.string().min(8, 'Пароль не короче 8 символов').max(200),
|
||||
});
|
||||
|
||||
authRouter.post('/invite/:token', inviteLimiter, async (req, res) => {
|
||||
const body = acceptBody.parse(req.body);
|
||||
const invite = await findInvite(String(req.params.token));
|
||||
if (await prisma.user.findUnique({ where: { email: body.email } })) {
|
||||
throw new HttpError(409, 'Пользователь с такой почтой уже есть. Войдите с паролем.');
|
||||
}
|
||||
const passwordHash = await hashPassword(body.password);
|
||||
// В одной транзакции: приглашение одноразовое, два человека по одной ссылке не зарегистрируются
|
||||
const user = await prisma.$transaction(async (tx) => {
|
||||
const used = await tx.invite.updateMany({ where: { id: invite.id, usedAt: null }, data: { usedAt: new Date() } });
|
||||
if (used.count !== 1) throw new HttpError(404, 'Ссылка-приглашение уже использована');
|
||||
return tx.user.create({ data: { email: body.email, name: body.name, passwordHash, role: invite.role } });
|
||||
});
|
||||
await createSession(res, user, true, req.get('user-agent'));
|
||||
res.status(201).json({ user: toUserDto(user) });
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { Router } from 'express';
|
||||
import type { Article, Section, Space } from '@prisma/client';
|
||||
import { parseCheatSheet, renderMarkdown } from '@kb/md';
|
||||
import type { ArticleDto, ArticleListItem, SectionDto, SpaceDto, TreeResponse, PlaqueColor } from '@kb/shared';
|
||||
import { canEdit } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { search } from '../search.js';
|
||||
@@ -45,18 +46,28 @@ export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({
|
||||
// Всё дерево одним запросом: пространства, разделы и список статей (без текста).
|
||||
// Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны,
|
||||
// а для офлайна один ответ кешировать проще.
|
||||
contentRouter.get('/tree', async (_req, res) => {
|
||||
const [spaces, sections, articles] = await Promise.all([
|
||||
// Кто что видит: без входа только опубликованные статьи с visibility PUBLIC;
|
||||
// читатель: все опубликованные; редактор и админ: ещё и черновики.
|
||||
contentRouter.get('/tree', async (req, res) => {
|
||||
const where = !req.user
|
||||
? { status: 'PUBLISHED' as const, visibility: 'PUBLIC' as const }
|
||||
: canEdit(req.user)
|
||||
? {}
|
||||
: { status: 'PUBLISHED' as const };
|
||||
const [spaces, allSections, articles] = await Promise.all([
|
||||
prisma.space.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.section.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.article.findMany({
|
||||
where: { status: 'PUBLISHED' },
|
||||
where,
|
||||
orderBy: [{ order: 'asc' }, { title: 'asc' }],
|
||||
include: { assets: { select: { size: true } } },
|
||||
}),
|
||||
]);
|
||||
// Гостю не показываем даже названия разделов, в которых нет публичных статей
|
||||
const used = new Set(articles.map((a) => a.sectionId));
|
||||
const sections = req.user ? allSections : allSections.filter((s) => used.has(s.id));
|
||||
const body: TreeResponse = {
|
||||
spaces: spaces.map(toSpaceDto),
|
||||
spaces: req.user || sections.length ? spaces.map(toSpaceDto) : [],
|
||||
sections: sections.map(toSectionDto),
|
||||
articles: articles.map(toListItem),
|
||||
};
|
||||
@@ -72,7 +83,9 @@ contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
author: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
if (!art || art.status !== 'PUBLISHED') throw new HttpError(404, 'Статья не найдена');
|
||||
if (!art || (art.status !== 'PUBLISHED' && !canEdit(req.user))) throw new HttpError(404, 'Статья не найдена');
|
||||
// Закрытая статья без входа: 401, клиент покажет экран входа
|
||||
if (!req.user && art.visibility !== 'PUBLIC') throw new HttpError(401, 'Нужно войти');
|
||||
|
||||
// Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье
|
||||
const { figures, toc } = renderMarkdown(art.bodyMd);
|
||||
@@ -98,5 +111,5 @@ contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
// Поиск. Пустой запрос: пустой ответ (подсказки рисует клиент).
|
||||
contentRouter.get('/search', async (req, res) => {
|
||||
const q = String(req.query.q ?? '').slice(0, 100);
|
||||
res.json(await search(q, false));
|
||||
res.json(await search(q, !req.user));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// Личные данные пользователя: избранное и недавно открытые.
|
||||
// На устройстве они хранятся локально (работают без сети), а здесь синхронизируются между устройствами.
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { requireAuth } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
|
||||
export const meRouter = Router();
|
||||
meRouter.use(requireAuth);
|
||||
|
||||
meRouter.get('/state', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const [favs, recent] = await Promise.all([
|
||||
prisma.favorite.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, include: { article: { select: { slug: true } } } }),
|
||||
prisma.recentView.findMany({ where: { userId }, orderBy: { viewedAt: 'desc' }, take: 12, include: { article: { select: { slug: true } } } }),
|
||||
]);
|
||||
res.json({
|
||||
favorites: favs.map((f) => f.article.slug),
|
||||
recent: recent.map((r) => ({ slug: r.article.slug, at: r.viewedAt.getTime() })),
|
||||
});
|
||||
});
|
||||
|
||||
const slugs = z.object({ slugs: z.array(z.string().max(200)).max(500) });
|
||||
|
||||
// Клиент присылает полный список избранного: сервер приводит своё к нему
|
||||
meRouter.put('/favorites', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const body = slugs.parse(req.body);
|
||||
const articles = await prisma.article.findMany({ where: { slug: { in: body.slugs } }, select: { id: true } });
|
||||
const ids = articles.map((a) => a.id);
|
||||
await prisma.$transaction([
|
||||
prisma.favorite.deleteMany({ where: { userId, articleId: { notIn: ids } } }),
|
||||
prisma.favorite.createMany({ data: ids.map((articleId) => ({ userId, articleId })), skipDuplicates: true }),
|
||||
]);
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
meRouter.post('/recent', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const { slug } = z.object({ slug: z.string().max(200) }).parse(req.body);
|
||||
const article = await prisma.article.findUnique({ where: { slug }, select: { id: true } });
|
||||
if (article) {
|
||||
await prisma.recentView.upsert({
|
||||
where: { userId_articleId: { userId, articleId: article.id } },
|
||||
create: { userId, articleId: article.id },
|
||||
update: { viewedAt: new Date() },
|
||||
});
|
||||
}
|
||||
res.status(204).end();
|
||||
});
|
||||
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 |
+51
-11
@@ -1,12 +1,17 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { lazy, Suspense, useEffect } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Screen } from './components/Shell';
|
||||
import { BackLink, Notice } from './components/ui';
|
||||
import { pushFavorites, useAuth } from './lib/auth';
|
||||
import { useFavorites } from './lib/store';
|
||||
import { useTheme } from './lib/theme';
|
||||
import { ArticlePage } from './pages/Article';
|
||||
import { CheatSheetPage } from './pages/CheatSheet';
|
||||
import { FavoritesPage } from './pages/Favorites';
|
||||
import { HomePage } from './pages/Home';
|
||||
import { InvitePage, LoginPage } from './pages/Login';
|
||||
import { OfflinePage } from './pages/OfflinePage';
|
||||
import { SearchPage } from './pages/Search';
|
||||
import { SectionPage } from './pages/Section';
|
||||
|
||||
@@ -27,19 +32,54 @@ function NotFound() {
|
||||
export function App() {
|
||||
// Тема применяется один раз здесь: вешает data-theme на <html>
|
||||
useTheme();
|
||||
const { user, loading } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
const { favs } = useFavorites();
|
||||
|
||||
// Любой запрос ответил 401 (сессия кончилась): перепроверяем, кто вошёл
|
||||
useEffect(() => {
|
||||
const onUnauthorized = () => void qc.invalidateQueries({ queryKey: ['me'] });
|
||||
window.addEventListener('kb:unauthorized', onUnauthorized);
|
||||
return () => window.removeEventListener('kb:unauthorized', onUnauthorized);
|
||||
}, [qc]);
|
||||
|
||||
// Избранное живёт на устройстве; у вошедшего пользователя копия уходит на сервер
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const id = setTimeout(() => void pushFavorites(favs), 800);
|
||||
return () => clearTimeout(id);
|
||||
}, [favs, user]);
|
||||
|
||||
if (loading) return <div className="splash" aria-busy="true" />;
|
||||
|
||||
// Без входа доступны только экран входа, приглашение и публичные статьи
|
||||
if (!user) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<LoginPage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,7 +4,9 @@ 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';
|
||||
import { UserMenu } from './UserMenu';
|
||||
|
||||
export type Tab = 'home' | 'search' | 'cheat' | 'fav';
|
||||
|
||||
@@ -33,7 +35,7 @@ export function TabBar({ active }: { active: Tab }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
export function Sidebar() {
|
||||
const nav = useNav();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { pathname } = useLocation();
|
||||
@@ -67,6 +69,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">
|
||||
@@ -88,7 +93,7 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
{footer}
|
||||
<UserMenu compact />
|
||||
<div className="sidebar-foot-label">Тема</div>
|
||||
<div className="segmented segmented--3" role="group" aria-label="Тема">
|
||||
{THEME_ORDER.map((t) => (
|
||||
@@ -127,6 +132,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)}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Блок «кто вошёл»: имя, роль, ссылки на управление и выход.
|
||||
// В макете его нет: добавлен в стиле списков, иначе негде выйти и открыть админку.
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ROLE_LABEL } from '@kb/shared';
|
||||
import { useAuth, useAuthActions } from '../lib/auth';
|
||||
|
||||
export function UserMenu({ compact }: { compact?: boolean }) {
|
||||
const { user, isEditor, isAdmin } = useAuth();
|
||||
const { logout } = useAuthActions();
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className={compact ? 'usermenu usermenu--compact' : 'usermenu list'}>
|
||||
<div className="usermenu-who list-row">
|
||||
<span className="avatar" aria-hidden="true">
|
||||
{user.name
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]?.toUpperCase())
|
||||
.join('')}
|
||||
</span>
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">{user.name}</span>
|
||||
<span className="list-row-sub">{ROLE_LABEL[user.role]}</span>
|
||||
</span>
|
||||
</div>
|
||||
{isEditor ? (
|
||||
<Link to="/new" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Новая статья</span>
|
||||
</Link>
|
||||
) : null}
|
||||
{isAdmin ? (
|
||||
<Link to="/admin" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Управление</span>
|
||||
</Link>
|
||||
) : null}
|
||||
<button type="button" className="list-row usermenu-link usermenu-btn" onClick={() => void logout()}>
|
||||
<span className="list-row-main list-row-title">Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+11
-2
@@ -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 {
|
||||
@@ -31,13 +32,21 @@ export async function api<T>(path: string, init?: RequestInit & { json?: unknown
|
||||
if (res.status === 204) return undefined as T;
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
// 401 на обычном запросе = сессия кончилась. Сам запрос «кто я» не считаем, иначе получится замкнутый круг.
|
||||
if (res.status === 401 && !path.startsWith('/auth/')) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
throw new ApiError(res.status, (data as { error?: string } | null)?.error ?? `Ошибка ${res.status}`);
|
||||
}
|
||||
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,109 @@
|
||||
// Кто вошёл. Сервер хранит сессию в httpOnly-cookie, здесь только узнаём пользователя.
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Role, UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from './api';
|
||||
import { clearPrivateCaches } from './offline';
|
||||
import { getStored, type RecentItem, setStored, useStored } from './store';
|
||||
|
||||
const USER_KEY = 'kb-user';
|
||||
|
||||
/**
|
||||
* Состояние входа:
|
||||
* loading: ещё спрашиваем сервер;
|
||||
* user: вошёл (или нет сети, но на этом устройстве уже входили: тогда читаем сохранённое);
|
||||
* null: не вошёл.
|
||||
*/
|
||||
export function useAuth() {
|
||||
const [cached, setCached] = useStored<UserDto | null>(USER_KEY, null);
|
||||
const q = useQuery({
|
||||
queryKey: ['me'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/me');
|
||||
return user;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) return null;
|
||||
throw e; // нет сети: оставляем сохранённого пользователя
|
||||
}
|
||||
},
|
||||
staleTime: 5 * 60_000,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (q.data === undefined) return;
|
||||
if (q.data === null && cached) {
|
||||
// Сессия кончилась: убираем с устройства сохранённые закрытые статьи
|
||||
setCached(null);
|
||||
void clearPrivateCaches();
|
||||
} else if (q.data && JSON.stringify(q.data) !== JSON.stringify(cached)) {
|
||||
setCached(q.data);
|
||||
}
|
||||
}, [q.data, cached, setCached]);
|
||||
|
||||
// Если на устройстве уже входили, не ждём ответа сервера: сразу показываем приложение
|
||||
// (так оно открывается мгновенно и работает без сети). Сервер ответит 401: покажем экран входа.
|
||||
const user = q.data !== undefined ? q.data : (cached ?? (q.isError ? null : undefined));
|
||||
return {
|
||||
user: user ?? null,
|
||||
loading: user === undefined,
|
||||
isEditor: user?.role === 'EDITOR' || user?.role === 'ADMIN',
|
||||
isAdmin: user?.role === 'ADMIN',
|
||||
};
|
||||
}
|
||||
|
||||
export const roleAtLeast = (role: Role | undefined, min: Role) =>
|
||||
!!role && ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(role) >= ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(min);
|
||||
|
||||
export function useAuthActions() {
|
||||
const qc = useQueryClient();
|
||||
return {
|
||||
/** После входа: запоминаем пользователя и перезапрашиваем всё (теперь видны закрытые статьи). */
|
||||
async onLogin(user: UserDto) {
|
||||
setStored(USER_KEY, user);
|
||||
qc.setQueryData(['me'], user);
|
||||
await syncPersonal();
|
||||
await qc.invalidateQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
async logout() {
|
||||
await api('/auth/logout', { method: 'POST' }).catch(() => undefined);
|
||||
setStored(USER_KEY, null);
|
||||
await clearPrivateCaches();
|
||||
qc.setQueryData(['me'], null);
|
||||
qc.removeQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- Синхронизация избранного и недавних между устройствами ----------
|
||||
interface PersonalState {
|
||||
favorites: string[];
|
||||
recent: RecentItem[];
|
||||
}
|
||||
|
||||
/** Объединяет локальные данные с серверными (ничего не теряя) и отправляет результат на сервер. */
|
||||
export async function syncPersonal() {
|
||||
try {
|
||||
const remote = await api<PersonalState>('/me/state');
|
||||
const favs = [...new Set([...getStored<string[]>('kb-fav', []), ...remote.favorites])];
|
||||
setStored('kb-fav', favs);
|
||||
const recent = new Map<string, number>();
|
||||
for (const r of [...remote.recent, ...getStored<RecentItem[]>('kb-recent', [])]) {
|
||||
recent.set(r.slug, Math.max(recent.get(r.slug) ?? 0, r.at));
|
||||
}
|
||||
setStored(
|
||||
'kb-recent',
|
||||
[...recent].map(([slug, at]) => ({ slug, at })).sort((a, b) => b.at - a.at).slice(0, 12),
|
||||
);
|
||||
await pushFavorites(favs);
|
||||
} catch {
|
||||
// нет сети: синхронизируемся в следующий раз
|
||||
}
|
||||
}
|
||||
|
||||
export const pushFavorites = (slugs: string[]) =>
|
||||
api('/me/favorites', { method: 'PUT', json: { slugs } }).catch(() => undefined);
|
||||
|
||||
export const pushRecentView = (slug: string) =>
|
||||
api('/me/recent', { method: 'POST', json: { slug } }).catch(() => undefined);
|
||||
@@ -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,12 +3,16 @@ 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';
|
||||
import { ApiError, useArticle } from '../lib/api';
|
||||
import { fileExt, formatBytes, formatDate, num2 } from '../lib/format';
|
||||
import { pushRecentView, useAuth } from '../lib/auth';
|
||||
import { pushRecent, useFavorites } from '../lib/store';
|
||||
import { LoginPage } from './Login';
|
||||
import { useTheme } from '../lib/theme';
|
||||
import { useNav } from '../lib/tree';
|
||||
|
||||
@@ -51,6 +55,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);
|
||||
@@ -58,9 +63,13 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
const listItem = nav.article(slug);
|
||||
const section = nav.sectionOf(art ?? listItem);
|
||||
|
||||
const { user } = useAuth();
|
||||
const artSlug = art?.slug;
|
||||
useEffect(() => {
|
||||
if (art) pushRecent(art.slug);
|
||||
}, [art]);
|
||||
if (!artSlug) return;
|
||||
pushRecent(artSlug);
|
||||
if (user) void pushRecentView(artSlug);
|
||||
}, [artSlug, user]);
|
||||
|
||||
// При переходе на другую статью начинаем чтение сверху
|
||||
useEffect(() => {
|
||||
@@ -102,6 +111,9 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
</nav>
|
||||
);
|
||||
|
||||
// Закрытая статья, а пользователь не вошёл: показываем экран входа (после входа статья откроется)
|
||||
if (!art && error instanceof ApiError && error.status === 401) return <LoginPage />;
|
||||
|
||||
if (!art) {
|
||||
const notFound = error instanceof ApiError && error.status === 404;
|
||||
return (
|
||||
@@ -184,7 +196,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 +204,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>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { UserMenu } from '../components/UserMenu';
|
||||
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { formatRecent } from '../lib/format';
|
||||
@@ -180,6 +181,22 @@ 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>
|
||||
<div className="home-more">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { type FormEvent, useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { ROLE_LABEL, type Role, type UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuthActions } from '../lib/auth';
|
||||
|
||||
function AuthFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="login">
|
||||
<div className="hazard hazard--lg" aria-hidden="true" />
|
||||
<main className="login-main">
|
||||
<div>
|
||||
<div className="login-site">wiki.suchtech.ru</div>
|
||||
<h1 className="login-title">Памятки монтажника</h1>
|
||||
</div>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordField({ value, onChange, label, autoComplete }: { value: string; onChange: (v: string) => void; label: string; autoComplete: string }) {
|
||||
const [shown, setShown] = useState(false);
|
||||
return (
|
||||
<label className="field">
|
||||
<span className="field-label">{label}</span>
|
||||
<span className="field-box">
|
||||
<input
|
||||
className="field-input"
|
||||
type={shown ? 'text' : 'password'}
|
||||
autoComplete={autoComplete}
|
||||
required
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="field-toggle" onClick={() => setShown(!shown)} aria-pressed={shown}>
|
||||
{shown ? 'Скрыть' : 'Показать'}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Remember({ on, toggle }: { on: boolean; toggle: () => void }) {
|
||||
return (
|
||||
<button type="button" role="switch" aria-checked={on} className="remember" onClick={toggle}>
|
||||
<span className={on ? 'bigbox bigbox--on' : 'bigbox'} aria-hidden="true" />
|
||||
<span>
|
||||
<span className="remember-title">Запомнить устройство</span>
|
||||
<span className="remember-text">Не спрашивать пароль 90 дней</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [remember, setRemember] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [inviteLink, setInviteLink] = useState('');
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/login', { method: 'POST', json: { email, password, remember } });
|
||||
await onLogin(user);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось войти');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// «Есть ссылка-приглашение»: принимаем и полную ссылку, и один код из неё
|
||||
const openInvite = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const token = inviteLink.trim().split('/').filter(Boolean).pop();
|
||||
if (token) navigate(`/invite/${token}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="username"
|
||||
placeholder="ivanov@suchtech.ru"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<PasswordField label="Пароль" autoComplete="current-password" value={password} onChange={setPassword} />
|
||||
<Remember on={remember} toggle={() => setRemember(!remember)} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Входим…' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{inviteOpen ? (
|
||||
<form className="login-form" onSubmit={openInvite}>
|
||||
<label className="field">
|
||||
<span className="field-label">Ссылка-приглашение</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
autoFocus
|
||||
placeholder="Вставьте ссылку от администратора"
|
||||
value={inviteLink}
|
||||
onChange={(e) => setInviteLink(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="btn btn--outline btn--lg">
|
||||
Продолжить
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="login-link" onClick={() => setInviteOpen(true)}>
|
||||
Есть ссылка-приглашение
|
||||
</button>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvitePage() {
|
||||
const { token = '' } = useParams();
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [role, setRole] = useState<Role | null>(null);
|
||||
const [invalid, setInvalid] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api<{ role: Role }>(`/auth/invite/${encodeURIComponent(token)}`)
|
||||
.then((r) => setRole(r.role))
|
||||
.catch((e) => setInvalid(e instanceof ApiError ? e.message : 'Не удалось проверить ссылку'));
|
||||
}, [token]);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>(`/auth/invite/${encodeURIComponent(token)}`, {
|
||||
method: 'POST',
|
||||
json: { name, email, password },
|
||||
});
|
||||
await onLogin(user);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось зарегистрироваться');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
{invalid ? (
|
||||
<>
|
||||
<div className="form-error" role="alert">
|
||||
{invalid}
|
||||
</div>
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={() => navigate('/')}>
|
||||
На экран входа
|
||||
</button>
|
||||
</>
|
||||
) : !role ? (
|
||||
<div className="login-note">Проверяем приглашение…</div>
|
||||
) : (
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<div className="login-note">
|
||||
Вас пригласили с ролью «{ROLE_LABEL[role]}». Придумайте пароль, чтобы входить с любого устройства.
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">Имя и фамилия</span>
|
||||
<input className="field-input field-input--box" autoComplete="name" required minLength={2} value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input className="field-input field-input--box" type="email" inputMode="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</label>
|
||||
<PasswordField label="Пароль (не короче 8 символов)" autoComplete="new-password" value={password} onChange={setPassword} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Создаём…' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
@@ -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,358 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Вход ---------- */
|
||||
.splash {
|
||||
min-height: 100dvh;
|
||||
background: var(--bg);
|
||||
}
|
||||
.hazard {
|
||||
height: 10px;
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 10px, var(--brand-ink) 10px 20px);
|
||||
}
|
||||
.hazard--lg {
|
||||
height: calc(14px + env(safe-area-inset-top));
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 12px, var(--brand-ink) 12px 24px);
|
||||
}
|
||||
.login {
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.login-main {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: var(--sp-9);
|
||||
padding: var(--sp-12) var(--sp-10);
|
||||
}
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-9);
|
||||
}
|
||||
.login-site {
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.login-title {
|
||||
font-size: var(--fs-32);
|
||||
font-weight: 700;
|
||||
line-height: 1.05;
|
||||
letter-spacing: -0.02em;
|
||||
margin-top: var(--sp-3);
|
||||
}
|
||||
.login-note {
|
||||
font-size: var(--fs-16);
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.login-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.field-label {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.field-box,
|
||||
.field-input--box {
|
||||
height: var(--h-field);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 var(--sp-3) 0 var(--sp-8);
|
||||
}
|
||||
.field-box:focus-within,
|
||||
.field-input--box:focus {
|
||||
box-shadow: 0 0 0 var(--focus-ring) var(--hl);
|
||||
outline: 0;
|
||||
}
|
||||
.field-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.field-input--box {
|
||||
flex: none;
|
||||
padding: 0 var(--sp-8);
|
||||
border: 2px solid var(--ink);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-input::placeholder {
|
||||
color: var(--ink2);
|
||||
}
|
||||
.field-toggle {
|
||||
flex: none;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-6);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
color: var(--ink2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.remember {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-7);
|
||||
min-height: var(--h-btn);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--ink);
|
||||
}
|
||||
.remember-title {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
}
|
||||
.remember-text {
|
||||
display: block;
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.bigbox {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--sf);
|
||||
}
|
||||
.bigbox--on {
|
||||
border-color: var(--grnS);
|
||||
background: var(--grnS);
|
||||
}
|
||||
.bigbox--on::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 9px;
|
||||
top: 3px;
|
||||
width: 8px;
|
||||
height: 15px;
|
||||
border: solid var(--on-strong);
|
||||
border-width: 0 3px 3px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.form-error {
|
||||
padding: var(--sp-6) var(--sp-7);
|
||||
border: 2px solid var(--redS);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Блок пользователя ---------- */
|
||||
.avatar {
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: var(--sf2);
|
||||
border: var(--bw) solid var(--ln);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 700;
|
||||
}
|
||||
.usermenu-btn {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font-size: inherit;
|
||||
}
|
||||
.usermenu-link {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin: calc(var(--sp-4) * -1) calc(var(--sp-4) * -1) var(--sp-2);
|
||||
}
|
||||
.usermenu--compact .list-row {
|
||||
min-height: var(--h-chip);
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border: 0;
|
||||
border-radius: var(--r-sm);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.usermenu--compact .usermenu-who {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact .avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.badge-draft {
|
||||
flex: none;
|
||||
padding: var(--sp-1) var(--sp-4);
|
||||
border-radius: var(--r-tag);
|
||||
border: var(--bw) solid var(--ambln);
|
||||
background: var(--ambbg);
|
||||
color: var(--amb);
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
+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