Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
79d49181a6 | ||
|
|
f2be0df17a | ||
|
|
0467281dc5 | ||
|
|
bca00cb103 | ||
|
|
59be0307cc | ||
|
|
be9be3f79e | ||
|
|
768daf7c5f | ||
|
|
aa04c1f5db |
@@ -18,3 +18,4 @@ apps/api/uploads/
|
||||
/kb-seed.zip
|
||||
/REVIEW.md
|
||||
/PROMPT_CLAUDE_DESIGN.md
|
||||
scripts/_*
|
||||
|
||||
@@ -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);
|
||||
@@ -1,6 +1,9 @@
|
||||
import express, { type ErrorRequestHandler } from 'express';
|
||||
import type { HealthResponse } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { contentRouter } from './routes/content.js';
|
||||
|
||||
export function createApp() {
|
||||
const app = express();
|
||||
@@ -17,12 +20,37 @@ export function createApp() {
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Загруженные файлы. Имена картинок не меняются при замене содержимого редко,
|
||||
// поэтому кешируем на сутки, а дальше браузер перепроверяет по ETag.
|
||||
app.use(
|
||||
'/uploads',
|
||||
express.static(env.UPLOADS_DIR, {
|
||||
index: false,
|
||||
dotfiles: 'deny',
|
||||
maxAge: '1d',
|
||||
setHeaders(res, file) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
// Исходники (PDF/DOCX) всегда скачиваются, а не открываются в браузере
|
||||
if (!/\.(webp|png|jpe?g|gif)$/i.test(file)) res.setHeader('Content-Disposition', 'attachment');
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use('/uploads', (_req, res) => {
|
||||
res.status(404).json({ error: 'Файл не найден' });
|
||||
});
|
||||
|
||||
app.use('/api', contentRouter);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: 'Не найдено' });
|
||||
});
|
||||
|
||||
// Единая обработка ошибок: клиенту короткое сообщение, подробности в лог.
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
if (err instanceof HttpError) {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
return;
|
||||
}
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Ошибка с HTTP-кодом: бросаем из обработчика, общий обработчик в app.ts превращает её в ответ. */
|
||||
export class HttpError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
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 { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { search } from '../search.js';
|
||||
|
||||
export const contentRouter = Router();
|
||||
|
||||
export const toSpaceDto = (s: Space): SpaceDto => ({ id: s.id, name: s.name, slug: s.slug, icon: s.icon, order: s.order });
|
||||
|
||||
export const toSectionDto = (s: Section): SectionDto => ({
|
||||
id: s.id,
|
||||
spaceId: s.spaceId,
|
||||
name: s.name,
|
||||
slug: s.slug,
|
||||
code: s.code,
|
||||
color: s.color as PlaqueColor,
|
||||
icon: s.icon,
|
||||
order: s.order,
|
||||
});
|
||||
|
||||
type ArticleWithAssets = Article & { assets: { size: number }[] };
|
||||
|
||||
export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({
|
||||
id: a.id,
|
||||
slug: a.slug,
|
||||
title: a.title,
|
||||
summary: a.summary,
|
||||
sectionId: a.sectionId,
|
||||
order: a.order,
|
||||
tags: a.tags,
|
||||
equipment: a.equipment,
|
||||
docCode: a.docCode,
|
||||
pinned: a.pinned,
|
||||
status: a.status,
|
||||
visibility: a.visibility,
|
||||
version: a.version,
|
||||
updatedAt: a.updatedAt.toISOString(),
|
||||
imageCount: a.assets.length,
|
||||
bytes: a.assets.reduce((n, x) => n + x.size, 0),
|
||||
});
|
||||
|
||||
// Всё дерево одним запросом: пространства, разделы и список статей (без текста).
|
||||
// Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны,
|
||||
// а для офлайна один ответ кешировать проще.
|
||||
contentRouter.get('/tree', async (_req, res) => {
|
||||
const [spaces, sections, articles] = await Promise.all([
|
||||
prisma.space.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.section.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.article.findMany({
|
||||
where: { status: 'PUBLISHED' },
|
||||
orderBy: [{ order: 'asc' }, { title: 'asc' }],
|
||||
include: { assets: { select: { size: true } } },
|
||||
}),
|
||||
]);
|
||||
const body: TreeResponse = {
|
||||
spaces: spaces.map(toSpaceDto),
|
||||
sections: sections.map(toSectionDto),
|
||||
articles: articles.map(toListItem),
|
||||
};
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
const art = await prisma.article.findUnique({
|
||||
where: { slug: req.params.slug },
|
||||
include: {
|
||||
assets: { select: { size: true } },
|
||||
attachments: { orderBy: { createdAt: 'asc' } },
|
||||
author: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
if (!art || art.status !== 'PUBLISHED') throw new HttpError(404, 'Статья не найдена');
|
||||
|
||||
// Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье
|
||||
const { figures, toc } = renderMarkdown(art.bodyMd);
|
||||
const cheat = art.pinned ? parseCheatSheet(art.bodyMd) : null;
|
||||
const body: ArticleDto = {
|
||||
...toListItem(art),
|
||||
bodyMd: art.bodyMd,
|
||||
bodyHtml: art.bodyHtml,
|
||||
attachments: art.attachments.map((a) => ({
|
||||
id: a.id,
|
||||
filename: a.filename,
|
||||
url: `/uploads/${a.path}`,
|
||||
size: a.size,
|
||||
})),
|
||||
images: figures.flatMap((f) => [f.thumb, f.full]),
|
||||
authorName: art.author?.name ?? null,
|
||||
toc,
|
||||
cheat: cheat?.ok ? cheat : null,
|
||||
};
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Поиск. Пустой запрос: пустой ответ (подсказки рисует клиент).
|
||||
contentRouter.get('/search', async (req, res) => {
|
||||
const q = String(req.query.q ?? '').slice(0, 100);
|
||||
res.json(await search(q, false));
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
// Поиск: PostgreSQL full-text (конфигурация russian) + pg_trgm.
|
||||
//
|
||||
// Статья попадает в выдачу, если КАЖДОЕ слово запроса нашлось одним из способов:
|
||||
// 1. полнотекстовый поиск по началу слова («узип», «шкос»: с учётом русских окончаний);
|
||||
// 2. подстрока в нормализованном тексте («2273» внутри «2273-245»);
|
||||
// 3. подстрока в «сжатом» тексте без пробелов и дефисов («MG12» → «MG-12», «ral 7024» → «RAL7024»).
|
||||
// Если так ничего не нашлось, включается поиск с опечатками (похожесть триграмм).
|
||||
//
|
||||
// Порядок выдачи: заголовок > «Главное» > теги и оборудование > остальной текст.
|
||||
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { compactSearch, normalizeSearch, type Highlight, type SearchResponse } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import type { StoredFact } from './services/articles.js';
|
||||
|
||||
const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const likeEsc = (s: string) => s.replace(/[\\%_]/g, '\\$&');
|
||||
|
||||
/** Слова запроса: буквы и цифры, десятичное число целиком. «патч-корд sip 1,2» → [патч, корд, sip, «1,2»]. */
|
||||
export function tokenize(q: string): string[] {
|
||||
return [...new Set(normalizeSearch(q).match(/\d+(?:,\d+)+|[\p{L}\p{N}]+/gu) ?? [])].slice(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Регулярное выражение для подсветки совпадений в исходном тексте (с заглавными буквами, «ё» и дефисами).
|
||||
* Между символами слова допускаем пробел или дефис: так «mg12» подсветит «MG-12».
|
||||
*/
|
||||
export function highlightRegex(q: string): RegExp | null {
|
||||
const tokens = tokenize(q);
|
||||
const whole = compactSearch(q);
|
||||
// Одиночные буквы и цифры не подсвечиваем: «м» из «1,2 м» раскрасила бы весь текст
|
||||
const variants = [...new Set([whole, ...tokens])].filter((v) => v.length >= 2).sort((a, b) => b.length - a.length);
|
||||
if (!variants.length) return null;
|
||||
const pattern = variants
|
||||
.map((t) =>
|
||||
[...t]
|
||||
.map((ch) => (ch === 'е' ? '[её]' : ch === ',' ? '[.,]' : esc(ch)))
|
||||
// Разделители допускаем только в «артикулах» (есть цифра), иначе слова склеятся через пробел
|
||||
.join(/\d/.test(t) ? '[\\s\\-–—.]?' : ''),
|
||||
)
|
||||
.join('|');
|
||||
return new RegExp(pattern, 'giu');
|
||||
}
|
||||
|
||||
export function highlight(text: string, re: RegExp | null): Highlight[] {
|
||||
if (!re || !text) return [{ t: text, hit: false }];
|
||||
const out: Highlight[] = [];
|
||||
let last = 0;
|
||||
// matchAll продолжает с re.lastIndex: сбрасываем, иначе после exec() часть совпадений потеряется
|
||||
re.lastIndex = 0;
|
||||
for (const m of text.matchAll(re)) {
|
||||
const at = m.index ?? 0;
|
||||
if (!m[0]) continue;
|
||||
if (at > last) out.push({ t: text.slice(last, at), hit: false });
|
||||
out.push({ t: m[0], hit: true });
|
||||
last = at + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push({ t: text.slice(last), hit: false });
|
||||
return out.length ? out : [{ t: text, hit: false }];
|
||||
}
|
||||
|
||||
const hasHit = (h: Highlight[]) => h.some((x) => x.hit);
|
||||
|
||||
/** Все слова запроса есть в тексте (как подстрока или в сжатом виде)? */
|
||||
function matchesAll(text: string, tokens: string[], whole: string): boolean {
|
||||
const norm = normalizeSearch(text);
|
||||
const compact = compactSearch(text);
|
||||
if (whole.length >= 3 && compact.includes(whole)) return true;
|
||||
return tokens.every((t) => norm.includes(t) || compact.includes(t));
|
||||
}
|
||||
|
||||
/** Кусок текста вокруг первого совпадения, чтобы было понятно, где нашлось. */
|
||||
function snippet(lines: string[], re: RegExp | null, fallback: string): string {
|
||||
if (re) {
|
||||
for (const line of lines) {
|
||||
re.lastIndex = 0;
|
||||
const m = re.exec(line);
|
||||
if (!m) continue;
|
||||
const start = Math.max(0, m.index - 50);
|
||||
const end = Math.min(line.length, m.index + m[0].length + 90);
|
||||
return (start > 0 ? '…' : '') + line.slice(start, end).trim() + (end < line.length ? '…' : '');
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
interface Row {
|
||||
id: string;
|
||||
slug: string;
|
||||
title: string;
|
||||
summary: string;
|
||||
tags: string[];
|
||||
equipment: string[];
|
||||
docCode: string | null;
|
||||
pinned: boolean;
|
||||
sectionId: string;
|
||||
sectionName: string;
|
||||
bodyMd: string;
|
||||
facts: StoredFact[];
|
||||
rank: number;
|
||||
sim: number;
|
||||
}
|
||||
|
||||
const stripMd = (s: string) => s.replace(/\*\*/g, '');
|
||||
|
||||
export async function search(q: string, visibleOnly: boolean): Promise<SearchResponse> {
|
||||
const tokens = tokenize(q);
|
||||
const whole = compactSearch(q);
|
||||
if (!tokens.length) return { q, facts: [], articles: [] };
|
||||
|
||||
// Условие на каждое слово: подстрока, сжатая подстрока или (для слов от 3 букв) полнотекстовое
|
||||
// совпадение по началу слова с учётом окончаний: «стойки» найдёт «стойка».
|
||||
const perToken = tokens.map((t) => {
|
||||
const like = `%${likeEsc(t)}%`;
|
||||
const fts = /^\p{L}{3,}$/u.test(t)
|
||||
? Prisma.sql` OR a."searchVector" @@ to_tsquery('russian', ${`${t}:*`})`
|
||||
: Prisma.empty;
|
||||
return Prisma.sql`(a."searchNorm" LIKE ${like} OR a."searchCompact" LIKE ${like}${fts})`;
|
||||
});
|
||||
const allTokens = Prisma.join(perToken, ' AND ');
|
||||
// Полнотекстовый запрос для ранжирования (веса A–D): «патч:* | корд:* | sip:*»
|
||||
const words = tokens.filter((t) => /^[\p{L}\p{N}]{2,}$/u.test(t));
|
||||
const tsq = words.length ? words.map((t) => `${t}:*`).join(' | ') : 'zzzzzz';
|
||||
const qn = normalizeSearch(q);
|
||||
const publicOnly = visibleOnly ? Prisma.sql`AND a.visibility = 'PUBLIC'` : Prisma.empty;
|
||||
|
||||
const select = Prisma.sql`
|
||||
SELECT a.id, a.slug, a.title, a.summary, a.tags, a.equipment, a."docCode", a.pinned, a."sectionId",
|
||||
s.name AS "sectionName", a."bodyMd", a.facts,
|
||||
ts_rank(a."searchVector", to_tsquery('russian', ${tsq}))::float8 AS rank,
|
||||
word_similarity(${qn}, a."searchNorm")::float8 AS sim
|
||||
FROM "Article" a JOIN "Section" s ON s.id = a."sectionId"
|
||||
WHERE a.status = 'PUBLISHED' ${publicOnly}`;
|
||||
|
||||
let rows = await prisma.$queryRaw<Row[]>`
|
||||
${select} AND (
|
||||
(${allTokens})
|
||||
OR (${whole.length >= 3} AND a."searchCompact" LIKE ${`%${likeEsc(whole)}%`})
|
||||
) LIMIT 60`;
|
||||
|
||||
// Ничего не нашли: пробуем с опечатками («шкоос», «узпи»)
|
||||
let fuzzy = false;
|
||||
if (!rows.length && qn.length >= 3) {
|
||||
fuzzy = true;
|
||||
rows = await prisma.$queryRaw<Row[]>`
|
||||
${select} AND word_similarity(${qn}, a."searchNorm") > 0.45
|
||||
ORDER BY sim DESC LIMIT 10`;
|
||||
}
|
||||
|
||||
const re = fuzzy ? null : highlightRegex(q);
|
||||
|
||||
const scored = rows.map((r) => {
|
||||
const meta = [...r.tags, ...r.equipment, r.docCode ?? ''].join('\n');
|
||||
const facts = (r.facts ?? []).map((f) => `${f.label} ${stripMd(f.value)}`).join('\n');
|
||||
let score = r.rank * 10 + r.sim;
|
||||
if (matchesAll(r.title, tokens, whole)) score += 100;
|
||||
if (matchesAll(`${facts}\n${r.summary}`, tokens, whole)) score += 40;
|
||||
if (matchesAll(meta, tokens, whole)) score += 20;
|
||||
// Шпаргалка содержит всё подряд: чуть опускаем её, чтобы первой шла статья-источник
|
||||
if (r.pinned) score -= 15;
|
||||
return { r, score };
|
||||
});
|
||||
scored.sort((a, b) => b.score - a.score || a.r.title.localeCompare(b.r.title, 'ru'));
|
||||
|
||||
const titles = new Map(
|
||||
(await prisma.article.findMany({ select: { slug: true, title: true } })).map((a) => [a.slug, a.title]),
|
||||
);
|
||||
|
||||
const articles = scored.slice(0, 20).map(({ r }) => {
|
||||
// Текст статьи без разметки, построчно: ищем строку с совпадением
|
||||
const lines = [
|
||||
...(r.facts ?? []).map((f) => `${f.label ? `${f.label}: ` : ''}${stripMd(f.value)}`),
|
||||
r.equipment.join(', '),
|
||||
r.tags.join(', '),
|
||||
r.docCode ?? '',
|
||||
...r.bodyMd
|
||||
.split('\n')
|
||||
.map((l) =>
|
||||
l
|
||||
.replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')
|
||||
.replace(/\[\[[^\]]+\]\]/g, '')
|
||||
.replace(/^[\s>#|:-]+|\*\*|- \[[ x]\] /g, '')
|
||||
.replace(/\s*\|\s*/g, ' · ')
|
||||
.trim(),
|
||||
),
|
||||
].filter(Boolean);
|
||||
return {
|
||||
slug: r.slug,
|
||||
title: highlight(r.title, re),
|
||||
section: r.sectionName,
|
||||
sectionId: r.sectionId,
|
||||
snippet: highlight(snippet(hasHit(highlight(r.summary, re)) ? [r.summary] : lines, re, r.summary), re),
|
||||
pinned: r.pinned,
|
||||
};
|
||||
});
|
||||
|
||||
// «Цифры»: пункты «Главного» и строки шпаргалки, в которых встречается запрос
|
||||
const facts: SearchResponse['facts'] = [];
|
||||
const seen = new Set<string>();
|
||||
if (!fuzzy) {
|
||||
for (const { r } of scored) {
|
||||
for (const f of r.facts ?? []) {
|
||||
const plain = stripMd(f.value);
|
||||
if (!matchesAll(`${f.label} ${plain}`, tokens, whole)) continue;
|
||||
// Крупно показываем то, что в статье выделено жирным: это и есть «цифра»
|
||||
const bolds = [...f.value.matchAll(/\*\*(.+?)\*\*/g)].map((m) => m[1]!);
|
||||
const big = bolds.length ? bolds.join(' · ') : plain;
|
||||
const small = big === plain ? f.label : f.label ? `${f.label}: ${plain}` : plain;
|
||||
const key = normalizeSearch(`${big}|${f.label}`);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
const links = (f.links?.length ? f.links : [r.slug]).map((slug) => ({ slug, title: titles.get(slug) ?? slug }));
|
||||
facts.push({ value: highlight(big, re), label: highlight(small, re), links, sectionId: r.sectionId, cheat: r.pinned });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { q, facts: facts.slice(0, 12), articles };
|
||||
}
|
||||
+257
-2
@@ -1,2 +1,257 @@
|
||||
// Импорт стартового контента. Реализация появится на этапе 2.
|
||||
console.log('seed: пока пусто');
|
||||
// pnpm seed: импорт стартового контента из kb-seed/.
|
||||
// Скрипт идемпотентный: повторный запуск обновляет записи, а не создаёт дубликаты.
|
||||
//
|
||||
// Что делает:
|
||||
// 1. пространство «АСУПП» и разделы по папкам content/NN-slug
|
||||
// 2. картинки kb-seed/assets → uploads/assets (WebP 1600 + превью 480, без EXIF)
|
||||
// 3. исходники kb-seed/originals → uploads/originals
|
||||
// 4. статьи из content/**/*.md (+ Attachment по полю source)
|
||||
// 5. администратор из ADMIN_EMAIL / ADMIN_PASSWORD
|
||||
// 6. отчёт: битые [[ссылки]], потерянные картинки и исходники
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { assetKey, parseFrontMatter } from '@kb/md';
|
||||
import type { PlaqueColor } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { rerenderAll } from './services/articles.js';
|
||||
import { fileSize, storeImage, uploadPath } from './services/images.js';
|
||||
import { hashPassword } from './services/password.js';
|
||||
|
||||
// Код и цвет плашки раздела: как в макете. Для новых папок код берётся из первых букв названия.
|
||||
const SECTION_STYLE: Record<string, { code: string; color: PlaqueColor }> = {
|
||||
shpargalka: { code: 'ШП', color: 'yellow' },
|
||||
'stoyka-vezda': { code: 'ВВ', color: 'yellow' },
|
||||
'stoyka-shlagbauma': { code: 'ШЛ', color: 'orange' },
|
||||
'optika-vok': { code: 'ВОК', color: 'blue' },
|
||||
ostrov: { code: 'ОБ', color: 'green' },
|
||||
'naves-terminala': { code: 'НТ', color: 'ink' },
|
||||
};
|
||||
|
||||
const IMAGE_EXT = /\.(jpe?g|png|webp|gif|tiff?)$/i;
|
||||
|
||||
async function walk(dir: string): Promise<string[]> {
|
||||
const out: string[] = [];
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return out;
|
||||
}
|
||||
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) out.push(...(await walk(p)));
|
||||
else out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const toPosix = (p: string) => p.split(path.sep).join('/');
|
||||
|
||||
function fallbackCode(name: string): string {
|
||||
return name
|
||||
.split(/[\s/()-]+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]!.toUpperCase())
|
||||
.join('');
|
||||
}
|
||||
|
||||
async function importImages(seedDir: string) {
|
||||
const dir = path.join(seedDir, 'assets');
|
||||
const files = (await walk(dir)).filter((f) => IMAGE_EXT.test(f));
|
||||
let converted = 0;
|
||||
for (const file of files) {
|
||||
const key = assetKey(`assets/${toPosix(path.relative(dir, file))}`)!;
|
||||
const rel = `${key}.webp`;
|
||||
const srcStat = await fs.stat(file);
|
||||
const existing = await prisma.asset.findUnique({ where: { path: rel } });
|
||||
const outStat = await fs.stat(uploadPath(rel)).catch(() => null);
|
||||
// Пропускаем, если уже сконвертировано и исходник с тех пор не менялся
|
||||
if (existing && outStat && outStat.mtimeMs >= srcStat.mtimeMs) continue;
|
||||
|
||||
const img = await storeImage(await fs.readFile(file), key);
|
||||
const data = { mime: 'image/webp', size: img.size, width: img.width, height: img.height };
|
||||
await prisma.asset.upsert({ where: { path: rel }, create: { path: rel, ...data }, update: data });
|
||||
converted++;
|
||||
}
|
||||
return { total: files.length, converted };
|
||||
}
|
||||
|
||||
async function importOriginals(seedDir: string) {
|
||||
const dir = path.join(seedDir, 'originals');
|
||||
const files = await walk(dir);
|
||||
for (const file of files) {
|
||||
const dest = uploadPath(`originals/${toPosix(path.relative(dir, file))}`);
|
||||
await fs.mkdir(path.dirname(dest), { recursive: true });
|
||||
await fs.copyFile(file, dest);
|
||||
}
|
||||
return files.length;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const seedDir = path.resolve(env.SEED_DIR);
|
||||
const contentDir = path.join(seedDir, 'content');
|
||||
console.log(`Импорт из ${seedDir}`);
|
||||
await fs.access(contentDir).catch(() => {
|
||||
throw new Error(`Не найдена папка ${contentDir}. Проверьте SEED_DIR.`);
|
||||
});
|
||||
await fs.mkdir(env.UPLOADS_DIR, { recursive: true });
|
||||
|
||||
// 1. Пространство
|
||||
const space = await prisma.space.upsert({
|
||||
where: { slug: 'asupp' },
|
||||
create: { slug: 'asupp', name: 'АСУПП', icon: 'А', order: 0 },
|
||||
update: {},
|
||||
});
|
||||
|
||||
// 2–3. Файлы
|
||||
const images = await importImages(seedDir);
|
||||
const originals = await importOriginals(seedDir);
|
||||
|
||||
// 4. Статьи
|
||||
const admin = await ensureAdmin();
|
||||
const problems: string[] = [];
|
||||
const mdFiles = (await walk(contentDir)).filter((f) => f.endsWith('.md'));
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
|
||||
for (const file of mdFiles) {
|
||||
const relFile = toPosix(path.relative(contentDir, file));
|
||||
const { meta, body } = parseFrontMatter(await fs.readFile(file, 'utf8'));
|
||||
if (!meta.slug || !meta.title) {
|
||||
problems.push(`${relFile}: нет slug или title в шапке, статья пропущена`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Раздел по папке: «01-stoyka-vezda» → порядок 1, slug stoyka-vezda
|
||||
const folder = relFile.split('/')[0] ?? '';
|
||||
const fm = folder.match(/^(\d+)-(.+)$/);
|
||||
const sectionSlug = fm?.[2] ?? folder;
|
||||
const sectionName = meta.section ?? sectionSlug;
|
||||
const style = SECTION_STYLE[sectionSlug] ?? { code: fallbackCode(sectionName), color: 'ink' as PlaqueColor };
|
||||
const section = await prisma.section.upsert({
|
||||
where: { slug: sectionSlug },
|
||||
create: { slug: sectionSlug, spaceId: space.id, name: sectionName, order: Number(fm?.[1] ?? 0), ...style },
|
||||
// При повторном запуске не затираем то, что админ поменял руками (название, порядок, цвет)
|
||||
update: {},
|
||||
});
|
||||
|
||||
const bodyMd = body.trim() + '\n';
|
||||
const data = {
|
||||
sectionId: section.id,
|
||||
title: meta.title,
|
||||
summary: meta.summary ?? '',
|
||||
tags: meta.tags,
|
||||
equipment: meta.equipment,
|
||||
docCode: meta.doc_code ?? null,
|
||||
pinned: meta.pinned,
|
||||
order: meta.order ?? 0,
|
||||
};
|
||||
|
||||
const existing = await prisma.article.findUnique({ where: { slug: meta.slug } });
|
||||
let articleId: string;
|
||||
if (!existing) {
|
||||
const art = await prisma.article.create({
|
||||
data: { ...data, slug: meta.slug, bodyMd, bodyHtml: '', status: 'PUBLISHED', authorId: admin?.id ?? null },
|
||||
});
|
||||
await prisma.articleRevision.create({
|
||||
data: { articleId: art.id, version: 1, title: art.title, bodyMd, authorId: admin?.id ?? null, comment: 'Импорт из kb-seed' },
|
||||
});
|
||||
articleId = art.id;
|
||||
created++;
|
||||
} else {
|
||||
const changed = existing.bodyMd !== bodyMd;
|
||||
const version = changed ? existing.version + 1 : existing.version;
|
||||
await prisma.article.update({
|
||||
where: { id: existing.id },
|
||||
data: { ...data, bodyMd, version, ...(changed ? { updatedAt: new Date() } : {}) },
|
||||
});
|
||||
if (changed) {
|
||||
await prisma.articleRevision.create({
|
||||
data: { articleId: existing.id, version, title: meta.title, bodyMd, authorId: admin?.id ?? null, comment: 'Обновление из kb-seed' },
|
||||
});
|
||||
updated++;
|
||||
}
|
||||
articleId = existing.id;
|
||||
}
|
||||
|
||||
// Исходники по полю source
|
||||
for (const src of meta.source) {
|
||||
const rel = src.replace(/^\.?\/+/, '');
|
||||
const size = await fileSize(uploadPath(rel));
|
||||
if (size === null) {
|
||||
problems.push(`${meta.slug}: исходник не найден: ${src}`);
|
||||
continue;
|
||||
}
|
||||
const att = { filename: path.posix.basename(rel), size };
|
||||
await prisma.attachment.upsert({
|
||||
where: { articleId_path: { articleId, path: rel } },
|
||||
create: { articleId, path: rel, ...att },
|
||||
update: att,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// HTML рисуем вторым проходом: к этому моменту известны названия всех статей для [[ссылок]]
|
||||
const report = await rerenderAll();
|
||||
for (const r of report) {
|
||||
for (const slug of r.brokenLinks) problems.push(`${r.slug}: битая ссылка [[${slug}]]`);
|
||||
}
|
||||
|
||||
// Картинки, на которые ссылается текст, но файла нет
|
||||
const assetPaths = new Set((await prisma.asset.findMany({ select: { path: true } })).map((a) => a.path));
|
||||
const articles = await prisma.article.findMany({ select: { slug: true, bodyMd: true } });
|
||||
let imageRefs = 0;
|
||||
for (const art of articles) {
|
||||
for (const m of art.bodyMd.matchAll(/!\[[^\]]*\]\(([^)\s]+)/g)) {
|
||||
const key = assetKey(m[1] ?? '');
|
||||
if (!key) continue;
|
||||
imageRefs++;
|
||||
if (!assetPaths.has(`${key}.webp`)) problems.push(`${art.slug}: картинка не найдена: ${m[1]}`);
|
||||
}
|
||||
}
|
||||
|
||||
const counts = {
|
||||
spaces: await prisma.space.count(),
|
||||
sections: await prisma.section.count(),
|
||||
articles: await prisma.article.count(),
|
||||
assets: await prisma.asset.count(),
|
||||
attachments: await prisma.attachment.count(),
|
||||
};
|
||||
|
||||
console.log('\n===== Отчёт импорта =====');
|
||||
console.log(`Статей в БД: ${counts.articles} (новых ${created}, обновлено ${updated})`);
|
||||
console.log(`Разделов: ${counts.sections}, пространств: ${counts.spaces}`);
|
||||
console.log(`Картинок: ${counts.assets} (в kb-seed ${images.total}, сконвертировано сейчас ${images.converted})`);
|
||||
console.log(`Ссылок на картинки: ${imageRefs}`);
|
||||
console.log(`Исходников: ${counts.attachments} привязано к статьям (файлов ${originals})`);
|
||||
console.log(`[[Ссылок]]: ${report.reduce((n, r) => n + r.brokenLinks.length, 0)} битых`);
|
||||
console.log(admin ? `Администратор: ${admin.email}` : 'Администратор: не создан (задайте ADMIN_EMAIL и ADMIN_PASSWORD в .env)');
|
||||
if (problems.length) {
|
||||
console.log(`\nПроблемы (${problems.length}):`);
|
||||
for (const p of problems) console.log(` - ${p}`);
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
console.log('\nПроблем нет: все картинки, исходники и ссылки на месте.');
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureAdmin() {
|
||||
if (!env.ADMIN_EMAIL || !env.ADMIN_PASSWORD) return prisma.user.findFirst({ where: { role: 'ADMIN' } });
|
||||
const email = env.ADMIN_EMAIL.toLowerCase();
|
||||
const existing = await prisma.user.findUnique({ where: { email } });
|
||||
// Существующему админу пароль не перезаписываем: он мог его уже сменить
|
||||
if (existing) return existing;
|
||||
return prisma.user.create({
|
||||
data: { email, name: env.ADMIN_NAME, role: 'ADMIN', passwordHash: await hashPassword(env.ADMIN_PASSWORD) },
|
||||
});
|
||||
}
|
||||
|
||||
main()
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
})
|
||||
.finally(() => prisma.$disconnect());
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { assetKey, parseCheatSheet, renderMarkdown, type RenderResult } from '@kb/md';
|
||||
import { compactSearch, normalizeSearch } from '@kb/shared';
|
||||
import { prisma } from '../db.js';
|
||||
|
||||
type Db = Prisma.TransactionClient | typeof prisma;
|
||||
|
||||
/** slug → название для подстановки в [[ссылки]]. */
|
||||
export async function loadTitleMap(db: Db = prisma): Promise<Map<string, string>> {
|
||||
const rows = await db.article.findMany({ select: { slug: true, title: true } });
|
||||
return new Map(rows.map((r) => [r.slug, r.title]));
|
||||
}
|
||||
|
||||
/** Размеры картинок по ключу (assets/shkon/fig-1), чтобы в HTML сразу стояли width/height. */
|
||||
export async function loadImageSizes(md: string, db: Db = prisma) {
|
||||
const keys = [...md.matchAll(/!\[[^\]]*\]\(([^)\s]+)/g)]
|
||||
.map((m) => assetKey(m[1] ?? ''))
|
||||
.filter((k): k is string => !!k);
|
||||
if (!keys.length) return new Map<string, { width: number; height: number }>();
|
||||
const rows = await db.asset.findMany({
|
||||
where: { path: { in: keys.map((k) => `${k}.webp`) } },
|
||||
select: { path: true, width: true, height: true },
|
||||
});
|
||||
return new Map(rows.map((r) => [r.path.replace(/\.webp$/, ''), { width: r.width, height: r.height }]));
|
||||
}
|
||||
|
||||
export async function renderArticle(md: string, db: Db = prisma): Promise<RenderResult> {
|
||||
const [titles, sizes] = await Promise.all([loadTitleMap(db), loadImageSizes(md, db)]);
|
||||
return renderMarkdown(md, {
|
||||
resolveLink: (slug) => titles.get(slug),
|
||||
imageSize: (key) => sizes.get(key),
|
||||
});
|
||||
}
|
||||
|
||||
/** Факт в поле Article.facts: пункт «Главного» или строка шпаргалки. */
|
||||
export interface StoredFact {
|
||||
label: string;
|
||||
value: string;
|
||||
/** Для строк шпаргалки: статьи-источники. */
|
||||
links?: string[];
|
||||
}
|
||||
|
||||
/** Факты статьи для блока «Цифры» в поиске. У шпаргалки это ещё и строки её таблицы цифр. */
|
||||
export function deriveFacts(md: string, pinned: boolean, render: RenderResult): StoredFact[] {
|
||||
const facts: StoredFact[] = [...render.facts];
|
||||
if (pinned) {
|
||||
const cheat = parseCheatSheet(md);
|
||||
for (const f of cheat.facts) {
|
||||
if (f.value) facts.push({ label: f.segs.map((x) => x.t).join(''), value: `**${f.value}**`, links: f.links });
|
||||
}
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
export interface IndexSource {
|
||||
title: string;
|
||||
summary: string;
|
||||
tags: string[];
|
||||
equipment: string[];
|
||||
docCode: string | null;
|
||||
render: RenderResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Обновляет поисковые поля статьи.
|
||||
* Веса: A заголовок, B «Главное» и краткое описание, C теги/оборудование/шифр, D остальной текст.
|
||||
*/
|
||||
export async function updateSearchIndex(articleId: string, src: IndexSource, db: Db = prisma) {
|
||||
const a = normalizeSearch(src.title);
|
||||
const b = normalizeSearch(`${src.render.text.keyfacts}\n${src.summary}`);
|
||||
const c = normalizeSearch([...src.tags, ...src.equipment, src.docCode ?? ''].join('\n'));
|
||||
const d = normalizeSearch(src.render.text.body);
|
||||
const all = [a, b, c, d].join('\n');
|
||||
|
||||
await db.$executeRaw`
|
||||
UPDATE "Article" SET
|
||||
"searchVector" =
|
||||
setweight(to_tsvector('russian', ${a}), 'A') ||
|
||||
setweight(to_tsvector('russian', ${b}), 'B') ||
|
||||
setweight(to_tsvector('russian', ${c}), 'C') ||
|
||||
setweight(to_tsvector('russian', ${d}), 'D'),
|
||||
"searchNorm" = ${all},
|
||||
"searchCompact" = ${compactSearch(all)}
|
||||
WHERE id = ${articleId}`;
|
||||
}
|
||||
|
||||
/** Привязывает картинки из текста к статье (поле Asset.articleId). */
|
||||
export async function linkAssets(articleId: string, render: RenderResult, db: Db = prisma) {
|
||||
const paths = render.figures.map((f) => assetKey(f.src)).filter((k): k is string => !!k).map((k) => `${k}.webp`);
|
||||
await db.asset.updateMany({ where: { articleId, path: { notIn: paths } }, data: { articleId: null } });
|
||||
if (paths.length) {
|
||||
await db.asset.updateMany({ where: { path: { in: paths }, articleId: null }, data: { articleId } });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Перерисовывает HTML всех статей. Нужно, когда поменялось название статьи
|
||||
* или появилась новая: в чужих [[ссылках]] должно стоять актуальное название.
|
||||
*/
|
||||
export async function rerenderAll(db: Db = prisma): Promise<{ slug: string; brokenLinks: string[] }[]> {
|
||||
const titles = await loadTitleMap(db);
|
||||
const articles = await db.article.findMany();
|
||||
const report: { slug: string; brokenLinks: string[] }[] = [];
|
||||
for (const art of articles) {
|
||||
const sizes = await loadImageSizes(art.bodyMd, db);
|
||||
const render = renderMarkdown(art.bodyMd, {
|
||||
resolveLink: (slug) => titles.get(slug),
|
||||
imageSize: (key) => sizes.get(key),
|
||||
});
|
||||
await db.article.update({
|
||||
where: { id: art.id },
|
||||
data: {
|
||||
bodyHtml: render.html,
|
||||
facts: deriveFacts(art.bodyMd, art.pinned, render) as unknown as Prisma.InputJsonValue,
|
||||
},
|
||||
});
|
||||
await updateSearchIndex(art.id, { ...art, render }, db);
|
||||
await linkAssets(art.id, render, db);
|
||||
report.push({ slug: art.slug, brokenLinks: render.brokenLinks });
|
||||
}
|
||||
return report;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import sharp from 'sharp';
|
||||
import { env } from '../env.js';
|
||||
|
||||
export const FULL_WIDTH = 1600;
|
||||
export const THUMB_WIDTH = 480;
|
||||
|
||||
export interface StoredImage {
|
||||
/** Путь относительно uploads: assets/shkon/fig-1.webp */
|
||||
path: string;
|
||||
width: number;
|
||||
height: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
/** Полный путь файла в папке uploads с защитой от выхода за её пределы («../»). */
|
||||
export function uploadPath(rel: string): string {
|
||||
const root = path.resolve(env.UPLOADS_DIR);
|
||||
const full = path.resolve(root, rel);
|
||||
if (full !== root && !full.startsWith(root + path.sep)) throw new Error(`Недопустимый путь: ${rel}`);
|
||||
return full;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сохраняет картинку в двух размерах:
|
||||
* <key>.webp до 1600 px по ширине (просмотр, зум)
|
||||
* <key>.480.webp превью 480 px
|
||||
* EXIF (в том числе координаты съёмки) удаляется: sharp не переносит метаданные,
|
||||
* а rotate() перед этим применяет поворот из EXIF, чтобы фото не легло набок.
|
||||
*/
|
||||
export async function storeImage(input: Buffer, key: string): Promise<StoredImage> {
|
||||
const fullRel = `${key}.webp`;
|
||||
const thumbRel = `${key}.${THUMB_WIDTH}.webp`;
|
||||
const fullAbs = uploadPath(fullRel);
|
||||
await fs.mkdir(path.dirname(fullAbs), { recursive: true });
|
||||
|
||||
const base = sharp(input, { failOn: 'error' }).rotate();
|
||||
const full = await base
|
||||
.clone()
|
||||
.resize({ width: FULL_WIDTH, withoutEnlargement: true })
|
||||
.webp({ quality: 80 })
|
||||
.toFile(fullAbs);
|
||||
await base
|
||||
.clone()
|
||||
.resize({ width: THUMB_WIDTH, withoutEnlargement: true })
|
||||
.webp({ quality: 72 })
|
||||
.toFile(uploadPath(thumbRel));
|
||||
|
||||
return { path: fullRel, width: full.width, height: full.height, size: full.size };
|
||||
}
|
||||
|
||||
export async function fileSize(abs: string): Promise<number | null> {
|
||||
try {
|
||||
return (await fs.stat(abs)).size;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import argon2 from 'argon2';
|
||||
|
||||
// argon2id: рекомендованный сейчас алгоритм хеширования паролей.
|
||||
export const hashPassword = (password: string) => argon2.hash(password, { type: argon2.argon2id });
|
||||
|
||||
export async function verifyPassword(hash: string, password: string): Promise<boolean> {
|
||||
try {
|
||||
return await argon2.verify(hash, password);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+7
-1
@@ -1,9 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<html lang="ru" data-theme="dark">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="description" content="Памятки монтажника: инструкции по монтажу АСУПП, цифры, запреты и чек-листы." />
|
||||
<meta name="theme-color" content="#0f1011" />
|
||||
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<title>Памятки монтажника</title>
|
||||
<!-- Тему ставим до первой отрисовки, чтобы экран не мигал тёмным у тех, кто выбрал светлую -->
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"@kb/md": "workspace:^",
|
||||
"@kb/shared": "workspace:^",
|
||||
"@tanstack/react-query": "^5.104.1",
|
||||
"qrcode-generator": "^2.0.4",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router-dom": "^7.18.4"
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#f5c400"/><path d="M0 44 44 0h14L0 58zM20 64 64 20v14L34 64z" fill="#141414"/><rect x="14" y="20" width="36" height="24" rx="4" fill="#141414"/><text x="32" y="38" font-family="Arial,sans-serif" font-size="17" font-weight="700" text-anchor="middle" fill="#f5c400">ПМ</text></svg>
|
||||
|
After Width: | Height: | Size: 385 B |
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 |
@@ -0,0 +1,9 @@
|
||||
// Отдельный файл (а не код в index.html): так политика безопасности CSP может запретить инлайн-скрипты.
|
||||
(function () {
|
||||
try {
|
||||
var t = JSON.parse(localStorage.getItem('kb-theme') || '"dark"');
|
||||
if (t === 'light' || t === 'sun' || t === 'dark') document.documentElement.setAttribute('data-theme', t);
|
||||
} catch {
|
||||
/* тема по умолчанию */
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,47 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { Screen } from './components/Shell';
|
||||
import { BackLink, Notice } from './components/ui';
|
||||
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 { OfflinePage } from './pages/OfflinePage';
|
||||
import { SearchPage } from './pages/Search';
|
||||
import { SectionPage } from './pages/Section';
|
||||
|
||||
// Редко нужные экраны грузятся отдельными файлами, чтобы не замедлять чтение статей
|
||||
const PrintPage = lazy(() => import('./pages/Print'));
|
||||
|
||||
function NotFound() {
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
</div>
|
||||
<Notice title="Страница не найдена">Проверьте адрес или вернитесь на главную.</Notice>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
export function App() {
|
||||
// Тема применяется один раз здесь: вешает data-theme на <html>
|
||||
useTheme();
|
||||
|
||||
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="/offline" element={<OfflinePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
// Тело статьи. HTML приходит готовым с сервера (или из рендера в редакторе),
|
||||
// здесь мы только «оживляем» его: галочки чек-листов, открытие фото, переходы по [[ссылкам]].
|
||||
|
||||
import { memo, useEffect, useRef } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { checkKey, getStored, setStored } from '../lib/store';
|
||||
|
||||
export interface Figure {
|
||||
src: string;
|
||||
thumb: string;
|
||||
caption: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
html: string;
|
||||
/** slug и версия: ключ для хранения галочек. Без них (предпросмотр) галочки живут до перезагрузки. */
|
||||
slug?: string;
|
||||
version?: number;
|
||||
onImage?: (index: number, figures: Figure[]) => void;
|
||||
/** Актуальные названия статей для [[ссылок]] (если статью переименовали после сохранения этой). */
|
||||
titles?: (slug: string) => string | undefined;
|
||||
}
|
||||
|
||||
type Checks = Record<string, boolean>;
|
||||
|
||||
function paintChecks(root: HTMLElement, state: Checks) {
|
||||
root.querySelectorAll<HTMLElement>('.kb-check').forEach((box) => {
|
||||
const g = box.dataset.check ?? '0';
|
||||
const rows = box.querySelectorAll<HTMLElement>('.kb-check-row');
|
||||
let done = 0;
|
||||
rows.forEach((row) => {
|
||||
const on = !!state[`${g}-${row.dataset.i}`];
|
||||
if (on) done++;
|
||||
row.classList.toggle('is-on', on);
|
||||
row.setAttribute('aria-pressed', String(on));
|
||||
});
|
||||
const count = box.querySelector('.kb-check-count');
|
||||
if (count) count.textContent = `${done} из ${rows.length}`;
|
||||
const fill = box.querySelector<HTMLElement>('.kb-check-fill');
|
||||
if (fill) fill.style.width = `${rows.length ? (done / rows.length) * 100 : 0}%`;
|
||||
});
|
||||
}
|
||||
|
||||
function collectFigures(root: HTMLElement): Figure[] {
|
||||
return [...root.querySelectorAll<HTMLElement>('.kb-fig')].map((fig) => {
|
||||
const img = fig.querySelector<HTMLImageElement>('img');
|
||||
const thumb = img?.getAttribute('src') ?? '';
|
||||
return {
|
||||
// Полноразмерный файл лежит рядом с превью: fig-1.480.webp → fig-1.webp
|
||||
src: thumb.replace(/\.480\.webp$/, '.webp'),
|
||||
thumb,
|
||||
caption: fig.querySelector('figcaption')?.textContent ?? '',
|
||||
file: img?.dataset.file ?? fig.querySelector<HTMLElement>('.kb-fig-miss')?.dataset.file ?? '',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function ArticleBodyInner({ html, slug, version, onImage, titles }: Props) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const navigate = useNavigate();
|
||||
const storageKey = slug ? checkKey(slug, version ?? 1) : null;
|
||||
// Для предпросмотра без slug состояние держим в памяти
|
||||
const memory = useRef<Checks>({});
|
||||
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root) return;
|
||||
const load = (): Checks => (storageKey ? getStored<Checks>(storageKey, {}) : memory.current);
|
||||
const save = (s: Checks) => (storageKey ? setStored(storageKey, s) : (memory.current = s));
|
||||
|
||||
paintChecks(root, load());
|
||||
|
||||
// Подставляем актуальные названия в ссылки-чипы
|
||||
if (titles) {
|
||||
root.querySelectorAll<HTMLElement>('[data-slug]').forEach((el) => {
|
||||
const t = titles(el.dataset.slug ?? '');
|
||||
const label = el.querySelector('.kb-link-t') ?? (el.classList.contains('kb-ulink') ? el : null);
|
||||
if (t && label && label.textContent !== t) label.textContent = t;
|
||||
});
|
||||
}
|
||||
|
||||
const onClick = (e: MouseEvent) => {
|
||||
const target = e.target as HTMLElement;
|
||||
|
||||
const row = target.closest<HTMLElement>('.kb-check-row');
|
||||
if (row) {
|
||||
const g = row.closest<HTMLElement>('.kb-check')?.dataset.check ?? '0';
|
||||
const key = `${g}-${row.dataset.i}`;
|
||||
const state = { ...load() };
|
||||
if (state[key]) delete state[key];
|
||||
else state[key] = true;
|
||||
save(state);
|
||||
paintChecks(root, state);
|
||||
return;
|
||||
}
|
||||
|
||||
const reset = target.closest('.kb-check-reset');
|
||||
if (reset) {
|
||||
const g = reset.closest<HTMLElement>('.kb-check')?.dataset.check ?? '0';
|
||||
const state = Object.fromEntries(Object.entries(load()).filter(([k]) => !k.startsWith(`${g}-`)));
|
||||
save(state);
|
||||
paintChecks(root, state);
|
||||
return;
|
||||
}
|
||||
|
||||
const fig = target.closest<HTMLElement>('.kb-fig-btn');
|
||||
if (fig) {
|
||||
onImage?.(Number(fig.dataset.fig ?? 0), collectFigures(root));
|
||||
return;
|
||||
}
|
||||
|
||||
// Внутренние ссылки открываем без перезагрузки страницы
|
||||
const link = target.closest<HTMLAnchorElement>('a.kb-link');
|
||||
if (link && !e.metaKey && !e.ctrlKey && !e.shiftKey && e.button === 0) {
|
||||
e.preventDefault();
|
||||
navigate(link.getAttribute('href') ?? '/');
|
||||
}
|
||||
};
|
||||
|
||||
// Картинка не загрузилась (нет сети и нет в кеше): показываем заглушку с именем файла.
|
||||
// Событие error не всплывает, поэтому ловим его на фазе перехвата.
|
||||
const onError = (e: Event) => {
|
||||
const img = e.target as HTMLElement;
|
||||
if (!(img instanceof HTMLImageElement) || !img.classList.contains('kb-fig-img')) return;
|
||||
const stub = document.createElement('div');
|
||||
stub.className = 'kb-fig-miss';
|
||||
stub.dataset.file = img.dataset.file ?? '';
|
||||
stub.textContent = `фото · ${img.dataset.file ?? ''}`;
|
||||
img.replaceWith(stub);
|
||||
};
|
||||
|
||||
root.addEventListener('click', onClick);
|
||||
root.addEventListener('error', onError, true);
|
||||
return () => {
|
||||
root.removeEventListener('click', onClick);
|
||||
root.removeEventListener('error', onError, true);
|
||||
};
|
||||
}, [html, storageKey, navigate, titles, onImage]);
|
||||
|
||||
// HTML собран нашим рендером и прошёл rehype-sanitize, поэтому вставлять его безопасно
|
||||
return <div ref={ref} className="kb-body" dangerouslySetInnerHTML={{ __html: html }} />;
|
||||
}
|
||||
|
||||
export const ArticleBody = memo(ArticleBodyInner);
|
||||
@@ -0,0 +1,70 @@
|
||||
// Иконки из макета: 24×24, линия 2, скруглённые концы, цвет текста.
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
function Svg({ children, size = 24, fill = 'none' }: { children: ReactNode; size?: number; fill?: string }) {
|
||||
return (
|
||||
<svg
|
||||
width={size}
|
||||
height={size}
|
||||
viewBox="0 0 24 24"
|
||||
fill={fill}
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
aria-hidden="true"
|
||||
className="icon"
|
||||
>
|
||||
{children}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
type P = { size?: number };
|
||||
|
||||
export const IconHome = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<path d="M3 11l9-7 9 7" />
|
||||
<path d="M5 10v10h14V10" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconSearch = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<circle cx="11" cy="11" r="7" />
|
||||
<path d="M16.5 16.5L21 21" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconDoc = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<rect x="4" y="3" width="16" height="18" rx="2" />
|
||||
<path d="M8 8h8M8 12h8M8 16h5" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconStar = ({ size, filled }: P & { filled?: boolean }) => (
|
||||
<Svg size={size} fill={filled ? 'var(--hl)' : 'none'}>
|
||||
<path d="M12 3.5l2.6 5.3 5.9.9-4.2 4.1 1 5.8-5.3-2.8-5.3 2.8 1-5.8-4.2-4.1 5.9-.9z" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconList = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<path d="M4 6h16M4 12h16M4 18h10" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconPrint = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<path d="M7 9V3h10v6" />
|
||||
<rect x="3" y="9" width="18" height="8" rx="2" />
|
||||
<path d="M7 14h10v7H7z" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconTheme = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<circle cx="12" cy="12" r="8" />
|
||||
<path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor" />
|
||||
</Svg>
|
||||
);
|
||||
export const IconUp = (p: P) => (
|
||||
<Svg {...p}>
|
||||
<path d="M12 20V5M5 11l7-7 7 7" />
|
||||
</Svg>
|
||||
);
|
||||
@@ -0,0 +1,177 @@
|
||||
// Полноэкранный просмотр фото: щипок и колесо для зума (1–5×), двойной тап 1× ↔ 2,5×,
|
||||
// перетаскивание при увеличении, свайп влево/вправо при 1×. Логика из new_design/Lightbox.dc.html.
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { Figure } from './ArticleBody';
|
||||
|
||||
interface View {
|
||||
z: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
const RESET: View = { z: 1, x: 0, y: 0 };
|
||||
const clampZ = (z: number) => Math.max(1, Math.min(5, z));
|
||||
const SWIPE_PX = 60;
|
||||
|
||||
export function Lightbox({ figures, start, onClose }: { figures: Figure[]; start: number; onClose: () => void }) {
|
||||
const [i, setI] = useState(Math.min(start, Math.max(0, figures.length - 1)));
|
||||
const [view, setView] = useState<View>(RESET);
|
||||
const [drag, setDrag] = useState(false);
|
||||
const [failed, setFailed] = useState<Record<number, boolean>>({});
|
||||
// Активные касания: id указателя → координаты
|
||||
const pointers = useRef(new Map<number, { x: number; y: number }>());
|
||||
const swipe = useRef<{ x: number; on: boolean }>({ x: 0, on: false });
|
||||
const lastTap = useRef(0);
|
||||
const closeRef = useRef<HTMLButtonElement>(null);
|
||||
|
||||
const fig = figures[i];
|
||||
const go = useCallback(
|
||||
(d: number) => {
|
||||
if (!figures.length) return;
|
||||
setI((cur) => (cur + d + figures.length) % figures.length);
|
||||
setView(RESET);
|
||||
},
|
||||
[figures.length],
|
||||
);
|
||||
const zoom = (z: number) => setView((v) => (clampZ(z) === 1 ? RESET : { ...v, z: clampZ(z) }));
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') onClose();
|
||||
else if (e.key === 'ArrowLeft') go(-1);
|
||||
else if (e.key === 'ArrowRight') go(1);
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
// Пока открыт просмотр, страница под ним не прокручивается
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
closeRef.current?.focus();
|
||||
return () => {
|
||||
window.removeEventListener('keydown', onKey);
|
||||
document.body.style.overflow = prev;
|
||||
};
|
||||
}, [go, onClose]);
|
||||
|
||||
const onDown = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
try {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
} catch {
|
||||
// не все браузеры дают захватить указатель: работаем и так
|
||||
}
|
||||
pointers.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
if (pointers.current.size === 1) swipe.current = { x: e.clientX, on: view.z === 1 };
|
||||
else swipe.current.on = false;
|
||||
setDrag(true);
|
||||
};
|
||||
|
||||
const onMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
const P = pointers.current;
|
||||
if (!P.has(e.pointerId)) return;
|
||||
const ids = [...P.keys()];
|
||||
const prev = ids.map((k) => P.get(k)!);
|
||||
P.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
||||
const cur = ids.map((k) => P.get(k)!);
|
||||
|
||||
if (cur.length === 1) {
|
||||
// Один палец: двигаем увеличенное фото
|
||||
const dx = cur[0]!.x - prev[0]!.x;
|
||||
const dy = cur[0]!.y - prev[0]!.y;
|
||||
setView((v) => (v.z > 1 ? { ...v, x: v.x + dx, y: v.y + dy } : v));
|
||||
} else {
|
||||
// Два пальца: отношение расстояний даёт масштаб, сдвиг середины даёт перемещение
|
||||
const dist = (a: { x: number; y: number }, b: { x: number; y: number }) => Math.hypot(a.x - b.x, a.y - b.y);
|
||||
const ratio = dist(cur[0]!, cur[1]!) / (dist(prev[0]!, prev[1]!) || 1);
|
||||
const mx = (cur[0]!.x + cur[1]!.x - prev[0]!.x - prev[1]!.x) / 2;
|
||||
const my = (cur[0]!.y + cur[1]!.y - prev[0]!.y - prev[1]!.y) / 2;
|
||||
setView((v) => {
|
||||
const z = clampZ(v.z * ratio);
|
||||
return z === 1 ? RESET : { z, x: v.x + mx, y: v.y + my };
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
pointers.current.delete(e.pointerId);
|
||||
if (pointers.current.size > 0) return;
|
||||
setDrag(false);
|
||||
const dx = e.clientX - swipe.current.x;
|
||||
if (swipe.current.on && Math.abs(dx) > SWIPE_PX) {
|
||||
go(dx < 0 ? 1 : -1);
|
||||
return;
|
||||
}
|
||||
// Двойной тап: 1× ↔ 2,5× (dblclick на телефонах ненадёжен, считаем сами)
|
||||
if (Math.abs(dx) < 8) {
|
||||
const now = Date.now();
|
||||
if (now - lastTap.current < 300) {
|
||||
setView((v) => (v.z > 1 ? RESET : { z: 2.5, x: 0, y: 0 }));
|
||||
lastTap.current = 0;
|
||||
} else lastTap.current = now;
|
||||
}
|
||||
};
|
||||
|
||||
const transform = `translate(${view.x}px, ${view.y}px) scale(${view.z})`;
|
||||
const style = { transform, transition: drag ? 'none' : undefined };
|
||||
const missing = !fig?.src || failed[i];
|
||||
|
||||
return (
|
||||
<div className="lb" role="dialog" aria-modal="true" aria-label="Просмотр фото">
|
||||
<div className="lb-top">
|
||||
<div className="lb-info">
|
||||
<div className="lb-counter">{figures.length ? `${i + 1} / ${figures.length}` : ''}</div>
|
||||
<div className="lb-cap">{fig?.caption}</div>
|
||||
</div>
|
||||
<button ref={closeRef} type="button" className="lb-btn lb-btn--close" onClick={onClose} aria-label="Закрыть">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="lb-stage"
|
||||
onPointerDown={onDown}
|
||||
onPointerMove={onMove}
|
||||
onPointerUp={onUp}
|
||||
onPointerCancel={onUp}
|
||||
onWheel={(e) => zoom(view.z * (e.deltaY < 0 ? 1.15 : 1 / 1.15))}
|
||||
>
|
||||
{missing ? (
|
||||
<div className="lb-miss" style={style}>
|
||||
фото · {fig?.file}
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
key={fig.src}
|
||||
className="lb-img"
|
||||
src={fig.src}
|
||||
alt={fig.caption}
|
||||
draggable={false}
|
||||
style={style}
|
||||
onError={() => setFailed((f) => ({ ...f, [i]: true }))}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="lb-bottom">
|
||||
<div className="lb-controls">
|
||||
<button type="button" className="lb-btn" onClick={() => go(-1)} aria-label="Предыдущее">
|
||||
‹
|
||||
</button>
|
||||
<span />
|
||||
<button type="button" className="lb-btn" onClick={() => zoom(view.z / 1.5)} aria-label="Уменьшить">
|
||||
−
|
||||
</button>
|
||||
<button type="button" className="lb-btn lb-btn--pct" onClick={() => setView(RESET)} aria-label="Сбросить масштаб">
|
||||
{Math.round(view.z * 100)}%
|
||||
</button>
|
||||
<button type="button" className="lb-btn" onClick={() => zoom(view.z * 1.5)} aria-label="Увеличить">
|
||||
+
|
||||
</button>
|
||||
<span />
|
||||
<button type="button" className="lb-btn" onClick={() => go(1)} aria-label="Следующее">
|
||||
›
|
||||
</button>
|
||||
</div>
|
||||
<div className="lb-hint">Щипок или двойной тап: зум · свайп: листать</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Окно «Печать и PDF»: формат, что включить, оценка числа листов.
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { useStored } from '../lib/store';
|
||||
import { Sheet } from './ui';
|
||||
|
||||
export interface PrintOptions {
|
||||
fmt: 'A4' | 'A5';
|
||||
photos: boolean;
|
||||
checks: boolean;
|
||||
keyOnly: boolean;
|
||||
}
|
||||
export const PRINT_DEFAULTS: PrintOptions = { fmt: 'A4', photos: true, checks: true, keyOnly: false };
|
||||
export const PRINT_KEY = 'kb-print';
|
||||
|
||||
export const printUrl = (slug: string, o: PrintOptions, auto = true) =>
|
||||
`/print/${slug}?fmt=${o.fmt}&photos=${o.photos ? 1 : 0}&checks=${o.checks ? 1 : 0}&keyOnly=${o.keyOnly ? 1 : 0}${auto ? '&auto=1' : ''}`;
|
||||
|
||||
/** Грубая оценка числа листов: точное число покажет окно печати браузера. */
|
||||
function estimateSheets(o: PrintOptions, textLength: number, images: number): number {
|
||||
if (o.keyOnly) return 1;
|
||||
let pages = textLength / 2400 + (o.photos ? Math.ceil(images / 2) * 0.27 : 0);
|
||||
if (o.fmt === 'A5') pages *= 2;
|
||||
return Math.max(1, Math.ceil(pages));
|
||||
}
|
||||
|
||||
const ROWS: { key: 'photos' | 'checks' | 'keyOnly'; title: string; text: string }[] = [
|
||||
{ key: 'photos', title: 'Фото', text: 'С подписями, по 2 в ряд' },
|
||||
{ key: 'checks', title: 'Чек-листы', text: 'Пустые квадраты, чтобы отмечать ручкой' },
|
||||
{ key: 'keyOnly', title: 'Только памятка', text: '«Главное» и запреты на одном листе' },
|
||||
];
|
||||
|
||||
export function PrintSheet({
|
||||
slug,
|
||||
title,
|
||||
textLength,
|
||||
images,
|
||||
onClose,
|
||||
}: {
|
||||
slug: string;
|
||||
title: string;
|
||||
textLength: number;
|
||||
images: number;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
// Последний выбор запоминается на устройстве
|
||||
const [opts, setOpts] = useStored<PrintOptions>(PRINT_KEY, PRINT_DEFAULTS);
|
||||
const navigate = useNavigate();
|
||||
const n = estimateSheets(opts, textLength, images);
|
||||
const go = () => navigate(printUrl(slug, opts));
|
||||
|
||||
return (
|
||||
<Sheet title="Печать и PDF" subtitle={title} onClose={onClose}>
|
||||
<div className="sheet-body">
|
||||
<div className="block">
|
||||
<div className="caps">Формат</div>
|
||||
<div className="segmented" role="group" aria-label="Формат">
|
||||
{(['A4', 'A5'] as const).map((f) => (
|
||||
<button
|
||||
key={f}
|
||||
type="button"
|
||||
className={opts.fmt === f ? 'seg seg--on seg--lg' : 'seg seg--lg'}
|
||||
aria-pressed={opts.fmt === f}
|
||||
onClick={() => setOpts({ ...opts, fmt: f })}
|
||||
>
|
||||
{f}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="block">
|
||||
<div className="caps">Что включить</div>
|
||||
<div className="list">
|
||||
{ROWS.map((r) => (
|
||||
<button
|
||||
key={r.key}
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={opts[r.key]}
|
||||
className="switch-row"
|
||||
onClick={() => setOpts({ ...opts, [r.key]: !opts[r.key] })}
|
||||
>
|
||||
<span className="switch-row-main">
|
||||
<span className="switch-row-title">{r.title}</span>
|
||||
<span className="switch-row-text">{r.text}</span>
|
||||
</span>
|
||||
<span className={opts[r.key] ? 'switch switch--on' : 'switch'} aria-hidden="true">
|
||||
<span />
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="print-est">
|
||||
≈ {n} {plural(n, ['лист', 'листа', 'листов'])} {opts.fmt} · ч/б-совместимо
|
||||
</div>
|
||||
<div className="btn-pair">
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={go}>
|
||||
Печать
|
||||
</button>
|
||||
<button type="button" className="btn btn--brand btn--lg" onClick={go}>
|
||||
Скачать PDF
|
||||
</button>
|
||||
</div>
|
||||
<div className="print-hint">Чтобы получить файл, в окне печати выберите «Сохранить как PDF».</div>
|
||||
</div>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// Каркас экрана: на телефоне нижняя панель вкладок, на компьютере левое меню с деревом статей.
|
||||
import type { ReactNode } from 'react';
|
||||
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';
|
||||
|
||||
const TABS: { id: Tab; to: string; label: string; icon: ReactNode }[] = [
|
||||
{ id: 'home', to: '/', label: 'Главная', icon: <IconHome /> },
|
||||
{ id: 'search', to: '/search', label: 'Поиск', icon: <IconSearch /> },
|
||||
{ id: 'cheat', to: '/cheatsheet', label: 'Шпаргалка', icon: <IconDoc /> },
|
||||
{ id: 'fav', to: '/favorites', label: 'Избранное', icon: <IconStar /> },
|
||||
];
|
||||
|
||||
export function TabBar({ active }: { active: Tab }) {
|
||||
return (
|
||||
<nav className="tabbar" aria-label="Основное меню">
|
||||
{TABS.map((t) => (
|
||||
<Link
|
||||
key={t.id}
|
||||
to={t.to}
|
||||
className={t.id === active ? 'tab tab--on' : 'tab'}
|
||||
aria-current={t.id === active ? 'page' : undefined}
|
||||
>
|
||||
{t.icon}
|
||||
<span>{t.label}</span>
|
||||
</Link>
|
||||
))}
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
const nav = useNav();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { pathname } = useLocation();
|
||||
|
||||
return (
|
||||
<aside className="sidebar">
|
||||
<Link to="/" className="sidebar-brand">
|
||||
<span className="sidebar-brand-title">Памятки монтажника</span>
|
||||
<span className="sidebar-brand-sub">wiki.suchtech.ru</span>
|
||||
</Link>
|
||||
|
||||
{nav.space ? (
|
||||
<div className="space-pick">
|
||||
<span className="space-pick-icon">{nav.space.icon || nav.space.name[0]}</span>
|
||||
<span className="space-pick-text">
|
||||
<span className="space-pick-label">Пространство</span>
|
||||
<span className="space-pick-name">{nav.space.name}</span>
|
||||
</span>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<nav className="tree" aria-label="Статьи">
|
||||
<NavLink to="/search" className="tree-link tree-link--top">
|
||||
Поиск
|
||||
</NavLink>
|
||||
{nav.pinned ? (
|
||||
<NavLink to="/cheatsheet" className="tree-link tree-link--top">
|
||||
Шпаргалка
|
||||
</NavLink>
|
||||
) : null}
|
||||
<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">
|
||||
<CodeTag code={s.code} small />
|
||||
{s.name}
|
||||
</Link>
|
||||
{s.articles.map((a) => (
|
||||
<Link
|
||||
key={a.id}
|
||||
to={articleHref(a)}
|
||||
className={pathname === articleHref(a) ? 'tree-link tree-link--on' : 'tree-link'}
|
||||
aria-current={pathname === articleHref(a) ? 'page' : undefined}
|
||||
>
|
||||
{nav.short(a)}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
{footer}
|
||||
<div className="sidebar-foot-label">Тема</div>
|
||||
<div className="segmented segmented--3" role="group" aria-label="Тема">
|
||||
{THEME_ORDER.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
className={t === theme ? 'seg seg--on' : 'seg'}
|
||||
aria-pressed={t === theme}
|
||||
onClick={() => setTheme(t)}
|
||||
>
|
||||
{THEME_LABEL[t]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Обёртка обычного экрана.
|
||||
* tab: какая вкладка подсвечена внизу; bar: своя нижняя панель вместо вкладок (экран статьи).
|
||||
*/
|
||||
export function Screen({
|
||||
tab,
|
||||
bar,
|
||||
children,
|
||||
wide,
|
||||
}: {
|
||||
tab?: Tab;
|
||||
bar?: ReactNode;
|
||||
children: ReactNode;
|
||||
wide?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<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)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Мелкие общие элементы интерфейса.
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { PlaqueColor } from '@kb/shared';
|
||||
import { useTheme } from '../lib/theme';
|
||||
|
||||
/** Цветная плашка с кодом раздела: «ВВ», «ВОК». size: sm (в сетке), lg (в шапке раздела). */
|
||||
export function Plaque({ code, color, size = 'sm' }: { code: string; color: PlaqueColor; size?: 'sm' | 'lg' }) {
|
||||
return <span className={`plaque plaque--${color} plaque--${size}`}>{code}</span>;
|
||||
}
|
||||
|
||||
/** Код раздела в рамке: в списках избранного, в меню. */
|
||||
export function CodeTag({ code, small }: { code: string; small?: boolean }) {
|
||||
return <span className={small ? 'codetag codetag--sm' : 'codetag'}>{code}</span>;
|
||||
}
|
||||
|
||||
/** Кнопка «Тема» в шапке экрана: переключает по кругу. */
|
||||
export function ThemeButton() {
|
||||
const { label, cycle } = useTheme();
|
||||
return (
|
||||
<button type="button" className="theme-btn" onClick={cycle} aria-label={`Тема: ${label}. Переключить`}>
|
||||
<span className="theme-btn-dot" aria-hidden="true" />
|
||||
{label}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** Ссылка «‹ Назад». */
|
||||
export function BackLink({ to, children }: { to: string; children: ReactNode }) {
|
||||
return (
|
||||
<Link to={to} className="back">
|
||||
<span className="back-chev" aria-hidden="true">
|
||||
‹
|
||||
</span>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export function Caps({ children, right }: { children: ReactNode; right?: ReactNode }) {
|
||||
return (
|
||||
<div className="caps-row">
|
||||
<h2 className="caps">{children}</h2>
|
||||
{right ? <span className="caps-right">{right}</span> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Состояния «загрузка / ошибка / пусто» в стиле макета (в самом макете их нет). */
|
||||
export function Notice({ title, children, tone }: { title: string; children?: ReactNode; tone?: 'error' }) {
|
||||
return (
|
||||
<div className={tone === 'error' ? 'notice notice--error' : 'notice'} role={tone === 'error' ? 'alert' : 'status'}>
|
||||
<div className="notice-title">{title}</div>
|
||||
{children ? <div className="notice-text">{children}</div> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Skeleton({ lines = 3 }: { lines?: number }) {
|
||||
return (
|
||||
<div className="skeleton" aria-busy="true" aria-label="Загрузка">
|
||||
{Array.from({ length: lines }, (_, i) => (
|
||||
<span key={i} className="skeleton-line" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Выдвижная панель снизу (на телефоне) или окно по центру (на компьютере). */
|
||||
export function Sheet({
|
||||
title,
|
||||
subtitle,
|
||||
onClose,
|
||||
children,
|
||||
dialog,
|
||||
}: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
onClose: () => void;
|
||||
children: ReactNode;
|
||||
/** true: на широком экране показывать окном по центру */
|
||||
dialog?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div className={dialog ? 'sheet-wrap sheet-wrap--dialog' : 'sheet-wrap'}>
|
||||
<button type="button" className="scrim" aria-label="Закрыть" onClick={onClose} />
|
||||
<div className="sheet" role="dialog" aria-modal="true" aria-label={title}>
|
||||
<div className="sheet-grip" aria-hidden="true">
|
||||
<span />
|
||||
</div>
|
||||
<div className="sheet-head">
|
||||
<div className="sheet-titles">
|
||||
<div className="sheet-title">{title}</div>
|
||||
{subtitle ? <div className="sheet-sub">{subtitle}</div> : null}
|
||||
</div>
|
||||
<button type="button" className="sheet-close" onClick={onClose} aria-label="Закрыть">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
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 {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export async function api<T>(path: string, init?: RequestInit & { json?: unknown }): Promise<T> {
|
||||
const headers = new Headers(init?.headers);
|
||||
let body = init?.body;
|
||||
if (init?.json !== undefined) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
body = JSON.stringify(init.json);
|
||||
}
|
||||
// X-Requested-With: простой заголовок, который браузер не даст отправить с чужого сайта
|
||||
// без разрешения CORS. Сервер требует его на изменяющих запросах (защита от CSRF).
|
||||
headers.set('X-Requested-With', 'kb');
|
||||
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`/api${path}`, { ...init, headers, body, credentials: 'same-origin' });
|
||||
} catch {
|
||||
throw new ApiError(0, 'Нет связи с сервером');
|
||||
}
|
||||
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'));
|
||||
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: async () => {
|
||||
const tree = await api<TreeResponse>('/tree');
|
||||
markSynced();
|
||||
return tree;
|
||||
},
|
||||
};
|
||||
|
||||
export const articleQuery = (slug: string) => ({
|
||||
queryKey: ['article', slug] as const,
|
||||
queryFn: () => api<ArticleDto>(`/articles/${encodeURIComponent(slug)}`),
|
||||
});
|
||||
|
||||
export function useTree() {
|
||||
return useQuery(treeQuery);
|
||||
}
|
||||
|
||||
export function useArticle(slug: string | undefined) {
|
||||
return useQuery({ ...articleQuery(slug ?? ''), enabled: !!slug });
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
/** 15.09.2026 */
|
||||
export function formatDate(iso: string | number | Date): string {
|
||||
const d = new Date(iso);
|
||||
return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}.${d.getFullYear()}`;
|
||||
}
|
||||
|
||||
/** 15.09.2026, 18:40 */
|
||||
export function formatDateTime(iso: string | number | Date): string {
|
||||
const d = new Date(iso);
|
||||
return `${formatDate(d)}, ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
/** Для «Недавно открытых»: сегодня → «14:20», вчера → «вчера», раньше → «30.09». */
|
||||
export function formatRecent(at: number): string {
|
||||
const d = new Date(at);
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const day = new Date(d);
|
||||
day.setHours(0, 0, 0, 0);
|
||||
const diff = Math.round((today.getTime() - day.getTime()) / 86_400_000);
|
||||
if (diff <= 0) return `${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
if (diff === 1) return 'вчера';
|
||||
return `${pad(d.getDate())}.${pad(d.getMonth() + 1)}`;
|
||||
}
|
||||
|
||||
/** 4,1 МБ */
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} Б`;
|
||||
const kb = bytes / 1024;
|
||||
if (kb < 1024) return `${Math.round(kb)} КБ`;
|
||||
const mb = kb / 1024;
|
||||
return `${mb < 10 ? mb.toFixed(1).replace('.', ',') : Math.round(mb)} МБ`;
|
||||
}
|
||||
|
||||
export const fileExt = (name: string) => (name.split('.').pop() ?? '').toUpperCase().slice(0, 4);
|
||||
|
||||
/** 01, 02, … */
|
||||
export const num2 = (n: number) => pad(n);
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Небольшое хранилище поверх localStorage: избранное, недавние, галочки чек-листов, тема.
|
||||
// Всё это живёт на устройстве и работает без сети.
|
||||
|
||||
import { useSyncExternalStore } from 'react';
|
||||
|
||||
type Listener = () => void;
|
||||
const listeners = new Map<string, Set<Listener>>();
|
||||
// Кеш разобранных значений: useSyncExternalStore требует, чтобы getSnapshot
|
||||
// возвращал ТОТ ЖЕ объект, пока данные не менялись.
|
||||
const cache = new Map<string, unknown>();
|
||||
|
||||
function read<T>(key: string, fallback: T): T {
|
||||
if (cache.has(key)) return cache.get(key) as T;
|
||||
let value = fallback;
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
if (raw !== null) value = JSON.parse(raw) as T;
|
||||
} catch {
|
||||
// localStorage недоступен (приватный режим) или там мусор: берём значение по умолчанию
|
||||
}
|
||||
cache.set(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
export function getStored<T>(key: string, fallback: T): T {
|
||||
return read(key, fallback);
|
||||
}
|
||||
|
||||
export function setStored<T>(key: string, value: T) {
|
||||
cache.set(key, value);
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify(value));
|
||||
} catch {
|
||||
// место кончилось: значение останется хотя бы в памяти до перезагрузки
|
||||
}
|
||||
listeners.get(key)?.forEach((l) => l());
|
||||
}
|
||||
|
||||
function subscribe(key: string, l: Listener) {
|
||||
let set = listeners.get(key);
|
||||
if (!set) listeners.set(key, (set = new Set()));
|
||||
set.add(l);
|
||||
return () => set.delete(l);
|
||||
}
|
||||
|
||||
// Изменения из другой вкладки
|
||||
if (typeof window !== 'undefined') {
|
||||
window.addEventListener('storage', (e) => {
|
||||
if (!e.key) return;
|
||||
cache.delete(e.key);
|
||||
listeners.get(e.key)?.forEach((l) => l());
|
||||
});
|
||||
}
|
||||
|
||||
export function useStored<T>(key: string, fallback: T): [T, (v: T) => void] {
|
||||
const value = useSyncExternalStore(
|
||||
(l) => subscribe(key, l),
|
||||
() => read(key, fallback),
|
||||
);
|
||||
return [value, (v: T) => setStored(key, v)];
|
||||
}
|
||||
|
||||
// ---------- Избранное ----------
|
||||
const FAV = 'kb-fav';
|
||||
const NO_FAVS: string[] = [];
|
||||
|
||||
export function useFavorites() {
|
||||
const [favs, setFavs] = useStored<string[]>(FAV, NO_FAVS);
|
||||
return {
|
||||
favs,
|
||||
has: (slug: string) => favs.includes(slug),
|
||||
toggle: (slug: string) => setFavs(favs.includes(slug) ? favs.filter((s) => s !== slug) : [slug, ...favs]),
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- Недавно открытые ----------
|
||||
export interface RecentItem {
|
||||
slug: string;
|
||||
at: number;
|
||||
}
|
||||
const RECENT = 'kb-recent';
|
||||
const NO_RECENT: RecentItem[] = [];
|
||||
|
||||
export function useRecent() {
|
||||
return useStored<RecentItem[]>(RECENT, NO_RECENT)[0];
|
||||
}
|
||||
|
||||
export function pushRecent(slug: string) {
|
||||
const list = getStored<RecentItem[]>(RECENT, NO_RECENT).filter((r) => r.slug !== slug);
|
||||
setStored(RECENT, [{ slug, at: Date.now() }, ...list].slice(0, 12));
|
||||
}
|
||||
|
||||
// ---------- Чек-листы ----------
|
||||
// Ключ = slug + версия статьи: после правки статьи старые галочки не переносятся на новый текст.
|
||||
export const checkKey = (slug: string, version: number) => `kb-check:${slug}:v${version}`;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useStored } from './store';
|
||||
|
||||
export type Theme = 'dark' | 'light' | 'sun';
|
||||
// Порядок переключения кнопкой «Тема»: тёмная → светлая → солнце
|
||||
export const THEME_ORDER: Theme[] = ['dark', 'light', 'sun'];
|
||||
export const THEME_LABEL: Record<Theme, string> = { dark: 'Тёмная', light: 'Светлая', sun: 'Солнце' };
|
||||
export const THEME_KEY = 'kb-theme';
|
||||
|
||||
export function useTheme() {
|
||||
const [stored, setTheme] = useStored<Theme>(THEME_KEY, 'dark');
|
||||
const theme = THEME_ORDER.includes(stored) ? stored : 'dark';
|
||||
|
||||
useEffect(() => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
// Цвет системной панели браузера берём из токена фона
|
||||
const bg = getComputedStyle(document.documentElement).getPropertyValue('--bg').trim();
|
||||
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', bg);
|
||||
}, [theme]);
|
||||
|
||||
return {
|
||||
theme,
|
||||
label: THEME_LABEL[theme],
|
||||
setTheme,
|
||||
cycle: () => setTheme(THEME_ORDER[(THEME_ORDER.indexOf(theme) + 1) % THEME_ORDER.length]!),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useMemo } from 'react';
|
||||
import { type ArticleListItem, type SectionDto, shortTitle } from '@kb/shared';
|
||||
import { useTree } from './api';
|
||||
|
||||
export interface SectionView extends SectionDto {
|
||||
/** Статьи раздела без закреплённой шпаргалки. */
|
||||
articles: ArticleListItem[];
|
||||
}
|
||||
|
||||
/** Дерево в удобном для экранов виде: разделы со статьями, поиск статьи и раздела по slug. */
|
||||
export function useNav() {
|
||||
const { data, isLoading, error } = useTree();
|
||||
return useMemo(() => {
|
||||
const sections = data?.sections ?? [];
|
||||
const articles = data?.articles ?? [];
|
||||
const bySection = new Map<string, SectionDto>(sections.map((s) => [s.id, s]));
|
||||
const bySlug = new Map<string, ArticleListItem>(articles.map((a) => [a.slug, a]));
|
||||
const pinned = articles.find((a) => a.pinned) ?? null;
|
||||
|
||||
const views: SectionView[] = sections
|
||||
.map((s) => ({ ...s, articles: articles.filter((a) => a.sectionId === s.id && !a.pinned) }))
|
||||
// Раздел, в котором только закреплённая шпаргалка, в сетке не показываем: у неё своя карточка
|
||||
.filter((s) => s.articles.length > 0);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
space: data?.spaces[0] ?? null,
|
||||
sections: views,
|
||||
articles,
|
||||
pinned,
|
||||
article: (slug: string) => bySlug.get(slug),
|
||||
sectionOf: (a: ArticleListItem | undefined) => (a ? bySection.get(a.sectionId) : undefined),
|
||||
/** Название для меню и списков: без названия раздела в начале. */
|
||||
short: (a: ArticleListItem) => shortTitle(a.title, bySection.get(a.sectionId)?.name),
|
||||
};
|
||||
}, [data, isLoading, error]);
|
||||
}
|
||||
|
||||
/** Адрес статьи: закреплённая шпаргалка живёт на своём экране. */
|
||||
export const articleHref = (a: { slug: string; pinned?: boolean }) => (a.pinned ? '/cheatsheet' : `/a/${a.slug}`);
|
||||
+31
-4
@@ -1,12 +1,39 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router-dom';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
// Шрифт Onest лежит в сборке (а не на Google Fonts): работает без сети и быстрее грузится
|
||||
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';
|
||||
|
||||
function App() {
|
||||
return <h1>Памятки монтажника</h1>;
|
||||
}
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
// Данные считаются свежими минуту: при переходах между экранами повторных запросов нет
|
||||
staleTime: 60_000,
|
||||
// Без сети запрос всё равно выполняем: ответ отдаст service worker из кеша
|
||||
networkMode: 'always',
|
||||
retry: (count, error) => !(error instanceof ApiError && error.status >= 400) && count < 1,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
mutations: { networkMode: 'always' },
|
||||
},
|
||||
});
|
||||
|
||||
// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
|
||||
registerSW({ immediate: true });
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</QueryClientProvider>
|
||||
</StrictMode>,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
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 { pushRecent, useFavorites } from '../lib/store';
|
||||
import { useTheme } from '../lib/theme';
|
||||
import { useNav } from '../lib/tree';
|
||||
|
||||
/** Прокрутка страницы: показывать ли липкую шапку (после 160 px) и прогресс чтения шагами по 2%. */
|
||||
function useReadProgress() {
|
||||
const [state, setState] = useState({ scrolled: false, progress: 0 });
|
||||
useEffect(() => {
|
||||
let frame = 0;
|
||||
const update = () => {
|
||||
frame = 0;
|
||||
const max = document.documentElement.scrollHeight - window.innerHeight;
|
||||
const p = max > 0 ? Math.min(1, window.scrollY / max) : 0;
|
||||
const next = { scrolled: window.scrollY > 160, progress: Math.round(p * 50) / 50 };
|
||||
setState((s) => (s.scrolled === next.scrolled && s.progress === next.progress ? s : next));
|
||||
};
|
||||
const onScroll = () => {
|
||||
if (!frame) frame = requestAnimationFrame(update);
|
||||
};
|
||||
update();
|
||||
window.addEventListener('scroll', onScroll, { passive: true });
|
||||
return () => {
|
||||
window.removeEventListener('scroll', onScroll);
|
||||
cancelAnimationFrame(frame);
|
||||
};
|
||||
}, []);
|
||||
return state;
|
||||
}
|
||||
|
||||
const scrollToHeading = (id: string) => document.getElementById(id)?.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
||||
|
||||
export function ArticlePage() {
|
||||
const { slug = '' } = useParams();
|
||||
// key: при переходе на другую статью состояние (оглавление, просмотр фото) создаётся заново
|
||||
return <ArticleView key={slug} slug={slug} />;
|
||||
}
|
||||
|
||||
function ArticleView({ slug }: { slug: string }) {
|
||||
const nav = useNav();
|
||||
const { data: art, isLoading, error } = useArticle(slug);
|
||||
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);
|
||||
|
||||
const listItem = nav.article(slug);
|
||||
const section = nav.sectionOf(art ?? listItem);
|
||||
|
||||
useEffect(() => {
|
||||
if (art) pushRecent(art.slug);
|
||||
}, [art]);
|
||||
|
||||
// При переходе на другую статью начинаем чтение сверху
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0);
|
||||
}, [slug]);
|
||||
|
||||
const onImage = useCallback((start: number, figures: Figure[]) => setLightbox({ figures, start }), []);
|
||||
const titles = useCallback((s: string) => nav.article(s)?.title, [nav]);
|
||||
|
||||
// Закреплённая статья-шпаргалка открывается на своём экране
|
||||
if (art?.pinned && art.cheat) return <Navigate to="/cheatsheet" replace />;
|
||||
|
||||
const isFav = fav.has(slug);
|
||||
const title = art?.title ?? listItem?.title ?? '';
|
||||
const backTo = section ? `/s/${section.slug}` : '/';
|
||||
|
||||
const bar = (
|
||||
<nav className="tabbar tabbar--5" aria-label="Действия со статьёй">
|
||||
<button type="button" className="tab tab--btn" onClick={() => fav.toggle(slug)} aria-pressed={isFav}>
|
||||
<IconStar filled={isFav} />
|
||||
<span>{isFav ? 'В избранном' : 'Избранное'}</span>
|
||||
</button>
|
||||
<button type="button" className="tab tab--btn" onClick={() => setTocOpen(true)}>
|
||||
<IconList />
|
||||
<span>Оглавление</span>
|
||||
</button>
|
||||
<button type="button" className="tab tab--btn" onClick={() => setPrintOpen(true)}>
|
||||
<IconPrint />
|
||||
<span>Печать</span>
|
||||
</button>
|
||||
<button type="button" className="tab tab--btn" onClick={theme.cycle}>
|
||||
<IconTheme />
|
||||
<span>{theme.label}</span>
|
||||
</button>
|
||||
<button type="button" className="tab tab--btn" onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}>
|
||||
<IconUp />
|
||||
<span>Наверх</span>
|
||||
</button>
|
||||
</nav>
|
||||
);
|
||||
|
||||
if (!art) {
|
||||
const notFound = error instanceof ApiError && error.status === 404;
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||
</div>
|
||||
{title ? <h1 className="art-title">{title}</h1> : null}
|
||||
{isLoading ? (
|
||||
<Skeleton lines={8} />
|
||||
) : notFound ? (
|
||||
<Notice title="Статья не найдена">Возможно, её переименовали или сняли с публикации.</Notice>
|
||||
) : (
|
||||
<Notice title="Статья не загрузилась" tone="error">
|
||||
Нет сети, и эта статья ещё не сохранена на устройстве. Откройте её при связи или скачайте раздел заранее.
|
||||
</Notice>
|
||||
)}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const meta = (
|
||||
<dl className="meta">
|
||||
{art.docCode ? (
|
||||
<>
|
||||
<dt>Шифр</dt>
|
||||
<dd className="meta-break">{art.docCode}</dd>
|
||||
</>
|
||||
) : null}
|
||||
<dt>Версия</dt>
|
||||
<dd>v{art.version}</dd>
|
||||
<dt>Обновлено</dt>
|
||||
<dd>{formatDate(art.updatedAt)}</dd>
|
||||
</dl>
|
||||
);
|
||||
|
||||
const sources = art.attachments.map((f) => (
|
||||
<a key={f.id} href={f.url} download={f.filename} className="src-card">
|
||||
<span className="src-ico" aria-hidden="true">
|
||||
{fileExt(f.filename)}
|
||||
</span>
|
||||
<span className="src-main">
|
||||
<span className="src-label">Исходник</span>
|
||||
<span className="src-name">{f.filename}</span>
|
||||
<span className="src-meta">
|
||||
{fileExt(f.filename)} · {formatBytes(f.size)}
|
||||
</span>
|
||||
</span>
|
||||
<span className="src-btn">Скачать</span>
|
||||
</a>
|
||||
));
|
||||
|
||||
const toc = art.toc.map((t, i) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
className="toc-row"
|
||||
onClick={() => {
|
||||
setTocOpen(false);
|
||||
scrollToHeading(t.id);
|
||||
}}
|
||||
>
|
||||
<span className="toc-n">{num2(i + 1)}</span>
|
||||
{t.text}
|
||||
</button>
|
||||
));
|
||||
|
||||
return (
|
||||
<Screen bar={bar}>
|
||||
{/* Липкая шапка на телефоне: появляется после 160 px прокрутки */}
|
||||
<div className={scrolled ? 'sticky-head is-on' : 'sticky-head'} aria-hidden={!scrolled}>
|
||||
<div className="sticky-head-sec">{section?.name}</div>
|
||||
<div className="sticky-head-title">{art.title}</div>
|
||||
<div className="sticky-head-bar" style={{ width: `${progress * 100}%` }} />
|
||||
</div>
|
||||
|
||||
{/* Верхняя панель на компьютере */}
|
||||
<div className="deskbar">
|
||||
<div className="crumbs">
|
||||
{nav.space?.name} / {section ? <Link to={`/s/${section.slug}`}>{section.name}</Link> : null} /{' '}
|
||||
<strong>{nav.short(art)}</strong>
|
||||
</div>
|
||||
{cached ? <OfflinePill long /> : null}
|
||||
<button type="button" className="btn btn--ghost" onClick={() => fav.toggle(slug)} aria-pressed={isFav}>
|
||||
{isFav ? '★ В избранном' : '☆ В избранное'}
|
||||
</button>
|
||||
<button type="button" className="btn btn--ghost" onClick={() => setPrintOpen(true)}>
|
||||
<IconPrint size={20} />
|
||||
Печать / PDF
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="art-layout">
|
||||
<article className="art">
|
||||
<div className="topline art-topline">
|
||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||
{cached ? <OfflinePill /> : null}
|
||||
</div>
|
||||
<div className="art-over">{section?.name}</div>
|
||||
<h1 className="art-title">{art.title}</h1>
|
||||
{art.summary ? <p className="art-summary">{art.summary}</p> : null}
|
||||
<div className="art-meta-mobile">{meta}</div>
|
||||
{art.equipment.length ? (
|
||||
<div className="tags">
|
||||
{art.equipment.map((e) => (
|
||||
<span key={e} className="tag tag--equip">
|
||||
{e}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<ArticleBody html={art.bodyHtml} slug={art.slug} version={art.version} onImage={onImage} titles={titles} />
|
||||
|
||||
{art.tags.length ? (
|
||||
<div className="hashtags">
|
||||
{art.tags.map((t) => (
|
||||
<Link key={t} to={`/search?q=${encodeURIComponent(t)}`} className="hashtag">
|
||||
#{t}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="art-src-mobile">{sources}</div>
|
||||
</article>
|
||||
|
||||
<aside className="art-aside">
|
||||
{art.toc.length ? (
|
||||
<div className="aside-card aside-toc">
|
||||
<div className="aside-caps">Оглавление</div>
|
||||
{toc}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="aside-card aside-meta">{meta}</div>
|
||||
{sources}
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
{tocOpen ? (
|
||||
<Sheet title="Оглавление" onClose={() => setTocOpen(false)}>
|
||||
<div className="sheet-scroll">{toc.length ? toc : <div className="sheet-empty">В статье нет разделов</div>}</div>
|
||||
</Sheet>
|
||||
) : null}
|
||||
{printOpen ? (
|
||||
<PrintSheet
|
||||
slug={art.slug}
|
||||
title={art.title}
|
||||
textLength={art.bodyMd.length}
|
||||
images={art.imageCount}
|
||||
onClose={() => setPrintOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
{lightbox ? <Lightbox figures={lightbox.figures} start={lightbox.start} onClose={() => setLightbox(null)} /> : null}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { CheatLine, Seg } from '@kb/shared';
|
||||
import { ArticleBody } from '../components/ArticleBody';
|
||||
import { IconPrint } from '../components/Icons';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { Notice, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
|
||||
/** Текст с жирными фрагментами. В запретах жирное красное, в «Всегда» просто жирное. */
|
||||
export function Segs({ segs }: { segs: Seg[] }) {
|
||||
return (
|
||||
<>
|
||||
{segs.map((s, i) => (s.bold ? <strong key={i}>{s.t}</strong> : <span key={i}>{s.t}</span>))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SourceChips({ line, small }: { line: CheatLine; small?: boolean }) {
|
||||
const nav = useNav();
|
||||
if (!line.links.length) return null;
|
||||
return (
|
||||
<div className="chips chips--tight">
|
||||
{line.links.map((slug) => {
|
||||
const a = nav.article(slug);
|
||||
return (
|
||||
<Link key={slug} to={a ? articleHref(a) : `/a/${slug}`} className={small ? 'linkchip linkchip--sm' : 'linkchip'}>
|
||||
<span aria-hidden="true">→</span> {a ? nav.short(a) : slug}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Образец цвета по коду RAL. Сами цвета заданы токенами --ral-XXXX в tokens.css. */
|
||||
const ralVar = (code: string) => `var(--ral-${code.replace(/\D/g, '')}, transparent)`;
|
||||
|
||||
export function CheatSheetPage() {
|
||||
const nav = useNav();
|
||||
const { data: art, isLoading } = useArticle(nav.pinned?.slug);
|
||||
const cheat = art?.cheat;
|
||||
|
||||
return (
|
||||
<Screen tab="cheat">
|
||||
<header className="home-head">
|
||||
<div className="home-head-text">
|
||||
<div className="over-caps">Закреплено</div>
|
||||
<h1 className="cheat-title">Шпаргалка</h1>
|
||||
</div>
|
||||
<ThemeButton />
|
||||
</header>
|
||||
|
||||
{!art ? (
|
||||
isLoading || nav.isLoading ? (
|
||||
<Skeleton lines={8} />
|
||||
) : (
|
||||
<Notice title="Шпаргалка недоступна">
|
||||
{nav.pinned ? 'Нет сети, и шпаргалка ещё не сохранена на устройстве.' : 'Закреплённой статьи пока нет.'}
|
||||
</Notice>
|
||||
)
|
||||
) : !cheat ? (
|
||||
// У закреплённой статьи нет структуры шпаргалки: показываем её как обычную статью
|
||||
<ArticleBody html={art.bodyHtml} slug={art.slug} version={art.version} />
|
||||
) : (
|
||||
<>
|
||||
<p className="cheat-intro">Все цифры и запреты на одном экране. Каждая строка ведёт в статью.</p>
|
||||
<Link to={`/print/${art.slug}?auto=1`} className="btn btn--outline btn--block cheat-print">
|
||||
<IconPrint size={22} />
|
||||
Распечатать на 1 лист / PDF
|
||||
</Link>
|
||||
|
||||
{cheat.bans.length ? (
|
||||
<section className="cs-box cs-box--red">
|
||||
<h2 className="cs-box-head">
|
||||
<span className="cs-minus" aria-hidden="true" />
|
||||
ЗАПРЕЩЕНО
|
||||
<span className="cs-box-n">{cheat.bans.length}</span>
|
||||
</h2>
|
||||
{cheat.bans.map((b, i) => (
|
||||
<div key={i} className="cs-ban">
|
||||
<span className="cs-ban-n">{String(i + 1).padStart(2, '0')}</span>
|
||||
<div className="cs-ban-main">
|
||||
<div className="cs-text">
|
||||
<Segs segs={b.segs} />
|
||||
</div>
|
||||
<SourceChips line={b} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{cheat.facts.length ? (
|
||||
<section className="block">
|
||||
<div className="cs-h">
|
||||
<h2>Цифры</h2>
|
||||
<span>{cheat.facts.length}</span>
|
||||
</div>
|
||||
<div className="list">
|
||||
{cheat.facts.map((f, i) => (
|
||||
<div key={i} className="cs-fact">
|
||||
<div className="cs-fact-row">
|
||||
<span className="cs-fact-t">
|
||||
<Segs segs={f.segs} />
|
||||
</span>
|
||||
<span className="cs-fact-v">{f.value}</span>
|
||||
</div>
|
||||
<SourceChips line={f} small />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{cheat.colors.length ? (
|
||||
<section className="block">
|
||||
<div className="cs-h">
|
||||
<h2>Цвета</h2>
|
||||
</div>
|
||||
<div className="cs-colors">
|
||||
{cheat.colors.map((c) => (
|
||||
<div key={c.code} className="cs-color">
|
||||
<div className="cs-swatch" style={{ background: ralVar(c.code) }} />
|
||||
<div className="cs-color-text">
|
||||
<div className="cs-color-code">{c.code}</div>
|
||||
<div className="cs-color-label">{c.label}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{cheat.always.length ? (
|
||||
<section className="cs-box cs-box--green">
|
||||
<h2 className="cs-box-head">ВСЕГДА</h2>
|
||||
{cheat.always.map((a, i) => (
|
||||
<div key={i} className="cs-always">
|
||||
<span className="cs-tick" aria-hidden="true" />
|
||||
<span className="cs-text">
|
||||
<Segs segs={a.segs} />
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { CodeTag, Notice, ThemeButton } from '../components/ui';
|
||||
import { useFavorites } from '../lib/store';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
|
||||
// Экрана «Избранное» в макете нет (есть только вкладка), сделан в стиле списков главной.
|
||||
export function FavoritesPage() {
|
||||
const nav = useNav();
|
||||
const { favs } = useFavorites();
|
||||
const items = favs.map((s) => nav.article(s)).filter((a) => !!a);
|
||||
|
||||
return (
|
||||
<Screen tab="fav">
|
||||
<header className="home-head">
|
||||
<div className="home-head-text">
|
||||
<h1 className="cheat-title">Избранное</h1>
|
||||
</div>
|
||||
<ThemeButton />
|
||||
</header>
|
||||
|
||||
{items.length ? (
|
||||
<div className="list">
|
||||
{items.map((a) => (
|
||||
<Link key={a!.slug} to={articleHref(a!)} className="list-row">
|
||||
<CodeTag code={nav.sectionOf(a)?.code ?? ''} />
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">{nav.short(a!)}</span>
|
||||
<span className="list-row-sub">{nav.sectionOf(a)?.name}</span>
|
||||
</span>
|
||||
<span className="list-row-chev" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Notice title="Пока пусто">
|
||||
Откройте статью и нажмите «Избранное» внизу экрана: она появится здесь и на главной.
|
||||
</Notice>
|
||||
)}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { formatRecent } from '../lib/format';
|
||||
import { useFavorites, useRecent } from '../lib/store';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
|
||||
// Быстрые запросы под строкой поиска (из макета): самые ходовые артикулы
|
||||
const QUICK = ['MG-12', '2273-245', 'RAL 7024', 'порт PoE'];
|
||||
|
||||
export function SearchIcon() {
|
||||
return (
|
||||
<span className="search-ico" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function HomePage() {
|
||||
const nav = useNav();
|
||||
const navigate = useNavigate();
|
||||
const { favs } = useFavorites();
|
||||
const recent = useRecent();
|
||||
const cheat = useArticle(nav.pinned?.slug).data?.cheat;
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// «/» на клавиатуре открывает поиск (подсказка в поле на компьютере)
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === '/' && !(e.target instanceof HTMLInputElement) && !(e.target instanceof HTMLTextAreaElement)) {
|
||||
e.preventDefault();
|
||||
navigate('/search');
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [navigate]);
|
||||
|
||||
const favArticles = favs.map((s) => nav.article(s)).filter((a) => !!a);
|
||||
const recentArticles = recent
|
||||
.map((r) => ({ r, a: nav.article(r.slug) }))
|
||||
.filter((x) => !!x.a)
|
||||
.slice(0, 5);
|
||||
const odd = nav.sections.length % 2 === 1;
|
||||
|
||||
return (
|
||||
<Screen tab="home" wide>
|
||||
<header className="home-head">
|
||||
<div className="home-head-text">
|
||||
<h1 className="home-title">Памятки монтажника</h1>
|
||||
<div className="home-sub">wiki.suchtech.ru{nav.space ? ` · ${nav.space.name}` : ''}</div>
|
||||
</div>
|
||||
<ThemeButton />
|
||||
</header>
|
||||
|
||||
{/* Поле на главной только открывает экран поиска: печатать удобнее там, где сразу видны результаты */}
|
||||
<div className="home-search">
|
||||
<label className="search-field">
|
||||
<SearchIcon />
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="search-input"
|
||||
type="search"
|
||||
enterKeyHint="search"
|
||||
placeholder="Цифра, артикул или слово"
|
||||
aria-label="Поиск по статьям"
|
||||
onChange={(e) => {
|
||||
if (e.target.value) navigate(`/search?q=${encodeURIComponent(e.target.value)}`);
|
||||
}}
|
||||
/>
|
||||
<span className="kbd" aria-hidden="true">
|
||||
/
|
||||
</span>
|
||||
</label>
|
||||
<div className="chips">
|
||||
{QUICK.map((q) => (
|
||||
<Link key={q} className="chip" to={`/search?q=${encodeURIComponent(q)}`}>
|
||||
{q}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{nav.error && !nav.articles.length ? (
|
||||
<Notice title="Не удалось загрузить статьи" tone="error">
|
||||
Проверьте связь и обновите страницу.
|
||||
</Notice>
|
||||
) : null}
|
||||
{nav.isLoading ? <Skeleton lines={6} /> : null}
|
||||
|
||||
<div className="home-top">
|
||||
{nav.pinned ? (
|
||||
<Link to="/cheatsheet" className="cheat-card">
|
||||
<div className="cheat-card-caps">
|
||||
<span>Закреплено</span>
|
||||
{cheat ? (
|
||||
<span>
|
||||
{cheat.bans.length} {plural(cheat.bans.length, ['запрет', 'запрета', 'запретов'])} ·{' '}
|
||||
{cheat.facts.length} {plural(cheat.facts.length, ['цифра', 'цифры', 'цифр'])}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="cheat-card-title">Шпаргалка</div>
|
||||
<div className="cheat-card-text">{nav.pinned.summary}</div>
|
||||
{cheat?.facts.length ? (
|
||||
<div className="cheat-card-facts">
|
||||
{cheat.facts.slice(0, 4).map((f, i) => (
|
||||
<div key={i} className="cheat-card-fact">
|
||||
<div className="cheat-card-value">{f.value}</div>
|
||||
<div className="cheat-card-label">{f.segs.map((s) => s.t).join('')}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</Link>
|
||||
) : null}
|
||||
|
||||
{recentArticles.length ? (
|
||||
<section className="block home-recent">
|
||||
<Caps>Недавно открытые</Caps>
|
||||
<div className="list">
|
||||
{recentArticles.map(({ r, a }) => (
|
||||
<Link key={r.slug} to={articleHref(a!)} className="list-row">
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">{nav.short(a!)}</span>
|
||||
<span className="list-row-sub">{nav.sectionOf(a)?.name}</span>
|
||||
</span>
|
||||
<span className="list-row-meta">{formatRecent(r.at)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{nav.sections.length ? (
|
||||
<section className="block">
|
||||
<Caps>Разделы</Caps>
|
||||
<div className="sec-grid">
|
||||
{nav.sections.map((s, i) => (
|
||||
<Link
|
||||
key={s.id}
|
||||
to={`/s/${s.slug}`}
|
||||
className={odd && i === nav.sections.length - 1 ? 'sec-card sec-card--row' : 'sec-card'}
|
||||
>
|
||||
<Plaque code={s.code} color={s.color} />
|
||||
<span>
|
||||
<span className="sec-card-name">{s.name}</span>
|
||||
<span className="sec-card-n">
|
||||
{s.articles.length} {plural(s.articles.length, ['статья', 'статьи', 'статей'])}
|
||||
</span>
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{favArticles.length ? (
|
||||
<section className="block">
|
||||
<Caps>Избранное</Caps>
|
||||
<div className="list list--cards">
|
||||
{favArticles.map((a) => (
|
||||
<Link key={a!.slug} to={articleHref(a!)} className="list-row">
|
||||
<CodeTag code={nav.sectionOf(a)?.code ?? ''} />
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-over">{nav.sectionOf(a)?.name}</span>
|
||||
<span className="list-row-title">{nav.short(a!)}</span>
|
||||
<span className="list-row-desc">{a!.summary}</span>
|
||||
</span>
|
||||
<span className="list-row-chev" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// Печатная версия статьи и шпаргалки: /print/:slug?fmt=A4&photos=1&checks=1&keyOnly=0&auto=1
|
||||
// Всегда светлая и читается в ч/б. Колонтитулы и «Стр. N из M» рисует браузер по правилам @page.
|
||||
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { Link, useParams, useSearchParams } from 'react-router-dom';
|
||||
import qrcode from 'qrcode-generator';
|
||||
import type { ArticleDto } from '@kb/shared';
|
||||
import { Notice, Skeleton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { formatDate } from '../lib/format';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
import { Segs } from './CheatSheet';
|
||||
import '../styles/print.css';
|
||||
|
||||
/** Строка для CSS content: экранируем кавычки и обратную косую. */
|
||||
const cssStr = (s: string) => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, ' ')}"`;
|
||||
|
||||
function Qr({ url, size }: { url: string; size: number }) {
|
||||
const svg = useMemo(() => {
|
||||
const qr = qrcode(0, 'M');
|
||||
qr.addData(url);
|
||||
qr.make();
|
||||
return qr.createSvgTag({ cellSize: 2, margin: 0, scalable: true });
|
||||
}, [url]);
|
||||
return <span className="pr-qr" style={{ width: size, height: size }} dangerouslySetInnerHTML={{ __html: svg }} />;
|
||||
}
|
||||
|
||||
function CheatPrint({ art, today, site }: { art: ArticleDto; today: string; site: string }) {
|
||||
const nav = useNav();
|
||||
const c = art.cheat!;
|
||||
return (
|
||||
<div className="pr-cheat">
|
||||
<div className="pr-cheat-head">
|
||||
<span className="pr-cheat-title">Шпаргалка монтажника</span>
|
||||
<span>
|
||||
{nav.space?.name} · {today}
|
||||
</span>
|
||||
</div>
|
||||
<div className="pr-cheat-grid">
|
||||
<div>
|
||||
<div className="pr-caps">ЦИФРЫ</div>
|
||||
{c.facts.map((f, i) => (
|
||||
<div key={i} className="pr-fact">
|
||||
<span>
|
||||
<Segs segs={f.segs} />
|
||||
</span>
|
||||
<strong>{f.value}</strong>
|
||||
</div>
|
||||
))}
|
||||
{c.colors.length ? (
|
||||
<div className="pr-colors">
|
||||
{c.colors.map((col) => (
|
||||
<div key={col.code} className="pr-color">
|
||||
<span className="pr-swatch" style={{ background: `var(--ral-${col.code.replace(/\D/g, '')}, transparent)` }} />
|
||||
<span>
|
||||
<strong>{col.code}</strong> {col.label.toLowerCase()}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="pr-cheat-right">
|
||||
{c.bans.length ? (
|
||||
<section className="pr-box pr-box--red">
|
||||
<div className="pr-box-head">✕ ЗАПРЕЩЕНО</div>
|
||||
{c.bans.map((b, i) => (
|
||||
<div key={i} className="pr-ban">
|
||||
<strong>{String(i + 1).padStart(2, '0')}</strong>
|
||||
<span>
|
||||
<Segs segs={b.segs} />
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
{c.always.length ? (
|
||||
<section className="pr-box">
|
||||
<div className="pr-box-head">✓ ВСЕГДА</div>
|
||||
{c.always.map((a, i) => (
|
||||
<div key={i} className="pr-always">
|
||||
<span className="pr-square" />
|
||||
<span>
|
||||
<Segs segs={a.segs} />
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<div className="pr-cheat-foot">
|
||||
<span>Подробности и фото в статьях: {site} · ламинировать и держать в стойке</span>
|
||||
<Qr url={`${location.origin}/cheatsheet`} size={56} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function PrintPage() {
|
||||
const { slug = '' } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const nav = useNav();
|
||||
const { data: art, isLoading } = useArticle(slug);
|
||||
const bodyRef = useRef<HTMLDivElement>(null);
|
||||
const printed = useRef(false);
|
||||
|
||||
const fmt = params.get('fmt') === 'A5' ? 'A5' : 'A4';
|
||||
const photos = params.get('photos') !== '0';
|
||||
const checks = params.get('checks') !== '0';
|
||||
const keyOnly = params.get('keyOnly') === '1';
|
||||
const auto = params.get('auto') === '1';
|
||||
|
||||
const section = nav.sectionOf(art);
|
||||
const today = formatDate(new Date());
|
||||
const site = location.host;
|
||||
const isCheat = !!art?.cheat;
|
||||
const url = art ? `${location.origin}${articleHref(art)}` : '';
|
||||
|
||||
// В печатной версии [[ссылки]] становятся жирным названием статьи
|
||||
const html = useMemo(
|
||||
() =>
|
||||
(art?.bodyHtml ?? '').replace(
|
||||
/<a class="kb-link[^"]*"[^>]*>.*?<span class="kb-link-t">(.*?)<\/span><\/a>/g,
|
||||
'<strong>$1</strong>',
|
||||
),
|
||||
[art?.bodyHtml],
|
||||
);
|
||||
|
||||
// Автопечать: ждём, пока догрузятся картинки, иначе на листе будут пустые рамки
|
||||
useEffect(() => {
|
||||
if (!art || !auto || printed.current) return;
|
||||
printed.current = true;
|
||||
const imgs = [...(bodyRef.current?.querySelectorAll('img') ?? [])];
|
||||
imgs.forEach((img) => (img.loading = 'eager'));
|
||||
const waits = imgs.map((img) =>
|
||||
img.complete ? Promise.resolve() : new Promise<void>((r) => (img.onload = img.onerror = () => r())),
|
||||
);
|
||||
const timeout = new Promise<void>((r) => setTimeout(r, 4000));
|
||||
void Promise.race([Promise.all(waits), timeout]).then(() => setTimeout(() => window.print(), 150));
|
||||
}, [art, auto]);
|
||||
|
||||
// Колонтитулы: шифр, версия и дата в шапке каждого листа, номер страницы внизу
|
||||
const pageCss = art
|
||||
? `@page { size: ${fmt}${isCheat ? '' : ' portrait'}; margin: ${isCheat ? '11mm 12mm' : '18mm 14mm 16mm'};
|
||||
${
|
||||
isCheat
|
||||
? ''
|
||||
: `@top-left { content: ${cssStr(`Памятки монтажника · ${nav.space?.name ?? ''} · ${section?.name ?? ''}`)}; font: 700 9pt Onest, sans-serif; border-bottom: 1.5px solid currentColor; padding-bottom: 2mm; }
|
||||
@top-right { content: ${cssStr([art.docCode, `v${art.version}`, formatDate(art.updatedAt)].filter(Boolean).join(' · '))}; font: 9pt Onest, sans-serif; border-bottom: 1.5px solid currentColor; padding-bottom: 2mm; }
|
||||
@bottom-left { content: ${cssStr(`Напечатано ${today} · ${url.replace(/^https?:\/\//, '')}`)}; font: 9pt Onest, sans-serif; }
|
||||
@bottom-right { content: "Стр. " counter(page) " из " counter(pages); font: 700 9pt Onest, sans-serif; }`
|
||||
}
|
||||
}`
|
||||
: '';
|
||||
|
||||
if (!art) {
|
||||
return (
|
||||
<div className="pr-screen">
|
||||
<div className="pr-tools">
|
||||
<Link to="/" className="btn">
|
||||
‹ Назад
|
||||
</Link>
|
||||
</div>
|
||||
{isLoading ? <Skeleton /> : <Notice title="Нужна сеть для PDF">Статья не сохранена на устройстве.</Notice>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const cls = ['pr-body', photos ? '' : 'pr-no-photos', checks ? '' : 'pr-no-checks', keyOnly ? 'pr-key-only' : '']
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
|
||||
return (
|
||||
<div className="pr-screen">
|
||||
<style>{pageCss}</style>
|
||||
<div className="pr-tools">
|
||||
<Link to={articleHref(art)} className="btn">
|
||||
‹ Назад
|
||||
</Link>
|
||||
<span className="pr-tools-info">
|
||||
{fmt} · в окне печати можно выбрать «Сохранить как PDF»
|
||||
</span>
|
||||
<button type="button" className="btn btn--solid" onClick={() => window.print()}>
|
||||
Печать
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className={`pr-sheet pr-sheet--${fmt}${isCheat ? ' pr-sheet--cheat' : ''}`}>
|
||||
{isCheat ? (
|
||||
<CheatPrint art={art} today={today} site={site} />
|
||||
) : (
|
||||
<>
|
||||
{/* Шапка для предпросмотра на экране; на бумаге её заменяют колонтитулы @page */}
|
||||
<div className="pr-runhead">
|
||||
<strong>
|
||||
Памятки монтажника · {nav.space?.name} · {section?.name}
|
||||
</strong>
|
||||
<span>{[art.docCode, `v${art.version}`, formatDate(art.updatedAt)].filter(Boolean).join(' · ')}</span>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="pr-title">{art.title}</h1>
|
||||
{art.summary ? <p className="pr-summary">{art.summary}</p> : null}
|
||||
</div>
|
||||
<div ref={bodyRef} className={cls} dangerouslySetInnerHTML={{ __html: html }} />
|
||||
<div className="pr-foot">
|
||||
<Qr url={url} size={76} />
|
||||
<div className="pr-foot-text">
|
||||
<strong>Актуальная версия всегда онлайн</strong>
|
||||
<span>{url.replace(/^https?:\/\//, '')} · проверьте версию перед монтажом</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import { keepPreviousData, useQuery } from '@tanstack/react-query';
|
||||
import { compactSearch, normalizeSearch, type Highlight, type SearchResponse } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { Caps } from '../components/ui';
|
||||
import { api } from '../lib/api';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
import { SearchIcon } from './Home';
|
||||
|
||||
// Примеры для пустого экрана (из макета)
|
||||
const HINTS: [string, string][] = [
|
||||
['MG-12', 'сальник'],
|
||||
['2273-245', 'клемма WAGO'],
|
||||
['RAL 7024', 'цвет навеса'],
|
||||
['порт PoE', 'вызывная панель'],
|
||||
['1,2 м', 'зачистка ВОК'],
|
||||
];
|
||||
|
||||
const DEBOUNCE_MS = 150;
|
||||
|
||||
function Marked({ parts }: { parts: Highlight[] }) {
|
||||
return <>{parts.map((p, i) => (p.hit ? <mark key={i}>{p.t}</mark> : <span key={i}>{p.t}</span>))}</>;
|
||||
}
|
||||
|
||||
export function SearchPage() {
|
||||
const nav = useNav();
|
||||
const [params, setParams] = useSearchParams();
|
||||
const [text, setText] = useState(params.get('q') ?? '');
|
||||
const [query, setQuery] = useState(text.trim());
|
||||
const [filter, setFilter] = useState<string>('all');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Ставим курсор в поле сразу при открытии экрана (в конец уже набранного текста)
|
||||
useEffect(() => {
|
||||
const el = inputRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
el.setSelectionRange(el.value.length, el.value.length);
|
||||
}, []);
|
||||
|
||||
// Запрос уходит не на каждую букву, а через 150 мс после последнего нажатия
|
||||
useEffect(() => {
|
||||
const id = setTimeout(() => {
|
||||
const q = text.trim();
|
||||
setQuery(q);
|
||||
setParams(q ? { q } : {}, { replace: true });
|
||||
}, DEBOUNCE_MS);
|
||||
return () => clearTimeout(id);
|
||||
}, [text, setParams]);
|
||||
|
||||
const { data, error, isFetching } = useQuery({
|
||||
queryKey: ['search', query],
|
||||
queryFn: () => api<SearchResponse>(`/search?q=${encodeURIComponent(query)}`),
|
||||
enabled: query.length > 0,
|
||||
// Пока грузится новый ответ, показываем предыдущий: список не мигает при наборе
|
||||
placeholderData: keepPreviousData,
|
||||
staleTime: 5 * 60_000,
|
||||
});
|
||||
|
||||
// Без сети сервер недоступен: ищем по названиям, описаниям и тегам из сохранённого списка статей
|
||||
const offline = useMemo<SearchResponse | null>(() => {
|
||||
if (!error || !query) return null;
|
||||
const words = normalizeSearch(query).split(' ').filter(Boolean);
|
||||
const whole = compactSearch(query);
|
||||
const articles = nav.articles
|
||||
.filter((a) => {
|
||||
const hay = [a.title, a.summary, ...a.tags, ...a.equipment, a.docCode ?? ''].join(' ');
|
||||
const norm = normalizeSearch(hay);
|
||||
const compact = compactSearch(hay);
|
||||
return (whole.length >= 3 && compact.includes(whole)) || words.every((w) => norm.includes(w) || compact.includes(compactSearch(w)));
|
||||
})
|
||||
.map((a) => ({
|
||||
slug: a.slug,
|
||||
title: [{ t: a.title, hit: false }],
|
||||
section: nav.sectionOf(a)?.name ?? '',
|
||||
sectionId: a.sectionId,
|
||||
snippet: [{ t: a.summary, hit: false }],
|
||||
pinned: a.pinned,
|
||||
}));
|
||||
return { q: query, facts: [], articles };
|
||||
}, [error, query, nav]);
|
||||
|
||||
const result = query ? (offline ?? data) : undefined;
|
||||
const byFilter = <T extends { sectionId: string }>(items: T[], isCheat: (x: T) => boolean) =>
|
||||
filter === 'all' ? items : filter === 'cheat' ? items.filter(isCheat) : items.filter((x) => x.sectionId === filter && !isCheat(x));
|
||||
const facts = byFilter(result?.facts ?? [], (f) => f.cheat);
|
||||
const articles = byFilter(result?.articles ?? [], (a) => a.pinned);
|
||||
const nothing = !!result && !facts.length && !articles.length && !isFetching;
|
||||
|
||||
const chips = [
|
||||
{ id: 'all', label: 'Все' },
|
||||
...(nav.pinned ? [{ id: 'cheat', label: 'Шпаргалка' }] : []),
|
||||
...nav.sections.map((s) => ({ id: s.id, label: s.name })),
|
||||
];
|
||||
|
||||
return (
|
||||
<Screen tab="search">
|
||||
<div className="search-top">
|
||||
<label className="search-field search-field--active">
|
||||
<SearchIcon />
|
||||
<input
|
||||
ref={inputRef}
|
||||
className="search-input"
|
||||
type="search"
|
||||
enterKeyHint="search"
|
||||
autoComplete="off"
|
||||
autoCorrect="off"
|
||||
autoCapitalize="off"
|
||||
spellCheck={false}
|
||||
placeholder="Цифра, артикул или слово"
|
||||
aria-label="Поиск по статьям"
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
/>
|
||||
{text ? (
|
||||
<button
|
||||
type="button"
|
||||
className="search-clear"
|
||||
aria-label="Очистить"
|
||||
onClick={() => {
|
||||
setText('');
|
||||
inputRef.current?.focus();
|
||||
}}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
) : null}
|
||||
</label>
|
||||
<div className="chips chips--scroll" role="group" aria-label="Где искать">
|
||||
{chips.map((c) => (
|
||||
<button
|
||||
key={c.id}
|
||||
type="button"
|
||||
className={filter === c.id ? 'chip chip--filter chip--on' : 'chip chip--filter'}
|
||||
aria-pressed={filter === c.id}
|
||||
onClick={() => setFilter(c.id)}
|
||||
>
|
||||
{c.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Число результатов для экранных читалок */}
|
||||
<div className="sr-only" role="status" aria-live="polite">
|
||||
{result ? `Найдено: цифр ${facts.length}, статей ${articles.length}` : ''}
|
||||
</div>
|
||||
|
||||
{!query ? (
|
||||
<div className="block">
|
||||
<div className="search-empty-title">Ищите по цифрам, артикулам и словам</div>
|
||||
<div className="search-empty-text">
|
||||
Поиск идёт по всем статьям и шпаргалке, без учёта регистра. Попробуйте:
|
||||
</div>
|
||||
<div className="list">
|
||||
{HINTS.map(([t, d]) => (
|
||||
<button key={t} type="button" className="hint-row" onClick={() => setText(t)}>
|
||||
<span className="hint-row-q">{t}</span>
|
||||
<span className="hint-row-d">{d}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{offline ? (
|
||||
<div className="search-offline">Нет сети: поиск только по названиям, описаниям и тегам статей.</div>
|
||||
) : null}
|
||||
|
||||
{nothing ? (
|
||||
<div className="notice">
|
||||
<div className="notice-title">Ничего не нашлось</div>
|
||||
<div className="notice-text">
|
||||
Проверьте раскладку или ищите часть артикула: «2273» вместо «2273-245».
|
||||
{filter !== 'all' ? ' Или снимите фильтр по разделу.' : ''}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{facts.length ? (
|
||||
<section className="block">
|
||||
<Caps>Цифры · {facts.length}</Caps>
|
||||
{facts.map((f, i) => (
|
||||
<div key={i} className="fact-card">
|
||||
<div className="fact-card-value">
|
||||
<Marked parts={f.value} />
|
||||
</div>
|
||||
{f.label.some((p) => p.t) ? (
|
||||
<div className="fact-card-label">
|
||||
<Marked parts={f.label} />
|
||||
</div>
|
||||
) : null}
|
||||
<div className="chips chips--tight">
|
||||
{f.links.map((l) => {
|
||||
const a = nav.article(l.slug);
|
||||
return (
|
||||
<Link key={l.slug} to={a ? articleHref(a) : `/a/${l.slug}`} className="linkchip">
|
||||
<span aria-hidden="true">→</span> {a ? nav.short(a) : l.title}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{articles.length ? (
|
||||
<section className="block">
|
||||
<Caps>Статьи · {articles.length}</Caps>
|
||||
{articles.map((a) => (
|
||||
<Link key={a.slug} to={articleHref(a)} className="result-card">
|
||||
<div className="result-card-sec">{a.section}</div>
|
||||
<div className="result-card-title">
|
||||
<Marked parts={a.title} />
|
||||
</div>
|
||||
<div className="result-card-snip">
|
||||
<Marked parts={a.snippet} />
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</section>
|
||||
) : null}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
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';
|
||||
|
||||
export function SectionPage() {
|
||||
const { slug } = useParams();
|
||||
const nav = useNav();
|
||||
const section = nav.sections.find((s) => s.slug === slug);
|
||||
|
||||
if (!section) {
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
<ThemeButton />
|
||||
</div>
|
||||
{nav.isLoading ? <Skeleton lines={5} /> : <Notice title="Раздел не найден">Возможно, его переименовали или удалили.</Notice>}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const photos = section.articles.reduce((n, a) => n + a.imageCount, 0);
|
||||
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
<ThemeButton />
|
||||
</div>
|
||||
|
||||
<div className="sec-head">
|
||||
<Plaque code={section.code} color={section.color} size="lg" />
|
||||
<div>
|
||||
<h1 className="sec-title">{section.name}</h1>
|
||||
<div className="sec-meta">
|
||||
{section.articles.length} {plural(section.articles.length, ['статья', 'статьи', 'статей'])}
|
||||
{photos ? ` · ${photos} фото` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cacheSupported() ? <SectionOfflineRow section={section} /> : null}
|
||||
|
||||
<div className="art-cards">
|
||||
{section.articles.map((a, i) => (
|
||||
<Link key={a.id} to={articleHref(a)} className="art-card">
|
||||
<div className="art-card-head">
|
||||
<span className="art-card-n">{num2(i + 1)}</span>
|
||||
<span className="art-card-title">{nav.short(a)}</span>
|
||||
</div>
|
||||
{a.summary ? <div className="art-card-text">{a.summary}</div> : null}
|
||||
{a.tags.length ? (
|
||||
<div className="tags">
|
||||
{a.tags.slice(0, 4).map((t) => (
|
||||
<span key={t} className="tag">
|
||||
{t}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,716 @@
|
||||
/*
|
||||
* Блоки статьи. Классы kb-* ставит рендер packages/md/src/hast.ts.
|
||||
* Размеры и цвета: из макета new_design/ArticleBodyXL.dc.html.
|
||||
*/
|
||||
|
||||
.kb-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-10);
|
||||
font-size: var(--fs-18);
|
||||
line-height: var(--lh-body);
|
||||
font-weight: var(--wb);
|
||||
color: var(--ink);
|
||||
text-wrap: pretty;
|
||||
overflow-wrap: anywhere;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.kb-body p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* Жирный в тексте выделен акцентным цветом: это цифры и ключевые слова */
|
||||
.kb-b {
|
||||
font-weight: var(--ws);
|
||||
color: var(--acc);
|
||||
}
|
||||
|
||||
.kb-h2 {
|
||||
margin: var(--sp-7) 0 calc(var(--sp-2) * -1);
|
||||
padding-top: var(--sp-11);
|
||||
border-top: 2px solid var(--ln);
|
||||
font-size: var(--fs-22);
|
||||
line-height: 1.25;
|
||||
font-weight: 700;
|
||||
/* Чтобы заголовок не прятался под липкой шапкой при переходе из оглавления */
|
||||
scroll-margin-top: 80px;
|
||||
}
|
||||
|
||||
.kb-h3 {
|
||||
margin: var(--sp-2) 0 calc(var(--sp-4) * -1);
|
||||
font-size: var(--fs-19);
|
||||
line-height: var(--lh-snug);
|
||||
font-weight: 700;
|
||||
color: var(--acc);
|
||||
}
|
||||
|
||||
.kb-code {
|
||||
padding: 0 var(--sp-2);
|
||||
border-radius: var(--r-xs);
|
||||
background: var(--sf2);
|
||||
font-size: 0.92em;
|
||||
}
|
||||
|
||||
.kb-pre {
|
||||
margin: 0;
|
||||
padding: var(--sp-6) var(--sp-8);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
overflow-x: auto;
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
|
||||
.kb-quote {
|
||||
margin: 0;
|
||||
padding-left: var(--sp-8);
|
||||
border-left: var(--sp-2) solid var(--ln);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
.kb-hr {
|
||||
width: 100%;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
border-top: 2px solid var(--ln);
|
||||
}
|
||||
|
||||
.kb-a {
|
||||
color: inherit;
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.kb-ulink {
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
/* ---------- Ссылка-чип на статью: [[slug]] ---------- */
|
||||
.kb-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-3);
|
||||
min-height: 36px;
|
||||
padding: var(--sp-1) var(--sp-6);
|
||||
margin: 3px 0;
|
||||
border: var(--bw) solid var(--ink);
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
vertical-align: middle;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.kb-link--broken {
|
||||
border-color: var(--redS);
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
/* ---------- «Главное» ---------- */
|
||||
.kb-key {
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-block);
|
||||
overflow: hidden;
|
||||
background: var(--sf);
|
||||
}
|
||||
|
||||
.kb-hazard {
|
||||
height: 10px;
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 10px, var(--brand-ink) 10px 20px);
|
||||
}
|
||||
|
||||
.kb-key-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
padding: var(--sp-6) var(--sp-8) var(--sp-1);
|
||||
}
|
||||
|
||||
.kb-key-title {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--caps-wide);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.kb-key-count {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
.kb-key-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
grid-auto-flow: dense;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-5);
|
||||
}
|
||||
|
||||
.kb-key-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
min-width: 0;
|
||||
padding: var(--sp-6) var(--sp-7);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf2);
|
||||
border: var(--bw) solid var(--ln);
|
||||
}
|
||||
|
||||
.kb-key-item--wide {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.kb-key-label {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
|
||||
/* Узкая плитка: значение крупно */
|
||||
.kb-key-val {
|
||||
line-height: 1.35;
|
||||
}
|
||||
.kb-key-val .kb-key-v {
|
||||
font-size: var(--fs-21);
|
||||
font-weight: 700;
|
||||
color: var(--acc);
|
||||
line-height: 1.25;
|
||||
}
|
||||
.kb-key-val .kb-key-t {
|
||||
font-size: var(--fs-16);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
/* Широкая плитка: значение в строке текста */
|
||||
.kb-key-item--wide .kb-key-val {
|
||||
font-size: var(--fs-17);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.kb-key-item--wide .kb-key-v {
|
||||
font-size: var(--fs-19);
|
||||
}
|
||||
.kb-key-item--wide .kb-key-t {
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
/* ---------- Плашки: ЗАПРЕЩЕНО / ВНИМАНИЕ / СОВЕТ / СПРАВКА ---------- */
|
||||
.kb-callout {
|
||||
border: 2px solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.kb-callout-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--caps-wide);
|
||||
}
|
||||
|
||||
.kb-callout-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-6) var(--sp-8) var(--sp-7);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.kb-callout-icon {
|
||||
flex: none;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* ЗАПРЕЩЕНО: красная шапка, белый круг с минусом */
|
||||
.kb-danger {
|
||||
border-color: var(--redS);
|
||||
background: var(--redbg);
|
||||
}
|
||||
.kb-danger .kb-callout-head {
|
||||
min-height: var(--tap);
|
||||
padding: 0 var(--sp-8);
|
||||
background: var(--redS);
|
||||
color: var(--on-strong);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.kb-danger .kb-callout-icon {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 50%;
|
||||
background: var(--on-strong);
|
||||
}
|
||||
.kb-danger .kb-callout-icon::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 5.5px;
|
||||
top: 10px;
|
||||
width: 13px;
|
||||
height: 4px;
|
||||
border-radius: 1px;
|
||||
background: var(--redS);
|
||||
}
|
||||
.kb-danger .kb-b {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
/* ВНИМАНИЕ: жёлтая шапка, треугольник */
|
||||
.kb-warning {
|
||||
border-color: var(--ambln);
|
||||
background: var(--ambbg);
|
||||
}
|
||||
.kb-warning .kb-callout-head {
|
||||
min-height: var(--tap);
|
||||
padding: 0 var(--sp-8);
|
||||
background: var(--brand);
|
||||
color: var(--brand-ink);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.kb-warning .kb-callout-icon {
|
||||
width: 0;
|
||||
height: 0;
|
||||
border-left: 12px solid transparent;
|
||||
border-right: 12px solid transparent;
|
||||
border-bottom: 20px solid var(--brand-ink);
|
||||
}
|
||||
.kb-warning .kb-callout-icon::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -2px;
|
||||
top: 6px;
|
||||
width: 4px;
|
||||
height: 8px;
|
||||
background: var(--brand);
|
||||
border-radius: 1px;
|
||||
}
|
||||
|
||||
/* СОВЕТ и СПРАВКА: без цветной шапки, заголовок строкой */
|
||||
.kb-tip,
|
||||
.kb-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
padding: var(--sp-6) var(--sp-8) var(--sp-7);
|
||||
}
|
||||
.kb-tip .kb-callout-head,
|
||||
.kb-info .kb-callout-head {
|
||||
gap: var(--sp-4);
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.kb-tip .kb-callout-body,
|
||||
.kb-info .kb-callout-body {
|
||||
padding: 0;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
|
||||
.kb-tip {
|
||||
border-color: var(--grnS);
|
||||
background: var(--grnbg);
|
||||
}
|
||||
.kb-tip .kb-callout-head {
|
||||
color: var(--grn);
|
||||
}
|
||||
.kb-tip .kb-callout-icon {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: var(--r-tag);
|
||||
background: var(--grnS);
|
||||
}
|
||||
.kb-tip .kb-callout-icon::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
top: 4px;
|
||||
width: 6px;
|
||||
height: 11px;
|
||||
border: solid var(--on-strong);
|
||||
border-width: 0 2.5px 2.5px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
|
||||
.kb-info {
|
||||
border-color: var(--blu);
|
||||
background: var(--blubg);
|
||||
}
|
||||
.kb-info .kb-callout-head {
|
||||
color: var(--blu);
|
||||
}
|
||||
.kb-info .kb-callout-icon {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--blu);
|
||||
}
|
||||
.kb-info .kb-callout-icon::after {
|
||||
content: 'i';
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
/* ---------- Обычный список ---------- */
|
||||
.kb-ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-5);
|
||||
}
|
||||
.kb-ul > li {
|
||||
display: flex;
|
||||
gap: var(--sp-6);
|
||||
}
|
||||
.kb-ul > li::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
margin-top: 10px;
|
||||
background: var(--ink);
|
||||
}
|
||||
.kb-ul > li > span {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ---------- Чек-лист ---------- */
|
||||
.kb-check {
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
overflow: hidden;
|
||||
box-shadow: var(--sh);
|
||||
}
|
||||
|
||||
.kb-check-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
padding: var(--sp-3) var(--sp-3) var(--sp-3) var(--sp-8);
|
||||
}
|
||||
|
||||
.kb-check-title {
|
||||
flex: 1;
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--caps-wide);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.kb-check-count {
|
||||
font-size: var(--fs-18);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.kb-check-reset {
|
||||
min-height: var(--tap);
|
||||
padding: 0 var(--sp-6);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink2);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.kb-check-bar {
|
||||
height: 4px;
|
||||
background: var(--sf2);
|
||||
}
|
||||
.kb-check-fill {
|
||||
width: 0;
|
||||
height: 100%;
|
||||
background: var(--grnS);
|
||||
transition: width 0.2s;
|
||||
}
|
||||
|
||||
.kb-check-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-7);
|
||||
width: 100%;
|
||||
min-height: 60px;
|
||||
padding: 15px var(--sp-8);
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font-size: var(--fs-18);
|
||||
line-height: 1.5;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.kb-box {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--sf);
|
||||
}
|
||||
|
||||
.kb-check-text {
|
||||
padding-top: var(--sp-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.kb-check-row.is-on .kb-box {
|
||||
border-color: var(--grnS);
|
||||
background: var(--grnS);
|
||||
}
|
||||
.kb-check-row.is-on .kb-box::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);
|
||||
}
|
||||
.kb-check-row.is-on .kb-check-text {
|
||||
opacity: 0.5;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
/* ---------- Шаги ---------- */
|
||||
.kb-steps {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-5);
|
||||
}
|
||||
|
||||
.kb-step {
|
||||
display: flex;
|
||||
gap: var(--sp-7);
|
||||
padding: var(--sp-8) var(--sp-8) var(--sp-8) var(--sp-7);
|
||||
background: var(--sf);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
box-shadow: var(--sh);
|
||||
}
|
||||
|
||||
.kb-step-n {
|
||||
flex: none;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: var(--r-xs);
|
||||
background: var(--hl);
|
||||
color: var(--brand-ink);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: var(--fs-20);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.kb-step-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.kb-step-title {
|
||||
font-size: var(--fs-18);
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
|
||||
/* ---------- Таблица из двух колонок: «что → значение» ---------- */
|
||||
.kb-kv {
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.kb-kv-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-8);
|
||||
padding: var(--sp-5) var(--sp-8);
|
||||
background: var(--sf2);
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
.kb-kv-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-8);
|
||||
min-height: var(--h-row-sm);
|
||||
padding: var(--sp-5) var(--sp-8);
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
|
||||
.kb-kv-k {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.kb-kv-v {
|
||||
font-size: var(--fs-19);
|
||||
font-weight: 700;
|
||||
color: var(--acc);
|
||||
text-align: right;
|
||||
/* Короткие значения не переносим, но длинные не должны распирать экран */
|
||||
max-width: 60%;
|
||||
}
|
||||
|
||||
/* ---------- Таблица из трёх и более колонок: карточки ---------- */
|
||||
.kb-cards {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
.kb-card {
|
||||
padding: var(--sp-7) var(--sp-8);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
.kb-card-title {
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
|
||||
.kb-card-row {
|
||||
display: flex;
|
||||
gap: var(--sp-6);
|
||||
align-items: baseline;
|
||||
}
|
||||
|
||||
.kb-card-label {
|
||||
flex: none;
|
||||
width: 84px;
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.kb-card-val {
|
||||
min-width: 0;
|
||||
}
|
||||
.kb-card-val .kb-b {
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
|
||||
/* ---------- Фото ---------- */
|
||||
.kb-figs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-7);
|
||||
}
|
||||
|
||||
.kb-figs-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--sp-6);
|
||||
}
|
||||
|
||||
.kb-fig {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.kb-fig--first {
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
.kb-fig-btn {
|
||||
position: relative;
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
overflow: hidden;
|
||||
background: var(--sf2);
|
||||
cursor: zoom-in;
|
||||
}
|
||||
.kb-fig--first .kb-fig-btn {
|
||||
border-radius: var(--r-btn);
|
||||
}
|
||||
|
||||
.kb-fig-img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
aspect-ratio: 1 / 1;
|
||||
object-fit: cover;
|
||||
}
|
||||
.kb-fig--first .kb-fig-img {
|
||||
aspect-ratio: auto;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.kb-fig-zoom {
|
||||
position: absolute;
|
||||
right: var(--sp-5);
|
||||
bottom: var(--sp-5);
|
||||
min-height: 36px;
|
||||
padding: 0 var(--sp-7);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--zoom-pill);
|
||||
color: var(--on-strong);
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.kb-fig-cap {
|
||||
font-size: var(--fs-14);
|
||||
line-height: 1.35;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.kb-fig--first .kb-fig-cap {
|
||||
font-size: var(--fs-15);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* Заглушка, если картинка не загрузилась (нет сети и нет в кеше) */
|
||||
.kb-fig-miss {
|
||||
aspect-ratio: 1 / 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: var(--sp-4);
|
||||
background: repeating-linear-gradient(135deg, var(--sf2) 0 10px, var(--sf) 10px 20px);
|
||||
font-size: var(--fs-12);
|
||||
color: var(--ink2);
|
||||
text-align: center;
|
||||
}
|
||||
.kb-fig--first .kb-fig-miss {
|
||||
aspect-ratio: 4 / 3;
|
||||
font-size: var(--fs-13);
|
||||
}
|
||||
@@ -0,0 +1,592 @@
|
||||
/*
|
||||
* Печатная версия (макеты P1–P3). Всегда светлая и читается в ч/б:
|
||||
* блоки различаются рамкой и подписью, цвет только дублирует их.
|
||||
*/
|
||||
|
||||
.pr-screen {
|
||||
min-height: 100dvh;
|
||||
background: var(--bg);
|
||||
padding: var(--sp-8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: var(--sp-8);
|
||||
}
|
||||
|
||||
.pr-tools {
|
||||
width: 100%;
|
||||
max-width: 794px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-6);
|
||||
}
|
||||
.pr-tools-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
/* Лист: на экране как страница A4 (794 px = 210 мм при 96 dpi), на телефоне сжимается по ширине */
|
||||
.pr-sheet {
|
||||
--ink: var(--pr-ink);
|
||||
--ink2: var(--pr-ink3);
|
||||
--acc: var(--pr-ink);
|
||||
--ws: 700;
|
||||
width: 100%;
|
||||
max-width: 794px;
|
||||
padding: var(--sp-24) var(--sp-28);
|
||||
background: var(--pr-bg);
|
||||
color: var(--pr-ink);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-9);
|
||||
font-size: 16px;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
box-shadow: var(--dialog-shadow);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.pr-sheet--A5 {
|
||||
max-width: 559px;
|
||||
padding: var(--sp-16);
|
||||
}
|
||||
.pr-sheet--cheat {
|
||||
padding: 44px 48px;
|
||||
gap: var(--sp-7);
|
||||
font-size: 15px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.pr-runhead {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-8);
|
||||
padding-bottom: var(--sp-5);
|
||||
border-bottom: 1.5px solid var(--pr-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
.pr-title {
|
||||
font-size: 32px;
|
||||
line-height: 1.15;
|
||||
font-weight: 700;
|
||||
}
|
||||
.pr-summary {
|
||||
margin-top: var(--sp-3);
|
||||
font-size: 17px;
|
||||
color: var(--pr-ink2);
|
||||
}
|
||||
|
||||
/* ---------- Блоки статьи в печатном виде ---------- */
|
||||
.pr-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-7);
|
||||
}
|
||||
.pr-body p {
|
||||
margin: 0;
|
||||
}
|
||||
.pr-body .kb-b,
|
||||
.pr-body strong {
|
||||
font-weight: 700;
|
||||
color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-h2 {
|
||||
margin: var(--sp-3) 0 0;
|
||||
padding-top: var(--sp-5);
|
||||
border-top: 1.5px solid var(--pr-ink);
|
||||
font-size: 21px;
|
||||
font-weight: 700;
|
||||
break-after: avoid;
|
||||
}
|
||||
.pr-body .kb-h3 {
|
||||
margin: 0;
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
color: var(--pr-ink);
|
||||
break-after: avoid;
|
||||
}
|
||||
.pr-body > * {
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-body .kb-ulink {
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
/* Главное: сплошная рамка 2 px */
|
||||
.pr-body .kb-key {
|
||||
border: 2px solid var(--pr-ink);
|
||||
border-radius: var(--r-sm);
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-hazard {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-key-head {
|
||||
padding: var(--sp-3) var(--sp-6);
|
||||
border-bottom: 1.5px solid var(--pr-ink);
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 8px, var(--pr-bg) 8px 16px);
|
||||
print-color-adjust: exact;
|
||||
-webkit-print-color-adjust: exact;
|
||||
}
|
||||
.pr-body .kb-key-title {
|
||||
font-size: 14px;
|
||||
background: var(--pr-bg);
|
||||
padding: 0 var(--sp-3);
|
||||
}
|
||||
.pr-body .kb-key-count {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-key-grid {
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.pr-body .kb-key-item {
|
||||
padding: var(--sp-5) var(--sp-6);
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--pr-ln);
|
||||
border-right: 1px solid var(--pr-ln);
|
||||
border-radius: 0;
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-key-label {
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
color: var(--pr-ink3);
|
||||
}
|
||||
.pr-body .kb-key-val .kb-key-v {
|
||||
font-size: 22px;
|
||||
color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-key-val .kb-key-t {
|
||||
font-size: 15px;
|
||||
color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-key-item--wide .kb-key-val {
|
||||
font-size: 16px;
|
||||
}
|
||||
.pr-body .kb-key-item--wide .kb-key-v {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
/* Плашки */
|
||||
.pr-body .kb-callout {
|
||||
border-radius: var(--r-sm);
|
||||
background: none;
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
}
|
||||
.pr-body .kb-callout-icon {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-callout-head {
|
||||
min-height: 0;
|
||||
padding: var(--sp-3) var(--sp-6);
|
||||
font-size: 14px;
|
||||
letter-spacing: var(--caps-xwide);
|
||||
color: var(--pr-ink);
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-callout-body {
|
||||
padding: var(--sp-5) var(--sp-6);
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
/* ЗАПРЕЩЕНО: рамка 3 px и красная шапка (в ч/б останется тёмной) */
|
||||
.pr-body .kb-danger {
|
||||
border: 3px solid var(--pr-red);
|
||||
}
|
||||
.pr-body .kb-danger .kb-callout-head {
|
||||
background: var(--pr-red);
|
||||
color: var(--pr-bg);
|
||||
print-color-adjust: exact;
|
||||
-webkit-print-color-adjust: exact;
|
||||
}
|
||||
.pr-body .kb-danger .kb-callout-head::before {
|
||||
content: '✕';
|
||||
}
|
||||
/* ВНИМАНИЕ: пунктирная рамка */
|
||||
.pr-body .kb-warning {
|
||||
border: 2px dashed var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-warning .kb-callout-head {
|
||||
border-bottom: 1.5px dashed var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-warning .kb-callout-head::before {
|
||||
content: '▲';
|
||||
}
|
||||
.pr-body .kb-tip,
|
||||
.pr-body .kb-info {
|
||||
border: 1px solid var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-tip .kb-callout-head,
|
||||
.pr-body .kb-info .kb-callout-head {
|
||||
padding-bottom: 0;
|
||||
}
|
||||
|
||||
/* Чек-лист: пустые квадраты под ручку */
|
||||
.pr-body .kb-check {
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-4);
|
||||
overflow: visible;
|
||||
break-inside: auto;
|
||||
}
|
||||
.pr-body .kb-check-head,
|
||||
.pr-body .kb-check-bar {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-check-row {
|
||||
min-height: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
gap: var(--sp-6);
|
||||
font-size: inherit;
|
||||
line-height: inherit;
|
||||
color: var(--pr-ink);
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-body .kb-box,
|
||||
.pr-square {
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin-top: 3px;
|
||||
border: 2px solid var(--pr-ink);
|
||||
border-radius: 0;
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-check-row.is-on .kb-box {
|
||||
background: none;
|
||||
border-color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-check-row.is-on .kb-box::after {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-check-row.is-on .kb-check-text {
|
||||
opacity: 1;
|
||||
text-decoration: none;
|
||||
}
|
||||
.pr-body .kb-check-text {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Шаги: квадрат для отметки + номер в рамке */
|
||||
.pr-body .kb-steps {
|
||||
gap: var(--sp-5);
|
||||
break-inside: auto;
|
||||
}
|
||||
.pr-body .kb-step {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
box-shadow: none;
|
||||
gap: var(--sp-5);
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-body .kb-step::before {
|
||||
content: '';
|
||||
flex: none;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
margin-top: 6px;
|
||||
border: 2px solid var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-step-n {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 2px solid var(--pr-ink);
|
||||
background: none;
|
||||
color: var(--pr-ink);
|
||||
font-size: 16px;
|
||||
}
|
||||
.pr-body .kb-step-title {
|
||||
font-size: inherit;
|
||||
}
|
||||
|
||||
/* Таблицы */
|
||||
.pr-body .kb-kv,
|
||||
.pr-body .kb-card {
|
||||
border: 1px solid var(--pr-ink);
|
||||
border-radius: var(--r-xs);
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-kv-head {
|
||||
background: none;
|
||||
color: var(--pr-ink);
|
||||
border-bottom: 1.5px solid var(--pr-ink);
|
||||
padding: var(--sp-3) var(--sp-6);
|
||||
}
|
||||
.pr-body .kb-kv-row {
|
||||
min-height: 0;
|
||||
padding: var(--sp-3) var(--sp-6);
|
||||
border-top: 1px solid var(--pr-ln2);
|
||||
}
|
||||
.pr-body .kb-kv-v {
|
||||
font-size: 16px;
|
||||
color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-cards {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--sp-4);
|
||||
break-inside: auto;
|
||||
}
|
||||
.pr-body .kb-card {
|
||||
padding: var(--sp-4) var(--sp-5);
|
||||
gap: var(--sp-1);
|
||||
font-size: 14px;
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-body .kb-card-label {
|
||||
font-size: 12px;
|
||||
color: var(--pr-ink3);
|
||||
}
|
||||
.pr-body .kb-card-val .kb-b {
|
||||
font-size: inherit;
|
||||
}
|
||||
.pr-body .kb-ul > li::before {
|
||||
background: var(--pr-ink);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
/* Фото: по 2 в ряд, высота 220 px */
|
||||
.pr-body .kb-figs {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--sp-7);
|
||||
break-inside: auto;
|
||||
}
|
||||
.pr-body .kb-figs-grid {
|
||||
display: contents;
|
||||
}
|
||||
.pr-body .kb-fig {
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-body .kb-fig-btn {
|
||||
border: 1px solid var(--pr-ink);
|
||||
border-radius: 0;
|
||||
background: none;
|
||||
}
|
||||
.pr-body .kb-fig-img,
|
||||
.pr-body .kb-fig--first .kb-fig-img {
|
||||
width: 100%;
|
||||
height: 220px;
|
||||
aspect-ratio: auto;
|
||||
object-fit: cover;
|
||||
}
|
||||
.pr-body .kb-fig-zoom {
|
||||
display: none;
|
||||
}
|
||||
.pr-body .kb-fig-cap,
|
||||
.pr-body .kb-fig--first .kb-fig-cap {
|
||||
font-size: 14px;
|
||||
color: var(--pr-ink);
|
||||
}
|
||||
.pr-body .kb-fig-miss,
|
||||
.pr-body .kb-fig--first .kb-fig-miss {
|
||||
height: 220px;
|
||||
aspect-ratio: auto;
|
||||
background: repeating-linear-gradient(135deg, var(--pr-fill) 0 10px, var(--pr-bg) 10px 20px);
|
||||
color: var(--pr-ink3);
|
||||
}
|
||||
|
||||
/* Что включить */
|
||||
.pr-no-photos .kb-figs {
|
||||
display: none;
|
||||
}
|
||||
.pr-no-checks .kb-check {
|
||||
display: none;
|
||||
}
|
||||
.pr-key-only > *:not(.kb-key):not(.kb-danger) {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Подвал с QR */
|
||||
.pr-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-8);
|
||||
padding-top: var(--sp-6);
|
||||
border-top: 1px solid var(--pr-ink);
|
||||
font-size: 13px;
|
||||
break-inside: avoid;
|
||||
}
|
||||
.pr-foot-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.pr-qr {
|
||||
flex: none;
|
||||
display: block;
|
||||
background: var(--pr-bg);
|
||||
}
|
||||
.pr-qr svg {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
/* ---------- Шпаргалка на один лист ---------- */
|
||||
.pr-cheat {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-7);
|
||||
}
|
||||
.pr-cheat-head {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-end;
|
||||
gap: var(--sp-6);
|
||||
padding-bottom: var(--sp-4);
|
||||
border-bottom: 2px solid var(--pr-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
.pr-cheat-title {
|
||||
font-size: 30px;
|
||||
font-weight: 700;
|
||||
line-height: 1;
|
||||
}
|
||||
.pr-cheat-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1.1fr 1fr;
|
||||
gap: var(--sp-10);
|
||||
}
|
||||
.pr-cheat-right {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-6);
|
||||
}
|
||||
.pr-caps {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--caps-wide);
|
||||
padding-bottom: var(--sp-2);
|
||||
border-bottom: 1.5px solid var(--pr-ink);
|
||||
}
|
||||
.pr-fact {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
gap: var(--sp-5);
|
||||
align-items: baseline;
|
||||
padding: 5px 0;
|
||||
border-bottom: 1px solid var(--pr-ln2);
|
||||
}
|
||||
.pr-fact strong {
|
||||
font-size: 16px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.pr-colors {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--sp-4);
|
||||
margin-top: var(--sp-6);
|
||||
}
|
||||
.pr-color {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
.pr-swatch {
|
||||
flex: none;
|
||||
width: 28px;
|
||||
height: 20px;
|
||||
border: 1px solid var(--pr-ink);
|
||||
print-color-adjust: exact;
|
||||
-webkit-print-color-adjust: exact;
|
||||
}
|
||||
.pr-box {
|
||||
border: 2px solid var(--pr-ink);
|
||||
}
|
||||
.pr-box--red {
|
||||
border: 3px solid var(--pr-red);
|
||||
}
|
||||
.pr-box-head {
|
||||
padding: 5px var(--sp-5);
|
||||
border-bottom: 1.5px solid var(--pr-ink);
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: var(--caps-xwide);
|
||||
}
|
||||
.pr-box--red .pr-box-head {
|
||||
border: 0;
|
||||
background: var(--pr-red);
|
||||
color: var(--pr-bg);
|
||||
print-color-adjust: exact;
|
||||
-webkit-print-color-adjust: exact;
|
||||
}
|
||||
.pr-ban {
|
||||
display: grid;
|
||||
grid-template-columns: 24px 1fr;
|
||||
gap: var(--sp-3);
|
||||
padding: 5px var(--sp-5);
|
||||
border-top: 1px solid var(--pr-ln2);
|
||||
}
|
||||
.pr-always {
|
||||
display: flex;
|
||||
gap: var(--sp-4);
|
||||
padding: 5px var(--sp-5);
|
||||
}
|
||||
.pr-always .pr-square {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.pr-cheat-foot {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: var(--sp-6);
|
||||
padding-top: var(--sp-4);
|
||||
border-top: 1px solid var(--pr-ink);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.pr-sheet,
|
||||
.pr-sheet--cheat {
|
||||
padding: var(--sp-10) var(--sp-8);
|
||||
}
|
||||
.pr-cheat-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.pr-tools-info {
|
||||
display: none;
|
||||
}
|
||||
.pr-tools {
|
||||
justify-content: space-between;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Собственно печать ---------- */
|
||||
@media print {
|
||||
html,
|
||||
body {
|
||||
background: var(--pr-bg) !important;
|
||||
}
|
||||
.pr-screen {
|
||||
display: block;
|
||||
padding: 0;
|
||||
background: none;
|
||||
min-height: 0;
|
||||
}
|
||||
.pr-tools,
|
||||
.pr-runhead {
|
||||
display: none;
|
||||
}
|
||||
.pr-sheet,
|
||||
.pr-sheet--A5,
|
||||
.pr-sheet--cheat {
|
||||
max-width: none;
|
||||
padding: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
.pr-cheat-grid {
|
||||
grid-template-columns: 1.1fr 1fr;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
/*
|
||||
* Дизайн-токены. ВСЕ цвета и размеры сайта заданы здесь, в компонентах только var(--…).
|
||||
* Значения взяты из new_design/README.md («Design Tokens»).
|
||||
* Тема переключается атрибутом data-theme на <html>: dark (по умолчанию), light, sun.
|
||||
*/
|
||||
|
||||
:root {
|
||||
/* ---------- Цвета, одинаковые во всех темах ---------- */
|
||||
--brand: #f5c400; /* жёлтый маркер бренда: шпаргалка, «Внимание», полосатая лента */
|
||||
--brand-ink: #141414; /* текст и рамки на жёлтом */
|
||||
--on-strong: #ffffff; /* текст на красной/зелёной плашке */
|
||||
--scrim: rgba(0, 0, 0, 0.5);
|
||||
--scrim-strong: rgba(0, 0, 0, 0.55);
|
||||
--zoom-pill: rgba(0, 0, 0, 0.75);
|
||||
--sheet-shadow: 0 -12px 40px rgba(0, 0, 0, 0.3);
|
||||
--dialog-shadow: 0 30px 80px rgba(0, 0, 0, 0.45);
|
||||
|
||||
/* Плашки разделов */
|
||||
--plq-yellow: #ffc400;
|
||||
--plq-orange: #ff8a00;
|
||||
--plq-blue: #4c8dff;
|
||||
--plq-green: #2db45a;
|
||||
--plq-ink-text: #111111;
|
||||
|
||||
/* Образцы цветов RAL для шпаргалки */
|
||||
--ral-5017: #005387;
|
||||
--ral-7024: #45494e;
|
||||
|
||||
/* Просмотрщик фото: всегда чёрный */
|
||||
--lb-bg: #000000;
|
||||
--lb-ink: #ffffff;
|
||||
--lb-ink2: #bdbdbd;
|
||||
--lb-ink3: #a8a8a8;
|
||||
--lb-sf: #1a1a1a;
|
||||
--lb-sf2: #262626;
|
||||
--lb-ln: #444444;
|
||||
|
||||
/* Печать: всегда светлая и читается в ч/б */
|
||||
--pr-bg: #ffffff;
|
||||
--pr-ink: #000000;
|
||||
--pr-ink2: #333333;
|
||||
--pr-ink3: #444444;
|
||||
--pr-ln: #999999;
|
||||
--pr-ln2: #bbbbbb;
|
||||
--pr-red: #b3001b;
|
||||
--pr-fill: #f2f2f2;
|
||||
|
||||
/* ---------- Типографика ---------- */
|
||||
--font: 'Onest Variable', 'Onest', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--fs-12: 0.75rem;
|
||||
--fs-13: 0.8125rem;
|
||||
--fs-14: 0.875rem;
|
||||
--fs-15: 0.9375rem;
|
||||
--fs-16: 1rem;
|
||||
--fs-17: 1.0625rem;
|
||||
--fs-18: 1.125rem; /* основной текст */
|
||||
--fs-19: 1.1875rem;
|
||||
--fs-20: 1.25rem;
|
||||
--fs-21: 1.3125rem;
|
||||
--fs-22: 1.375rem; /* H2 */
|
||||
--fs-23: 1.4375rem;
|
||||
--fs-24: 1.5rem;
|
||||
--fs-26: 1.625rem;
|
||||
--fs-28: 1.75rem;
|
||||
--fs-30: 1.875rem; /* H1 на телефоне */
|
||||
--fs-32: 2rem;
|
||||
--fs-36: 2.25rem;
|
||||
--fs-40: 2.5rem; /* H1 на компьютере */
|
||||
--lh-body: 1.6;
|
||||
--lh-tight: 1.15;
|
||||
--lh-snug: 1.3;
|
||||
--lh-normal: 1.45;
|
||||
--caps: 0.08em;
|
||||
--caps-wide: 0.1em;
|
||||
--caps-xwide: 0.12em;
|
||||
|
||||
/* ---------- Отступы (шаг 4) ---------- */
|
||||
--sp-1: 2px;
|
||||
--sp-2: 4px;
|
||||
--sp-3: 6px;
|
||||
--sp-4: 8px;
|
||||
--sp-5: 10px;
|
||||
--sp-6: 12px;
|
||||
--sp-7: 14px;
|
||||
--sp-8: 16px; /* поля экрана */
|
||||
--sp-9: 18px;
|
||||
--sp-10: 20px;
|
||||
--sp-11: 22px;
|
||||
--sp-12: 24px;
|
||||
--sp-16: 32px;
|
||||
--sp-20: 40px;
|
||||
--sp-24: 48px;
|
||||
--sp-28: 56px;
|
||||
--sp-32: 64px;
|
||||
|
||||
/* ---------- Скругления ---------- */
|
||||
--r-plaque: 3px;
|
||||
--r-xs: 4px;
|
||||
--r-tag: 6px;
|
||||
--r-sm: 8px;
|
||||
--r-md: 10px;
|
||||
--r-btn: 12px;
|
||||
--r-card: 14px;
|
||||
--r-block: 16px;
|
||||
--r-lg: 18px;
|
||||
--r-sheet: 22px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* ---------- Размеры элементов ---------- */
|
||||
--tap: 48px; /* минимальная зона нажатия */
|
||||
--tap-sm: 44px;
|
||||
--h-field: 60px;
|
||||
--h-btn: 56px;
|
||||
--h-row: 64px;
|
||||
--h-row-sm: 56px;
|
||||
--h-chip: 40px;
|
||||
--h-tabbar: 64px;
|
||||
--w-sidebar: 300px;
|
||||
--w-article: 720px;
|
||||
--w-aside: 300px;
|
||||
--focus-ring: 4px;
|
||||
|
||||
--t-fast: 0.15s ease;
|
||||
--t-sheet: 0.24s ease;
|
||||
}
|
||||
|
||||
/* ---------- Тёмная тема (по умолчанию) ---------- */
|
||||
:root,
|
||||
[data-theme='dark'] {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1011;
|
||||
--sf: #1a1b1d;
|
||||
--sf2: #242528;
|
||||
--ink: #f2f1ec;
|
||||
--ink2: #c4c2bb;
|
||||
--ln: #393b3f;
|
||||
--acc: #ffcf4a;
|
||||
--red: #ff8a8a;
|
||||
--redS: #c81e32;
|
||||
--redbg: #2e1215;
|
||||
--amb: #ffd266;
|
||||
--ambbg: #2b220c;
|
||||
--ambln: #c99700;
|
||||
--grn: #7ed89c;
|
||||
--grnS: #24854a;
|
||||
--grnbg: #112a1a;
|
||||
--blu: #9ec1f7;
|
||||
--blubg: #13203a;
|
||||
--hl: #f5c400;
|
||||
--wb: 400;
|
||||
--ws: 700;
|
||||
--bw: 1px;
|
||||
--sh: none;
|
||||
}
|
||||
|
||||
[data-theme='light'] {
|
||||
color-scheme: light;
|
||||
--bg: #eeede8;
|
||||
--sf: #ffffff;
|
||||
--sf2: #f5f4f0;
|
||||
--ink: #141414;
|
||||
--ink2: #45443f;
|
||||
--ln: #d3d1c9;
|
||||
--acc: #8a4b00;
|
||||
--red: #a8001a;
|
||||
--redS: #b3001b;
|
||||
--redbg: #fbeaec;
|
||||
--amb: #6b4500;
|
||||
--ambbg: #fff4d6;
|
||||
--ambln: #e0a800;
|
||||
--grn: #14602f;
|
||||
--grnS: #1b7a3d;
|
||||
--grnbg: #e6f2e9;
|
||||
--blu: #174a8f;
|
||||
--blubg: #e8eef7;
|
||||
--hl: #f5c400;
|
||||
--wb: 400;
|
||||
--ws: 700;
|
||||
--bw: 1px;
|
||||
--sh: 0 1px 2px rgba(20, 20, 20, 0.06), 0 4px 12px -6px rgba(20, 20, 20, 0.12);
|
||||
}
|
||||
|
||||
/* «Солнце»: максимальный контраст для яркого света, жирнее текст и линии */
|
||||
[data-theme='sun'] {
|
||||
color-scheme: light;
|
||||
--bg: #ffffff;
|
||||
--sf: #ffffff;
|
||||
--sf2: #ffffff;
|
||||
--ink: #000000;
|
||||
--ink2: #111111;
|
||||
--ln: #000000;
|
||||
--acc: #6b3a00;
|
||||
--red: #8c0000;
|
||||
--redS: #a00000;
|
||||
--redbg: #ffffff;
|
||||
--amb: #3d2600;
|
||||
--ambbg: #ffffff;
|
||||
--ambln: #000000;
|
||||
--grn: #004d1e;
|
||||
--grnS: #006b2a;
|
||||
--grnbg: #ffffff;
|
||||
--blu: #00337a;
|
||||
--blubg: #ffffff;
|
||||
--hl: #ffd000;
|
||||
--wb: 500;
|
||||
--ws: 800;
|
||||
--bw: 2px;
|
||||
--sh: 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
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"globals": "^17.13.0",
|
||||
"playwright-core": "^1.63.0",
|
||||
"prettier": "^3.9.9",
|
||||
"typescript": "^5.9.0",
|
||||
"typescript-eslint": "^8.71.0"
|
||||
|
||||
@@ -13,13 +13,12 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"hast-util-to-string": "^3.0.1",
|
||||
"@kb/shared": "workspace:^",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"rehype-stringify": "^10.0.1",
|
||||
"remark-directive": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.2",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.1.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Правило адресов картинок. Одно и то же на сервере и на клиенте.
|
||||
//
|
||||
// В Markdown автор пишет путь как есть: 
|
||||
// При загрузке сервер делает из картинки два WebP-файла:
|
||||
// /uploads/assets/shkon/fig-1.webp (до 1600 px, для просмотра и зума)
|
||||
// /uploads/assets/shkon/fig-1.480.webp (превью 480 px, для сетки и списка)
|
||||
|
||||
export interface AssetUrls {
|
||||
full: string;
|
||||
thumb: string;
|
||||
/** Имя файла для подписи-заглушки, если картинка не загрузилась. */
|
||||
file: string;
|
||||
/** Ключ картинки в папке uploads без расширения: assets/shkon/fig-1 */
|
||||
key: string | null;
|
||||
}
|
||||
|
||||
export function assetKey(src: string): string | null {
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith('//')) return null; // внешний адрес
|
||||
const clean = src
|
||||
.split(/[?#]/)[0]!
|
||||
.replace(/^\.?\/+/, '')
|
||||
.replace(/^uploads\//, '');
|
||||
return clean.replace(/(\.480)?\.[a-z0-9]+$/i, '');
|
||||
}
|
||||
|
||||
export function assetUrls(src: string): AssetUrls {
|
||||
const file = src.split(/[?#]/)[0]!.split('/').pop() ?? src;
|
||||
const key = assetKey(src);
|
||||
if (key === null) return { full: src, thumb: src, file, key };
|
||||
return { full: `/uploads/${key}.webp`, thumb: `/uploads/${key}.480.webp`, file, key };
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// Разбор статьи-шпаргалки на структурные части для экрана «Шпаргалка»:
|
||||
// запреты, цифры, цвета, «всегда». Разделы узнаём по словам в заголовках H2,
|
||||
// эмодзи в заголовках не обязательны.
|
||||
//
|
||||
// Ничего не выдумываем: если раздела в статье нет, список будет пустым,
|
||||
// а если структура совсем другая, экран покажет статью обычным рендером.
|
||||
|
||||
import type { CheatColor, CheatLine, CheatSheet, Seg } from '@kb/shared';
|
||||
import { type MdNode, parseMarkdown, plainText } from './parse.js';
|
||||
|
||||
export type { CheatSheet, CheatLine, CheatColor, Seg };
|
||||
|
||||
function segsOf(nodes: MdNode[]): { segs: Seg[]; links: string[] } {
|
||||
const segs: Seg[] = [];
|
||||
const links: string[] = [];
|
||||
for (const n of nodes) {
|
||||
if (n.type === 'wikiLink') {
|
||||
if (n.slug) links.push(n.slug);
|
||||
} else if (n.type === 'strong') {
|
||||
segs.push({ t: plainText(n), bold: true });
|
||||
} else {
|
||||
segs.push({ t: plainText(n) });
|
||||
}
|
||||
}
|
||||
// Убираем хвост из стрелок и разделителей перед ссылками: «… шинки → » и « · »
|
||||
for (let i = segs.length - 1; i >= 0; i--) {
|
||||
const s = segs[i]!;
|
||||
if (s.bold) break;
|
||||
s.t = s.t.replace(/[\s→·]+$/u, '');
|
||||
if (s.t) break;
|
||||
segs.pop();
|
||||
}
|
||||
if (segs[0] && !segs[0].bold) segs[0].t = segs[0].t.replace(/^[\s·]+/u, '');
|
||||
return { segs: segs.filter((s) => s.t), links };
|
||||
}
|
||||
|
||||
const itemNodes = (li: MdNode): MdNode[] => (li.children ?? []).flatMap((p) => p.children ?? []);
|
||||
|
||||
export function parseCheatSheet(md: string): CheatSheet {
|
||||
const tree = parseMarkdown(md);
|
||||
const sheet: CheatSheet = { bans: [], facts: [], colors: [], always: [], ok: false };
|
||||
let part: 'bans' | 'facts' | 'colors' | 'always' | null = null;
|
||||
|
||||
for (const node of tree.children ?? []) {
|
||||
if (node.type === 'heading') {
|
||||
const t = plainText(node).toLowerCase();
|
||||
part = /запрещ|запрет/.test(t)
|
||||
? 'bans'
|
||||
: /цифр/.test(t)
|
||||
? 'facts'
|
||||
: /цвет/.test(t)
|
||||
? 'colors'
|
||||
: /всегда/.test(t)
|
||||
? 'always'
|
||||
: null;
|
||||
continue;
|
||||
}
|
||||
if (!part) continue;
|
||||
|
||||
if (node.type === 'list') {
|
||||
for (const li of node.children ?? []) {
|
||||
const line = segsOf(itemNodes(li));
|
||||
if (part === 'colors') {
|
||||
// «Уголок фотоэлемента: **RAL 5017**»
|
||||
const code = line.segs.find((s) => s.bold)?.t ?? '';
|
||||
const label = line.segs
|
||||
.filter((s) => !s.bold)
|
||||
.map((s) => s.t)
|
||||
.join(' ')
|
||||
.replace(/[:\s]+$/u, '')
|
||||
.trim();
|
||||
if (code) sheet.colors.push({ code, label });
|
||||
} else if (part === 'facts') {
|
||||
sheet.facts.push(line);
|
||||
} else {
|
||||
sheet[part].push(line);
|
||||
}
|
||||
}
|
||||
} else if (node.type === 'table' && part === 'facts') {
|
||||
// Таблица «Что | Значение | Где»
|
||||
for (const row of (node.children ?? []).slice(1)) {
|
||||
const cells = row.children ?? [];
|
||||
const what = segsOf(cells[0]?.children ?? []);
|
||||
const where = segsOf(cells.slice(2).flatMap((c) => c.children ?? []));
|
||||
sheet.facts.push({
|
||||
segs: what.segs,
|
||||
value: plainText(cells[1] ?? { type: 'text', value: '' }).trim(),
|
||||
links: [...what.links, ...where.links],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sheet.ok = sheet.bans.length + sheet.facts.length + sheet.always.length > 0;
|
||||
return sheet;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Разбор шапки статьи (front matter).
|
||||
//
|
||||
// Почему не библиотека YAML: в наших статьях встречаются строки вида
|
||||
// summary: Карта стойки: верх — оптика и коммутатор
|
||||
// equipment: [уголок 130х130х100х1,8, FTP Cat5e]
|
||||
// Строгий YAML на первой падает (двоеточие в значении), а вторую режет по запятой
|
||||
// внутри «1,8». Поэтому разбираем сами по простым правилам:
|
||||
// - ключ отделяется ПЕРВЫМ двоеточием;
|
||||
// - список [a, b] делится по «запятая + пробел», запятая без пробела остаётся в значении.
|
||||
|
||||
export interface FrontMatter {
|
||||
title?: string;
|
||||
slug?: string;
|
||||
section?: string;
|
||||
order?: number;
|
||||
tags: string[];
|
||||
equipment: string[];
|
||||
/** Пути к исходникам: originals/file.pdf */
|
||||
source: string[];
|
||||
doc_code?: string;
|
||||
summary?: string;
|
||||
pinned: boolean;
|
||||
/** Остальные ключи как есть. */
|
||||
extra: Record<string, string>;
|
||||
}
|
||||
|
||||
function unquote(s: string): string {
|
||||
const t = s.trim();
|
||||
if (t.length >= 2 && ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))) {
|
||||
return t.slice(1, -1);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
function parseList(raw: string): string[] {
|
||||
const t = raw.trim();
|
||||
if (!t) return [];
|
||||
if (t.startsWith('[') && t.endsWith(']')) {
|
||||
return t
|
||||
.slice(1, -1)
|
||||
.split(/,\s+/)
|
||||
.map(unquote)
|
||||
.filter(Boolean);
|
||||
}
|
||||
return [unquote(t)];
|
||||
}
|
||||
|
||||
export function parseFrontMatter(src: string): { meta: FrontMatter; body: string } {
|
||||
const meta: FrontMatter = { tags: [], equipment: [], source: [], pinned: false, extra: {} };
|
||||
// Убираем BOM и приводим переводы строк к \n
|
||||
const text = (src.charCodeAt(0) === 0xfeff ? src.slice(1) : src).replace(/\r\n?/g, '\n');
|
||||
const m = text.match(/^---\n([\s\S]*?)\n---\n?/);
|
||||
if (!m) return { meta, body: text };
|
||||
|
||||
const lines = (m[1] ?? '').split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i] ?? '';
|
||||
const c = line.indexOf(':');
|
||||
if (c < 1 || /^\s/.test(line) || line.startsWith('#')) continue;
|
||||
const key = line.slice(0, c).trim();
|
||||
let value = line.slice(c + 1).trim();
|
||||
|
||||
// Многострочный список:
|
||||
// tags:
|
||||
// - один
|
||||
// - два
|
||||
if (!value) {
|
||||
const items: string[] = [];
|
||||
while (i + 1 < lines.length && /^\s*-\s+/.test(lines[i + 1] ?? '')) {
|
||||
items.push(unquote((lines[++i] ?? '').replace(/^\s*-\s+/, '')));
|
||||
}
|
||||
if (items.length) value = `[${items.join(', ')}]`;
|
||||
}
|
||||
|
||||
switch (key) {
|
||||
case 'title':
|
||||
case 'slug':
|
||||
case 'section':
|
||||
case 'summary':
|
||||
case 'doc_code':
|
||||
meta[key] = unquote(value);
|
||||
break;
|
||||
case 'order':
|
||||
meta.order = Number.parseInt(value, 10) || 0;
|
||||
break;
|
||||
case 'pinned':
|
||||
meta.pinned = /^(true|yes|да|1)$/i.test(value);
|
||||
break;
|
||||
case 'tags':
|
||||
case 'equipment':
|
||||
case 'source':
|
||||
meta[key] = parseList(value);
|
||||
break;
|
||||
default:
|
||||
meta.extra[key] = unquote(value);
|
||||
}
|
||||
}
|
||||
return { meta, body: text.slice(m[0].length) };
|
||||
}
|
||||
@@ -0,0 +1,485 @@
|
||||
// Markdown-дерево (mdast) → HTML-дерево (hast) с нашими блоками.
|
||||
//
|
||||
// Разметка повторяет макет new_design/ArticleBodyXL.dc.html, только вместо инлайн-стилей
|
||||
// стоят классы kb-*; сами стили лежат в apps/web/src/styles/article.css.
|
||||
// Интерактив (галочки чек-листа, открытие фото) навешивает клиент по data-атрибутам,
|
||||
// поэтому один и тот же HTML годится и для сервера, и для предпросмотра в редакторе.
|
||||
|
||||
import { plural } from '@kb/shared';
|
||||
import { assetUrls } from './assets.js';
|
||||
import { type MdNode, plainText } from './parse.js';
|
||||
|
||||
export interface HNode {
|
||||
type: 'element' | 'text' | 'root';
|
||||
tagName?: string;
|
||||
properties?: Record<string, string | number | boolean | string[] | undefined>;
|
||||
children?: HNode[];
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface TocItem {
|
||||
id: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface FigureInfo {
|
||||
src: string;
|
||||
full: string;
|
||||
thumb: string;
|
||||
caption: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
/** Название статьи по slug. Вернёт undefined: ссылка битая. */
|
||||
resolveLink?: (slug: string) => string | undefined;
|
||||
/** Размеры картинки по ключу (assets/shkon/fig-1): чтобы страница не прыгала при загрузке. */
|
||||
imageSize?: (key: string) => { width: number; height: number } | undefined;
|
||||
}
|
||||
|
||||
export interface RenderContext {
|
||||
opts: RenderOptions;
|
||||
toc: TocItem[];
|
||||
figures: FigureInfo[];
|
||||
links: string[];
|
||||
brokenLinks: string[];
|
||||
checkGroups: number;
|
||||
}
|
||||
|
||||
type Props = HNode['properties'];
|
||||
const h = (tagName: string, properties: Props, ...children: (HNode | string | null | undefined)[]): HNode => ({
|
||||
type: 'element',
|
||||
tagName,
|
||||
properties: properties ?? {},
|
||||
children: children
|
||||
.filter((c): c is HNode | string => c !== null && c !== undefined)
|
||||
.map((c) => (typeof c === 'string' ? { type: 'text', value: c } : c)),
|
||||
});
|
||||
const text = (value: string): HNode => ({ type: 'text', value });
|
||||
|
||||
// «flat»: внутри кнопок и плашек ссылка-чип не нужна (в кнопке не может быть ссылки),
|
||||
// там она рисуется подчёркнутым текстом, как в макете.
|
||||
type InlineMode = 'chip' | 'flat';
|
||||
|
||||
function inline(nodes: MdNode[] | undefined, ctx: RenderContext, mode: InlineMode): HNode[] {
|
||||
const out: HNode[] = [];
|
||||
for (const n of nodes ?? []) {
|
||||
switch (n.type) {
|
||||
case 'text':
|
||||
out.push(text(n.value ?? ''));
|
||||
break;
|
||||
case 'strong':
|
||||
out.push(h('strong', { className: ['kb-b'] }, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'emphasis':
|
||||
out.push(h('em', {}, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'delete':
|
||||
out.push(h('del', {}, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'inlineCode':
|
||||
out.push(h('code', { className: ['kb-code'] }, n.value ?? ''));
|
||||
break;
|
||||
case 'break':
|
||||
out.push(h('br', {}));
|
||||
break;
|
||||
case 'link':
|
||||
out.push(
|
||||
mode === 'flat'
|
||||
? h('span', { className: ['kb-ulink'] }, ...inline(n.children, ctx, mode))
|
||||
: h(
|
||||
'a',
|
||||
{ className: ['kb-a'], href: n.url ?? '', target: '_blank', rel: ['noopener', 'noreferrer'] },
|
||||
...inline(n.children, ctx, mode),
|
||||
),
|
||||
);
|
||||
break;
|
||||
case 'wikiLink': {
|
||||
const slug = n.slug ?? '';
|
||||
const title = ctx.opts.resolveLink?.(slug);
|
||||
ctx.links.push(slug);
|
||||
if (title === undefined && ctx.opts.resolveLink) ctx.brokenLinks.push(slug);
|
||||
const broken = title === undefined && !!ctx.opts.resolveLink;
|
||||
if (mode === 'flat') {
|
||||
out.push(
|
||||
h(
|
||||
'span',
|
||||
{ className: broken ? ['kb-ulink', 'kb-link--broken'] : ['kb-ulink'], dataSlug: slug },
|
||||
title ?? slug,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
out.push(
|
||||
h(
|
||||
'a',
|
||||
{
|
||||
className: broken ? ['kb-link', 'kb-link--broken'] : ['kb-link'],
|
||||
href: `/a/${slug}`,
|
||||
dataSlug: slug,
|
||||
},
|
||||
h('span', { className: ['kb-link-arrow'], ariaHidden: 'true' }, '→'),
|
||||
h('span', { className: ['kb-link-t'] }, title ?? slug),
|
||||
),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'image':
|
||||
// Картинка посреди текста: показываем подпись, сам рисунок выносится в блок фото
|
||||
out.push(text(n.alt ?? ''));
|
||||
break;
|
||||
case 'textDirective':
|
||||
// remark-directive принимает «:слово» за директиву. Возвращаем текст как был.
|
||||
out.push(text(`:${n.name ?? ''}`), ...inline(n.children, ctx, mode));
|
||||
break;
|
||||
case 'html':
|
||||
// Сырой HTML из Markdown не пропускаем вообще
|
||||
break;
|
||||
default:
|
||||
if (n.children) out.push(...inline(n.children, ctx, mode));
|
||||
else if (n.value) out.push(text(n.value));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Абзац состоит только из картинок (и переводов строк между ними)? */
|
||||
function onlyImages(p: MdNode): MdNode[] | null {
|
||||
const imgs: MdNode[] = [];
|
||||
for (const c of p.children ?? []) {
|
||||
if (c.type === 'image') imgs.push(c);
|
||||
else if (c.type === 'break' || (c.type === 'text' && !(c.value ?? '').trim())) continue;
|
||||
else return null;
|
||||
}
|
||||
return imgs.length ? imgs : null;
|
||||
}
|
||||
|
||||
function figure(img: MdNode, first: boolean, ctx: RenderContext): HNode {
|
||||
const src = img.url ?? '';
|
||||
const urls = assetUrls(src);
|
||||
const caption = img.alt ?? '';
|
||||
const idx = ctx.figures.length;
|
||||
ctx.figures.push({ src, full: urls.full, thumb: urls.thumb, caption, file: urls.file });
|
||||
const size = urls.key ? ctx.opts.imageSize?.(urls.key) : undefined;
|
||||
|
||||
const imgProps: Props = {
|
||||
className: ['kb-fig-img'],
|
||||
alt: caption,
|
||||
loading: 'lazy',
|
||||
decoding: 'async',
|
||||
dataFile: urls.file,
|
||||
};
|
||||
if (first) {
|
||||
// Первое фото во всю ширину: телефон берёт превью 480, большой экран 1600
|
||||
imgProps.src = urls.full;
|
||||
if (urls.key) {
|
||||
imgProps.srcSet = `${urls.thumb} 480w, ${urls.full} 1600w`;
|
||||
imgProps.sizes = '(max-width: 760px) 100vw, 720px';
|
||||
}
|
||||
if (size) {
|
||||
imgProps.width = size.width;
|
||||
imgProps.height = size.height;
|
||||
}
|
||||
} else {
|
||||
imgProps.src = urls.thumb;
|
||||
imgProps.width = 480;
|
||||
imgProps.height = 480;
|
||||
}
|
||||
|
||||
return h(
|
||||
'figure',
|
||||
{ className: first ? ['kb-fig', 'kb-fig--first'] : ['kb-fig'] },
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', className: ['kb-fig-btn'], dataFig: idx, ariaLabel: `Увеличить: ${caption}` },
|
||||
h('img', imgProps),
|
||||
first ? h('span', { className: ['kb-fig-zoom'], ariaHidden: 'true' }, 'Увеличить') : null,
|
||||
),
|
||||
h('figcaption', { className: ['kb-fig-cap'] }, caption),
|
||||
);
|
||||
}
|
||||
|
||||
function figures(imgs: MdNode[], ctx: RenderContext): HNode {
|
||||
const [first, ...rest] = imgs;
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-figs'] },
|
||||
first ? figure(first, true, ctx) : null,
|
||||
rest.length ? h('div', { className: ['kb-figs-grid'] }, ...rest.map((i) => figure(i, false, ctx))) : null,
|
||||
);
|
||||
}
|
||||
|
||||
/** Содержимое пункта списка как инлайн (у пункта внутри лежит абзац). */
|
||||
function itemInline(item: MdNode): MdNode[] {
|
||||
const out: MdNode[] = [];
|
||||
for (const c of item.children ?? []) {
|
||||
if (c.type === 'paragraph') {
|
||||
if (out.length) out.push({ type: 'text', value: ' ' });
|
||||
out.push(...(c.children ?? []));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Делит абзац по переводам строк: в :::блоке каждая строка исходника становится
|
||||
* отдельной строкой на экране (Markdown сам по себе склеил бы их в один абзац).
|
||||
*/
|
||||
function splitLines(nodes: MdNode[]): MdNode[][] {
|
||||
const lines: MdNode[][] = [[]];
|
||||
for (const n of nodes) {
|
||||
if (n.type === 'break') {
|
||||
lines.push([]);
|
||||
} else if (n.type === 'text' && n.value?.includes('\n')) {
|
||||
n.value.split('\n').forEach((part, i) => {
|
||||
if (i > 0) lines.push([]);
|
||||
if (part) lines.at(-1)!.push({ type: 'text', value: part });
|
||||
});
|
||||
} else {
|
||||
lines.at(-1)!.push(n);
|
||||
}
|
||||
}
|
||||
return lines.filter((l) => l.length);
|
||||
}
|
||||
|
||||
/** Строки внутри :::блока: каждый абзац и каждый пункт списка становится отдельной строкой. */
|
||||
function directiveLines(node: MdNode): MdNode[][] {
|
||||
const lines: MdNode[][] = [];
|
||||
for (const c of node.children ?? []) {
|
||||
if (c.type === 'paragraph') lines.push(...splitLines(c.children ?? []));
|
||||
else if (c.type === 'list') for (const li of c.children ?? []) lines.push(itemInline(li));
|
||||
else lines.push([{ type: 'text', value: plainText(c) }]);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** «Подпись: значение» → подпись отдельно. Двоеточие ищем в начале строки (до 44 знаков). */
|
||||
export function splitLabel(nodes: MdNode[]): { label: string; rest: MdNode[] } {
|
||||
const first = nodes[0];
|
||||
if (first?.type === 'text' && first.value) {
|
||||
const c = first.value.indexOf(':');
|
||||
if (c > -1 && c < 44) {
|
||||
const tail = first.value.slice(c + 1).replace(/^\s+/, '');
|
||||
const rest = tail ? [{ type: 'text', value: tail }, ...nodes.slice(1)] : nodes.slice(1);
|
||||
return { label: first.value.slice(0, c).trim(), rest };
|
||||
}
|
||||
}
|
||||
return { label: '', rest: nodes };
|
||||
}
|
||||
|
||||
function keyfacts(node: MdNode, ctx: RenderContext): HNode {
|
||||
const items = directiveLines(node).map((line) => {
|
||||
const { label, rest } = splitLabel(line);
|
||||
const len = rest.map(plainText).join('').length;
|
||||
// Длинное значение занимает всю ширину, короткое встаёт плиткой в две колонки
|
||||
const wide = len > 24;
|
||||
const segs = rest.map((n) =>
|
||||
n.type === 'strong'
|
||||
? h('span', { className: ['kb-key-v'] }, ...inline(n.children, ctx, 'flat'))
|
||||
: h('span', { className: ['kb-key-t'] }, ...inline([n], ctx, 'flat')),
|
||||
);
|
||||
return h(
|
||||
'div',
|
||||
{ className: wide ? ['kb-key-item', 'kb-key-item--wide'] : ['kb-key-item'] },
|
||||
label ? h('div', { className: ['kb-key-label'] }, label) : null,
|
||||
h('div', { className: ['kb-key-val'] }, ...segs),
|
||||
);
|
||||
});
|
||||
const n = items.length;
|
||||
return h(
|
||||
'section',
|
||||
{ className: ['kb-key'] },
|
||||
h('div', { className: ['kb-hazard'], ariaHidden: 'true' }),
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-key-head'] },
|
||||
h('div', { className: ['kb-key-title'] }, 'Главное'),
|
||||
h('div', { className: ['kb-key-count'] }, `${n} ${plural(n, ['пункт', 'пункта', 'пунктов'])}`),
|
||||
),
|
||||
h('div', { className: ['kb-key-grid'] }, ...items),
|
||||
);
|
||||
}
|
||||
|
||||
const CALLOUTS: Record<string, string> = {
|
||||
danger: 'ЗАПРЕЩЕНО',
|
||||
warning: 'ВНИМАНИЕ',
|
||||
tip: 'СОВЕТ',
|
||||
info: 'СПРАВКА',
|
||||
};
|
||||
|
||||
function callout(kind: string, node: MdNode, ctx: RenderContext): HNode {
|
||||
const paras = directiveLines(node).map((line) => h('p', {}, ...inline(line, ctx, 'flat')));
|
||||
const props: Props = { className: ['kb-callout', `kb-${kind}`] };
|
||||
if (kind === 'danger') props.role = 'alert';
|
||||
return h(
|
||||
'section',
|
||||
props,
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-callout-head'] },
|
||||
h('span', { className: ['kb-callout-icon'], ariaHidden: 'true' }),
|
||||
CALLOUTS[kind] ?? kind,
|
||||
),
|
||||
h('div', { className: ['kb-callout-body'] }, ...paras),
|
||||
);
|
||||
}
|
||||
|
||||
function checklist(list: MdNode, ctx: RenderContext): HNode {
|
||||
const gid = ctx.checkGroups++;
|
||||
const items = list.children ?? [];
|
||||
return h(
|
||||
'section',
|
||||
{ className: ['kb-check'], dataCheck: gid },
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-check-head'] },
|
||||
h('div', { className: ['kb-check-title'] }, 'Чек-лист'),
|
||||
h('div', { className: ['kb-check-count'] }, `0 из ${items.length}`),
|
||||
h('button', { type: 'button', className: ['kb-check-reset'] }, 'Сбросить'),
|
||||
),
|
||||
h('div', { className: ['kb-check-bar'] }, h('div', { className: ['kb-check-fill'] })),
|
||||
...items.map((it, i) =>
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', className: ['kb-check-row'], dataI: i, ariaPressed: 'false' },
|
||||
h('span', { className: ['kb-box'], ariaHidden: 'true' }),
|
||||
h('span', { className: ['kb-check-text'] }, ...inline(itemInline(it), ctx, 'flat')),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function steps(list: MdNode, ctx: RenderContext): HNode {
|
||||
const start = list.start ?? 1;
|
||||
return h(
|
||||
'ol',
|
||||
{ className: ['kb-steps'] },
|
||||
...(list.children ?? []).map((it, i) => {
|
||||
let nodes = itemInline(it);
|
||||
let title: HNode | null = null;
|
||||
// «1. **Заголовок.** текст»: жирное начало становится заголовком шага
|
||||
if (nodes[0]?.type === 'strong') {
|
||||
title = h('div', { className: ['kb-step-title'] }, ...inline(nodes[0].children, ctx, 'flat'));
|
||||
nodes = nodes.slice(1);
|
||||
if (nodes[0]?.type === 'text') nodes[0] = { type: 'text', value: (nodes[0].value ?? '').replace(/^\s+/, '') };
|
||||
}
|
||||
const body = inline(nodes, ctx, 'flat');
|
||||
return h(
|
||||
'li',
|
||||
{ className: ['kb-step'] },
|
||||
h('span', { className: ['kb-step-n'] }, String(start + i)),
|
||||
h('div', { className: ['kb-step-main'] }, title, body.length ? h('div', {}, ...body) : null),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function table(node: MdNode, ctx: RenderContext): HNode {
|
||||
const rows = (node.children ?? []).map((r) => r.children ?? []);
|
||||
const head = rows[0] ?? [];
|
||||
const body = rows.slice(1);
|
||||
const cell = (c: MdNode | undefined, mode: InlineMode = 'chip') => inline(c?.children, ctx, mode);
|
||||
|
||||
// Две колонки: «что → значение», значение крупно справа
|
||||
if (head.length === 2) {
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-kv'], role: 'table' },
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-kv-head'], role: 'row' },
|
||||
h('span', { role: 'columnheader' }, ...cell(head[0], 'flat')),
|
||||
h('span', { role: 'columnheader' }, ...cell(head[1], 'flat')),
|
||||
),
|
||||
...body.map((r) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-kv-row'], role: 'row' },
|
||||
h('span', { className: ['kb-kv-k'], role: 'cell' }, ...cell(r[0], 'flat')),
|
||||
h('span', { className: ['kb-kv-v'], role: 'cell' }, ...cell(r[1], 'flat')),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Три колонки и больше: каждая строка становится карточкой, первая ячейка: заголовок
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-cards'] },
|
||||
...body.map((r) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-card'] },
|
||||
h('div', { className: ['kb-card-title'] }, ...cell(r[0])),
|
||||
...r.slice(1).map((c, j) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-card-row'] },
|
||||
h('span', { className: ['kb-card-label'] }, plainText(head[j + 1] ?? { type: 'text', value: '' })),
|
||||
h('span', { className: ['kb-card-val'] }, ...cell(c)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function block(node: MdNode, ctx: RenderContext): HNode | null {
|
||||
switch (node.type) {
|
||||
case 'heading': {
|
||||
const t = plainText(node).trim();
|
||||
if ((node.depth ?? 2) <= 2) {
|
||||
const id = `h-${ctx.toc.length}`;
|
||||
ctx.toc.push({ id, text: t });
|
||||
return h('h2', { className: ['kb-h2'], id }, ...inline(node.children, ctx, 'flat'));
|
||||
}
|
||||
return h('h3', { className: ['kb-h3'] }, ...inline(node.children, ctx, 'flat'));
|
||||
}
|
||||
case 'paragraph': {
|
||||
const imgs = onlyImages(node);
|
||||
if (imgs) return figures(imgs, ctx);
|
||||
return h('p', { className: ['kb-p'] }, ...inline(node.children, ctx, 'chip'));
|
||||
}
|
||||
case 'containerDirective': {
|
||||
const name = node.name ?? '';
|
||||
if (name === 'keyfacts') return keyfacts(node, ctx);
|
||||
if (name in CALLOUTS) return callout(name, node, ctx);
|
||||
// Неизвестный блок показываем как справку, чтобы текст не пропал
|
||||
return callout('info', node, ctx);
|
||||
}
|
||||
case 'list': {
|
||||
const items = node.children ?? [];
|
||||
if (items.length && items.every((i) => typeof i.checked === 'boolean')) return checklist(node, ctx);
|
||||
if (node.ordered) return steps(node, ctx);
|
||||
return h(
|
||||
'ul',
|
||||
{ className: ['kb-ul'] },
|
||||
...items.map((it) => h('li', {}, h('span', {}, ...inline(itemInline(it), ctx, 'chip')))),
|
||||
);
|
||||
}
|
||||
case 'table':
|
||||
return table(node, ctx);
|
||||
case 'blockquote':
|
||||
return h('blockquote', { className: ['kb-quote'] }, ...blocks(node.children ?? [], ctx));
|
||||
case 'code':
|
||||
return h('pre', { className: ['kb-pre'] }, h('code', {}, node.value ?? ''));
|
||||
case 'thematicBreak':
|
||||
return h('hr', { className: ['kb-hr'] });
|
||||
case 'leafDirective':
|
||||
return h('p', { className: ['kb-p'] }, `::${node.name ?? ''}`, ...inline(node.children, ctx, 'chip'));
|
||||
case 'html':
|
||||
case 'definition':
|
||||
case 'footnoteDefinition':
|
||||
return null;
|
||||
default:
|
||||
return node.children ? h('div', {}, ...blocks(node.children, ctx)) : null;
|
||||
}
|
||||
}
|
||||
|
||||
function blocks(nodes: MdNode[], ctx: RenderContext): HNode[] {
|
||||
return nodes.map((n) => block(n, ctx)).filter((n): n is HNode => n !== null);
|
||||
}
|
||||
|
||||
export function toHast(tree: MdNode, ctx: RenderContext): HNode {
|
||||
return { type: 'root', children: blocks(tree.children ?? [], ctx) };
|
||||
}
|
||||
+137
-2
@@ -1,2 +1,137 @@
|
||||
// Общий Markdown-рендер (сервер + клиент). Наполняется на этапе 2.
|
||||
export const MD_PACKAGE = '@kb/md';
|
||||
// @kb/md: единственное место, где Markdown статьи превращается в HTML.
|
||||
// Используется сервером (bodyHtml при сохранении, текст для поиска) и клиентом
|
||||
// (живой предпросмотр в редакторе), поэтому результат всегда одинаковый.
|
||||
|
||||
import { unified } from 'unified';
|
||||
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
|
||||
import rehypeStringify from 'rehype-stringify';
|
||||
import { type FigureInfo, type HNode, type RenderContext, type RenderOptions, type TocItem, splitLabel, toHast } from './hast.js';
|
||||
import { type MdNode, parseMarkdown, plainText } from './parse.js';
|
||||
|
||||
export { parseFrontMatter, type FrontMatter } from './frontmatter.js';
|
||||
export { assetUrls, assetKey, type AssetUrls } from './assets.js';
|
||||
export { parseCheatSheet, type CheatSheet, type CheatLine } from './cheatsheet.js';
|
||||
export { parseMarkdown, plainText, type MdNode } from './parse.js';
|
||||
export type { RenderOptions, TocItem, FigureInfo } from './hast.js';
|
||||
|
||||
// Белый список тегов и атрибутов. HTML мы строим сами, но на всякий случай прогоняем
|
||||
// через санитайзер: он же отсекает опасные адреса вроде javascript: в ссылках.
|
||||
const schema: typeof defaultSchema = {
|
||||
...defaultSchema,
|
||||
clobber: [], // не добавлять префикс к id заголовков (h-0, h-1): они наши, а не от автора
|
||||
strip: ['script', 'style'],
|
||||
tagNames: [
|
||||
'h2', 'h3', 'p', 'strong', 'em', 'del', 'code', 'br', 'a', 'span', 'div', 'section',
|
||||
'figure', 'figcaption', 'button', 'img', 'ul', 'ol', 'li', 'blockquote', 'pre', 'hr',
|
||||
],
|
||||
attributes: {
|
||||
'*': ['className', 'id', 'role', 'ariaHidden', 'ariaLabel', 'ariaPressed', 'data*'],
|
||||
a: ['href', 'target', 'rel'],
|
||||
img: ['src', 'srcSet', 'sizes', 'alt', 'loading', 'decoding', 'width', 'height'],
|
||||
button: ['type'],
|
||||
},
|
||||
protocols: {
|
||||
href: ['http', 'https', 'mailto', 'tel'],
|
||||
src: ['http', 'https'],
|
||||
},
|
||||
};
|
||||
|
||||
const htmlProcessor = unified().use(rehypeSanitize, schema).use(rehypeStringify);
|
||||
|
||||
export interface FactItem {
|
||||
label: string;
|
||||
/** Значение в Markdown: «только **порты 1 и 2** коммутатора». */
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
html: string;
|
||||
/** Заголовки H2 для оглавления. */
|
||||
toc: TocItem[];
|
||||
/** Все рисунки статьи по порядку (для просмотрщика и офлайн-кеша). */
|
||||
figures: FigureInfo[];
|
||||
/** Все [[slug]] из текста. */
|
||||
links: string[];
|
||||
/** [[slug]], для которых статья не нашлась. */
|
||||
brokenLinks: string[];
|
||||
/** Пункты блоков «Главное». */
|
||||
facts: FactItem[];
|
||||
/** Текст без разметки по частям: для поиска. */
|
||||
text: { keyfacts: string; body: string };
|
||||
}
|
||||
|
||||
/** Собрать Markdown обратно из инлайн-узлов (нужен только жирный). */
|
||||
function inlineMd(nodes: MdNode[]): string {
|
||||
return nodes
|
||||
.map((n) => (n.type === 'strong' ? `**${plainText(n)}**` : plainText(n)))
|
||||
.join('')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function collectFacts(tree: MdNode): FactItem[] {
|
||||
const facts: FactItem[] = [];
|
||||
for (const node of tree.children ?? []) {
|
||||
if (node.type !== 'containerDirective' || node.name !== 'keyfacts') continue;
|
||||
for (const c of node.children ?? []) {
|
||||
const lines =
|
||||
c.type === 'list'
|
||||
? (c.children ?? []).map((li) => (li.children ?? []).flatMap((p) => p.children ?? []))
|
||||
: [c.children ?? []];
|
||||
for (const line of lines) {
|
||||
const { label, rest } = splitLabel(line);
|
||||
const value = inlineMd(rest);
|
||||
if (value) facts.push({ label, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Главная функция пакета: Markdown (без front matter) → HTML и всё, что из него извлекается.
|
||||
*/
|
||||
export function renderMarkdown(md: string, opts: RenderOptions = {}): RenderResult {
|
||||
const tree = parseMarkdown(md);
|
||||
const ctx: RenderContext = { opts, toc: [], figures: [], links: [], brokenLinks: [], checkGroups: 0 };
|
||||
const hast = toHast(tree, ctx);
|
||||
// HNode совместим с типом Root из hast, но описан проще: приводим тип для unified
|
||||
const clean = htmlProcessor.runSync(hast as unknown as Parameters<typeof htmlProcessor.runSync>[0]);
|
||||
const html = htmlProcessor.stringify(clean as Parameters<typeof htmlProcessor.stringify>[0]) as string;
|
||||
|
||||
const keyfacts: string[] = [];
|
||||
const body: string[] = [];
|
||||
for (const node of tree.children ?? []) {
|
||||
const t = plainText(node).replace(/\s+/g, ' ').trim();
|
||||
if (!t) continue;
|
||||
if (node.type === 'containerDirective' && node.name === 'keyfacts') keyfacts.push(blockText(node));
|
||||
else body.push(node.children && node.type !== 'paragraph' && node.type !== 'heading' ? blockText(node) : t);
|
||||
}
|
||||
|
||||
return {
|
||||
html,
|
||||
toc: ctx.toc,
|
||||
figures: ctx.figures,
|
||||
links: [...new Set(ctx.links)],
|
||||
brokenLinks: [...new Set(ctx.brokenLinks)],
|
||||
facts: collectFacts(tree),
|
||||
text: { keyfacts: keyfacts.join('\n'), body: body.join('\n') },
|
||||
};
|
||||
}
|
||||
|
||||
/** Текст блока, где пункты списка и ячейки таблицы разделены переводом строки (а не слиты в одно слово). */
|
||||
function blockText(node: MdNode): string {
|
||||
const parts: string[] = [];
|
||||
const walk = (n: MdNode) => {
|
||||
if (n.type === 'paragraph' || n.type === 'heading' || n.type === 'tableCell') {
|
||||
const t = plainText(n).replace(/\s+/g, ' ').trim();
|
||||
if (t) parts.push(t);
|
||||
return;
|
||||
}
|
||||
if (n.children) n.children.forEach(walk);
|
||||
else if (n.value?.trim()) parts.push(n.value.trim());
|
||||
};
|
||||
walk(node);
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
export type { HNode };
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { assetUrls, parseCheatSheet, parseFrontMatter, renderMarkdown } from './index.js';
|
||||
|
||||
describe('front matter', () => {
|
||||
it('терпит двоеточие в значении и запятую без пробела в списке', () => {
|
||||
const { meta, body } = parseFrontMatter(
|
||||
[
|
||||
'---',
|
||||
'title: Заголовок',
|
||||
'summary: Карта стойки: верх — оптика',
|
||||
'equipment: [Fortisflex MG-12 80033, уголок 130х130х100х1,8, FTP Cat5e]',
|
||||
'source: [originals/a.pdf, originals/b.pdf]',
|
||||
'pinned: true',
|
||||
'order: 3',
|
||||
'---',
|
||||
'',
|
||||
'Текст',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(meta.summary).toBe('Карта стойки: верх — оптика');
|
||||
expect(meta.equipment).toEqual(['Fortisflex MG-12 80033', 'уголок 130х130х100х1,8', 'FTP Cat5e']);
|
||||
expect(meta.source).toHaveLength(2);
|
||||
expect(meta.pinned).toBe(true);
|
||||
expect(meta.order).toBe(3);
|
||||
expect(body.trim()).toBe('Текст');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderMarkdown', () => {
|
||||
it('рисует блок «Главное» и собирает факты', () => {
|
||||
const r = renderMarkdown(':::keyfacts\n- Запас: **20 см** (под светофор)\n- Сальник: **MG-12**\n:::');
|
||||
expect(r.html).toContain('kb-key');
|
||||
expect(r.html).toContain('2 пункта');
|
||||
expect(r.facts).toEqual([
|
||||
{ label: 'Запас', value: '**20 см** (под светофор)' },
|
||||
{ label: 'Сальник', value: '**MG-12**' },
|
||||
]);
|
||||
expect(r.text.keyfacts).toContain('20 см');
|
||||
});
|
||||
|
||||
it('рисует запрет, чек-лист, шаги и таблицы', () => {
|
||||
const r = renderMarkdown(
|
||||
[
|
||||
':::danger',
|
||||
'Нельзя **так**.',
|
||||
':::',
|
||||
'',
|
||||
'- [ ] Раз',
|
||||
'- [x] Два',
|
||||
'',
|
||||
'1. **Шаг.** Сделать',
|
||||
'',
|
||||
'| Куда | Длина |',
|
||||
'|---|---|',
|
||||
'| SIP | **2 м** |',
|
||||
'',
|
||||
'| A | B | C |',
|
||||
'|---|---|---|',
|
||||
'| 1 | 2 | 3 |',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(r.html).toContain('kb-danger');
|
||||
expect(r.html).toContain('ЗАПРЕЩЕНО');
|
||||
expect(r.html).toContain('data-check="0"');
|
||||
expect(r.html).toContain('0 из 2');
|
||||
expect(r.html).toContain('kb-step-title');
|
||||
expect(r.html).toContain('kb-kv');
|
||||
expect(r.html).toContain('kb-cards');
|
||||
});
|
||||
|
||||
it('подставляет названия в [[ссылки]] и отмечает битые', () => {
|
||||
const r = renderMarkdown('См. [[shkon]] и [[net-takoy]]', {
|
||||
resolveLink: (s) => (s === 'shkon' ? 'ШКОН' : undefined),
|
||||
});
|
||||
expect(r.links).toEqual(['shkon', 'net-takoy']);
|
||||
expect(r.brokenLinks).toEqual(['net-takoy']);
|
||||
expect(r.html).toContain('href="/a/shkon"');
|
||||
expect(r.html).toContain('>ШКОН<');
|
||||
expect(r.html).toContain('kb-link--broken');
|
||||
});
|
||||
|
||||
it('собирает фото в группу и оглавление по H2', () => {
|
||||
const r = renderMarkdown('## Фото\n\n\n');
|
||||
expect(r.toc).toEqual([{ id: 'h-0', text: 'Фото' }]);
|
||||
expect(r.figures.map((f) => f.full)).toEqual(['/uploads/assets/x/fig-1.webp', '/uploads/assets/x/fig-2.webp']);
|
||||
expect(r.html).toContain('/uploads/assets/x/fig-2.480.webp');
|
||||
expect(r.html).toContain('data-fig="1"');
|
||||
});
|
||||
|
||||
it('не пропускает HTML и опасные ссылки', () => {
|
||||
const r = renderMarkdown('<script>alert(1)</script>\n\n<img src=x onerror=alert(1)>\n\n[жми](javascript:alert(1))');
|
||||
expect(r.html).not.toContain('<script');
|
||||
expect(r.html).not.toContain('onerror');
|
||||
expect(r.html).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
it('не зачёркивает текст между одиночными тильдами', () => {
|
||||
expect(renderMarkdown('Изолента ~15 см и ~30 см').html).not.toContain('<del');
|
||||
});
|
||||
});
|
||||
|
||||
describe('assetUrls', () => {
|
||||
it('строит адреса WebP и превью', () => {
|
||||
expect(assetUrls('assets/shkon/fig-1.jpg')).toMatchObject({
|
||||
full: '/uploads/assets/shkon/fig-1.webp',
|
||||
thumb: '/uploads/assets/shkon/fig-1.480.webp',
|
||||
file: 'fig-1.jpg',
|
||||
});
|
||||
expect(assetUrls('/uploads/2026/10/abc.webp').thumb).toBe('/uploads/2026/10/abc.480.webp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseCheatSheet', () => {
|
||||
it('разбирает запреты, цифры, цвета и «всегда»', () => {
|
||||
const s = parseCheatSheet(
|
||||
[
|
||||
'## ⛔ Запрещено',
|
||||
'- Подключать **УЗИП до автомата** → только шинки → [[silovoe]]',
|
||||
'## 📏 Цифры',
|
||||
'| Что | Значение | Где |',
|
||||
'|---|---|---|',
|
||||
'| Изолента: ШКОН / ШКОС | **15 см / 30 см** | [[shkon]] · [[shkos]] |',
|
||||
'## 🎨 Цвета',
|
||||
'- Уголок фотоэлемента: **RAL 5017**',
|
||||
'## ✅ Всегда',
|
||||
'- бирки на ВОК **до** сварки',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(s.ok).toBe(true);
|
||||
expect(s.bans[0]?.links).toEqual(['silovoe']);
|
||||
expect(s.bans[0]?.segs.at(-1)?.t).toBe(' → только шинки');
|
||||
expect(s.facts[0]).toMatchObject({ value: '15 см / 30 см', links: ['shkon', 'shkos'] });
|
||||
expect(s.colors).toEqual([{ code: 'RAL 5017', label: 'Уголок фотоэлемента' }]);
|
||||
expect(s.always[0]?.segs).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { unified } from 'unified';
|
||||
import remarkParse from 'remark-parse';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import remarkDirective from 'remark-directive';
|
||||
|
||||
// Упрощённый тип узла Markdown-дерева (mdast). Полные типы из @types/mdast здесь
|
||||
// только мешают: у нас есть свои узлы (wikiLink, containerDirective).
|
||||
export interface MdNode {
|
||||
type: string;
|
||||
value?: string;
|
||||
children?: MdNode[];
|
||||
depth?: number;
|
||||
ordered?: boolean;
|
||||
start?: number | null;
|
||||
checked?: boolean | null;
|
||||
url?: string;
|
||||
alt?: string | null;
|
||||
title?: string | null;
|
||||
name?: string;
|
||||
slug?: string;
|
||||
lang?: string | null;
|
||||
}
|
||||
|
||||
const WIKI_RE = /\[\[([a-z0-9][a-z0-9-]*)\]\]/g;
|
||||
|
||||
/**
|
||||
* Свой remark-плагин: превращает текст `[[slug]]` в узел { type: 'wikiLink', slug }.
|
||||
* Дальше рендер делает из него ссылку-чип с названием статьи.
|
||||
*/
|
||||
function remarkWikiLinks() {
|
||||
return (tree: MdNode) => {
|
||||
const walk = (node: MdNode) => {
|
||||
if (!node.children) return;
|
||||
// Внутри кода ссылки не трогаем
|
||||
if (node.type === 'code' || node.type === 'inlineCode') return;
|
||||
const out: MdNode[] = [];
|
||||
for (const child of node.children) {
|
||||
if (child.type !== 'text' || !child.value || !child.value.includes('[[')) {
|
||||
walk(child);
|
||||
out.push(child);
|
||||
continue;
|
||||
}
|
||||
const text = child.value;
|
||||
let last = 0;
|
||||
for (const m of text.matchAll(WIKI_RE)) {
|
||||
const at = m.index ?? 0;
|
||||
if (at > last) out.push({ type: 'text', value: text.slice(last, at) });
|
||||
out.push({ type: 'wikiLink', slug: m[1] });
|
||||
last = at + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push({ type: 'text', value: text.slice(last) });
|
||||
}
|
||||
node.children = out;
|
||||
};
|
||||
walk(tree);
|
||||
};
|
||||
}
|
||||
|
||||
const processor = unified().use(remarkParse)
|
||||
// singleTilde: false, иначе «~15 см … ~30 см» в одном абзаце станет зачёркнутым текстом
|
||||
.use(remarkGfm, { singleTilde: false })
|
||||
.use(remarkDirective)
|
||||
.use(remarkWikiLinks);
|
||||
|
||||
/** Markdown (без front matter) → дерево mdast. */
|
||||
export function parseMarkdown(md: string): MdNode {
|
||||
const tree = processor.parse(md);
|
||||
return processor.runSync(tree) as unknown as MdNode;
|
||||
}
|
||||
|
||||
/** Весь текст узла подряд, без разметки. */
|
||||
export function plainText(node: MdNode): string {
|
||||
if (node.type === 'wikiLink') return '';
|
||||
if (node.type === 'image') return node.alt ?? '';
|
||||
if (node.type === 'break') return ' ';
|
||||
if (typeof node.value === 'string') return node.value;
|
||||
return (node.children ?? []).map(plainText).join('');
|
||||
}
|
||||
@@ -83,6 +83,10 @@ export interface ArticleDto extends ArticleListItem {
|
||||
/** Адреса картинок статьи (полные и превью): нужны для офлайн-кеша. */
|
||||
images: string[];
|
||||
authorName: string | null;
|
||||
/** Заголовки H2 для оглавления. */
|
||||
toc: TocEntry[];
|
||||
/** Разобранная шпаргалка (только у закреплённой статьи со структурой шпаргалки). */
|
||||
cheat: CheatSheet | null;
|
||||
}
|
||||
|
||||
/** Всё дерево одним запросом: его хватает для главной, меню и офлайна. */
|
||||
@@ -100,8 +104,11 @@ export interface Highlight {
|
||||
export interface SearchFact {
|
||||
value: Highlight[];
|
||||
label: Highlight[];
|
||||
articleSlug: string;
|
||||
articleTitle: string;
|
||||
/** Статьи-источники. */
|
||||
links: { slug: string; title: string }[];
|
||||
sectionId: string;
|
||||
/** Строка из шпаргалки. */
|
||||
cheat: boolean;
|
||||
}
|
||||
|
||||
export interface SearchArticle {
|
||||
@@ -157,3 +164,80 @@ export function plural(n: number, forms: [string, string, string]): string {
|
||||
if (b === 1) return forms[0];
|
||||
return forms[2];
|
||||
}
|
||||
|
||||
// ---------- Нормализация текста для поиска (одинаковая при индексации и при запросе) ----------
|
||||
|
||||
/** Нижний регистр, ё→е, все виды тире → дефис, лишние пробелы убраны. */
|
||||
export function normalizeSearch(s: string): string {
|
||||
return s
|
||||
.toLowerCase()
|
||||
.replace(/ё/g, 'е')
|
||||
// \p{Pd}: все виды тире и дефисов, плюс математический минус
|
||||
.replace(/[\p{Pd}−]/gu, '-')
|
||||
// \p{Zs}: все виды пробелов, включая неразрывный и узкий
|
||||
.replace(/\p{Zs}/gu, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
// Десятичная точка → запятая: «2.5» и «2,5» ищутся одинаково
|
||||
.replace(/(\d)\.(?=\d)/g, '$1,')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* «Сжатый» вид: только буквы и цифры (и запятая внутри числа). Так «MG12» находит «MG-12»,
|
||||
* а «ral7024» находит «RAL 7024».
|
||||
*/
|
||||
export function compactSearch(s: string): string {
|
||||
return (
|
||||
normalizeSearch(s)
|
||||
.replace(/[^\p{L}\p{N},]+/gu, '')
|
||||
// Запятую оставляем только между цифрами: «1,2 м» не должно совпасть с «12 мм»
|
||||
.replace(/(?<!\d),|,(?!\d)/g, '')
|
||||
);
|
||||
}
|
||||
|
||||
/** Короткое название статьи для меню: без «Название раздела — » в начале. */
|
||||
export function shortTitle(title: string, sectionName?: string): string {
|
||||
let t = title;
|
||||
if (sectionName && t.toLowerCase().startsWith(sectionName.toLowerCase())) {
|
||||
const rest = t.slice(sectionName.length).replace(/^\s*[—–:-]\s*/, '');
|
||||
if (rest && rest !== t.slice(sectionName.length)) t = rest;
|
||||
}
|
||||
return t.charAt(0).toUpperCase() + t.slice(1);
|
||||
}
|
||||
|
||||
// ---------- Шпаргалка ----------
|
||||
|
||||
export interface Seg {
|
||||
t: string;
|
||||
bold?: boolean;
|
||||
}
|
||||
|
||||
export interface CheatLine {
|
||||
/** Текст с выделением жирного. */
|
||||
segs: Seg[];
|
||||
/** Значение (для «Цифр»): «20 см». */
|
||||
value?: string;
|
||||
/** Статьи-источники: slug из [[...]]. */
|
||||
links: string[];
|
||||
}
|
||||
|
||||
export interface CheatColor {
|
||||
/** «RAL 5017» */
|
||||
code: string;
|
||||
/** «Уголок фотоэлемента» */
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface CheatSheet {
|
||||
bans: CheatLine[];
|
||||
facts: CheatLine[];
|
||||
colors: CheatColor[];
|
||||
always: CheatLine[];
|
||||
/** true, если нашёлся хотя бы один из разделов. */
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export interface TocEntry {
|
||||
id: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
Generated
+21
-24
@@ -20,6 +20,9 @@ importers:
|
||||
globals:
|
||||
specifier: ^17.13.0
|
||||
version: 17.13.0
|
||||
playwright-core:
|
||||
specifier: ^1.63.0
|
||||
version: 1.63.0
|
||||
prettier:
|
||||
specifier: ^3.9.9
|
||||
version: 3.9.9
|
||||
@@ -117,6 +120,9 @@ importers:
|
||||
'@tanstack/react-query':
|
||||
specifier: ^5.104.1
|
||||
version: 5.104.1(react@19.3.0)
|
||||
qrcode-generator:
|
||||
specifier: ^2.0.4
|
||||
version: 2.0.4
|
||||
react:
|
||||
specifier: ^19.3.0
|
||||
version: 19.3.0
|
||||
@@ -151,9 +157,9 @@ importers:
|
||||
|
||||
packages/md:
|
||||
dependencies:
|
||||
hast-util-to-string:
|
||||
specifier: ^3.0.1
|
||||
version: 3.0.1
|
||||
'@kb/shared':
|
||||
specifier: workspace:^
|
||||
version: link:../shared
|
||||
rehype-sanitize:
|
||||
specifier: ^6.0.0
|
||||
version: 6.0.0
|
||||
@@ -169,9 +175,6 @@ importers:
|
||||
remark-parse:
|
||||
specifier: ^11.0.0
|
||||
version: 11.0.0
|
||||
remark-rehype:
|
||||
specifier: ^11.1.2
|
||||
version: 11.1.2
|
||||
unified:
|
||||
specifier: ^11.0.5
|
||||
version: 11.0.5
|
||||
@@ -2440,9 +2443,6 @@ packages:
|
||||
hast-util-to-html@9.0.5:
|
||||
resolution: {integrity: sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==}
|
||||
|
||||
hast-util-to-string@3.0.1:
|
||||
resolution: {integrity: sha512-XelQVTDWvqcl3axRfI0xSeoVKzyIFPwsAGSLIsKdJKQMXDYJS4WYrBNF/8J7RdhIcFI2BOHgAifggsvsxp/3+A==}
|
||||
|
||||
hast-util-whitespace@3.0.0:
|
||||
resolution: {integrity: sha512-88JUN06ipLwsnv+dVn+OIYOvAuvBMy/Qoi6O7mQHxdPXpjy+Cd6xRkWwux7DKO+4sYILtLBRIKgsdpS2gQc7qw==}
|
||||
|
||||
@@ -3127,6 +3127,11 @@ packages:
|
||||
pkg-types@2.3.3:
|
||||
resolution: {integrity: sha512-j/lCFdcppV0JxWpCEITdbDltBxPP6cHT+yNJ6Go2OgoSA9518X847X9z0p6LtA4Nc16+eQzCZjRrWanTGvHJ5w==}
|
||||
|
||||
playwright-core@1.63.0:
|
||||
resolution: {integrity: sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==}
|
||||
engines: {node: '>=20'}
|
||||
hasBin: true
|
||||
|
||||
possible-typed-array-names@1.1.0:
|
||||
resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -3198,6 +3203,9 @@ packages:
|
||||
resolution: {integrity: sha512-+Owyggi9IxT1ePKGafcI87ubSmxol6smwJ+RAHDQlx9+9cPwFWDiKFFCPuWhr9ignlGpZ9vDQLw67N4dcTVFEA==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
qrcode-generator@2.0.4:
|
||||
resolution: {integrity: sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==}
|
||||
|
||||
qs@6.16.0:
|
||||
resolution: {integrity: sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==}
|
||||
engines: {node: '>=0.6'}
|
||||
@@ -3284,9 +3292,6 @@ packages:
|
||||
remark-parse@11.0.0:
|
||||
resolution: {integrity: sha512-FCxlKLNGknS5ba/1lmpYijMUzX2esxW5xQqjWxw2eHFfS2MSdaHVINFmhjo+qN1WhZhNimq0dZATN9pH0IDrpA==}
|
||||
|
||||
remark-rehype@11.1.2:
|
||||
resolution: {integrity: sha512-Dh7l57ianaEoIpzbp0PC9UKAdCSVklD8E5Rpw7ETfbTl3FqcOOgq5q2LVDhgGCkaBv7p24JXikPdvhhmHvKMsw==}
|
||||
|
||||
remark-stringify@11.0.0:
|
||||
resolution: {integrity: sha512-1OSmLd3awB/t8qdoEOMazZkNsfVTeY4fTsgzcQFdXNq8ToTN4ZGwrMnlda4K6smTFKD+GRV6O48i6Z4iKgPPpw==}
|
||||
|
||||
@@ -6206,10 +6211,6 @@ snapshots:
|
||||
stringify-entities: 4.0.4
|
||||
zwitch: 2.0.4
|
||||
|
||||
hast-util-to-string@3.0.1:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.5
|
||||
|
||||
hast-util-whitespace@3.0.0:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.5
|
||||
@@ -7034,6 +7035,8 @@ snapshots:
|
||||
exsolve: 1.1.3
|
||||
pathe: 2.0.3
|
||||
|
||||
playwright-core@1.63.0: {}
|
||||
|
||||
possible-typed-array-names@1.1.0: {}
|
||||
|
||||
postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.28)(tsx@4.23.15):
|
||||
@@ -7082,6 +7085,8 @@ snapshots:
|
||||
dependencies:
|
||||
hookified: 2.2.0
|
||||
|
||||
qrcode-generator@2.0.4: {}
|
||||
|
||||
qs@6.16.0:
|
||||
dependencies:
|
||||
es-define-property: 1.0.1
|
||||
@@ -7205,14 +7210,6 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
remark-rehype@11.1.2:
|
||||
dependencies:
|
||||
'@types/hast': 3.0.5
|
||||
'@types/mdast': 4.0.4
|
||||
mdast-util-to-hast: 13.2.1
|
||||
unified: 11.0.5
|
||||
vfile: 6.0.3
|
||||
|
||||
remark-stringify@11.0.0:
|
||||
dependencies:
|
||||
'@types/mdast': 4.0.4
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// Проверка вёрстки: на телефонах страница не должна прокручиваться по горизонтали.
|
||||
// Запуск: node scripts/check-layout.mjs [адрес сайта] [папка для скриншотов]
|
||||
// Нужен установленный Chrome. Переменные KB_EMAIL / KB_PASSWORD: вход, если сайт закрыт.
|
||||
import { chromium } from 'playwright-core';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const base = process.argv[2] ?? 'http://localhost:8200';
|
||||
const shotsDir = process.argv[3];
|
||||
const devices = [
|
||||
{ name: 'iphone-se', width: 375, height: 667 },
|
||||
{ name: 'pixel-7', width: 412, height: 915 },
|
||||
{ name: 'desktop', width: 1440, height: 940 },
|
||||
];
|
||||
|
||||
const browser = await chromium.launch({ channel: 'chrome' });
|
||||
let failed = 0;
|
||||
|
||||
for (const d of devices) {
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: d.width, height: d.height },
|
||||
deviceScaleFactor: d.width < 500 ? 2 : 1,
|
||||
isMobile: d.width < 500,
|
||||
hasTouch: d.width < 500,
|
||||
});
|
||||
const page = await ctx.newPage();
|
||||
|
||||
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: false },
|
||||
});
|
||||
if (!res.ok()) throw new Error(`Не удалось войти: ${res.status()}`);
|
||||
}
|
||||
|
||||
const tree = await (await page.request.get(`${base}/api/tree`)).json();
|
||||
const paths = [
|
||||
'/',
|
||||
'/search?q=MG12',
|
||||
'/cheatsheet',
|
||||
'/favorites',
|
||||
...tree.sections.map((s) => `/s/${s.slug}`),
|
||||
...tree.articles.filter((a) => !a.pinned).map((a) => `/a/${a.slug}`),
|
||||
];
|
||||
|
||||
for (const p of paths) {
|
||||
await page.goto(base + p, { waitUntil: 'networkidle' });
|
||||
// Ширина содержимого больше ширины окна = есть горизонтальная прокрутка
|
||||
const over = await page.evaluate(() => {
|
||||
const w = document.documentElement.clientWidth;
|
||||
const wide = [...document.querySelectorAll('body *')]
|
||||
.filter((el) => el.getBoundingClientRect().right > w + 1 && !el.closest('.chips--scroll, .ed-toolbar'))
|
||||
.slice(0, 3)
|
||||
.map((el) => `${el.tagName.toLowerCase()}.${el.className}`);
|
||||
return { scroll: document.documentElement.scrollWidth - w, wide };
|
||||
});
|
||||
const ok = over.scroll <= 0 && over.wide.length === 0;
|
||||
if (!ok) failed++;
|
||||
console.log(`${ok ? 'ok ' : 'FAIL'} ${d.name.padEnd(10)} ${p}${ok ? '' : ` (+${over.scroll}px: ${over.wide.join(', ')})`}`);
|
||||
if (shotsDir) {
|
||||
fs.mkdirSync(shotsDir, { recursive: true });
|
||||
const name = p.replace(/[^a-z0-9]+/gi, '_').replace(/^_|_$/g, '') || 'home';
|
||||
await page.screenshot({ path: `${shotsDir}/${d.name}-${name}.png`, fullPage: false });
|
||||
}
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
console.log(failed ? `\nПроблем: ${failed}` : '\nГоризонтальной прокрутки нет');
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -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);
|
||||
@@ -0,0 +1,46 @@
|
||||
// Проверка поиска на контрольных запросах из ТЗ.
|
||||
// Запуск: node scripts/check-search.mjs [адрес API или сайта]
|
||||
// Переменные KB_EMAIL / KB_PASSWORD: вход, если сайт закрыт.
|
||||
const base = process.argv[2] ?? 'http://localhost:8200';
|
||||
|
||||
// запрос → slug статьи, которая обязана быть в выдаче
|
||||
const CASES = [
|
||||
['узип', 'stoyka-vezda-silovoe'],
|
||||
['MG12', 'uzel-fotoelementa'],
|
||||
['2273', 'stoyka-vezda-silovoe'],
|
||||
['патч корд sip', 'stoyka-vezda-slabotochka'],
|
||||
['ral 7024', 'navesy-terminala'],
|
||||
['шкос', 'shkos'],
|
||||
['RAL7024', 'navesy-terminala'],
|
||||
['1,2 м', 'shkon'],
|
||||
['шкоос', 'shkos'], // опечатка
|
||||
['ёлка-которой-нет', null],
|
||||
];
|
||||
|
||||
const headers = { 'X-Requested-With': 'kb' };
|
||||
if (process.env.KB_EMAIL) {
|
||||
const res = await fetch(`${base}/api/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { ...headers, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: process.env.KB_EMAIL, password: process.env.KB_PASSWORD, remember: false }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`Не удалось войти: ${res.status}`);
|
||||
headers.Cookie = res.headers.getSetCookie().map((c) => c.split(';')[0]).join('; ');
|
||||
}
|
||||
|
||||
const show = (h) => h.map((x) => (x.hit ? `[${x.t}]` : x.t)).join('');
|
||||
let failed = 0;
|
||||
|
||||
for (const [q, want] of CASES) {
|
||||
const res = await fetch(`${base}/api/search?q=${encodeURIComponent(q)}`, { headers });
|
||||
const r = await res.json();
|
||||
const slugs = (r.articles ?? []).map((a) => a.slug);
|
||||
const ok = want === null ? slugs.length === 0 : slugs.includes(want);
|
||||
if (!ok) failed++;
|
||||
console.log(`${ok ? 'ok ' : 'FAIL'} «${q}» → статей ${slugs.length}, цифр ${r.facts?.length ?? 0}`);
|
||||
for (const a of (r.articles ?? []).slice(0, 3)) console.log(` ${show(a.title)}\n ${show(a.snippet).slice(0, 110)}`);
|
||||
for (const f of (r.facts ?? []).slice(0, 2)) console.log(` # ${show(f.value)} — ${show(f.label).slice(0, 80)}`);
|
||||
}
|
||||
|
||||
console.log(failed ? `\nНе прошло: ${failed}` : '\nВсе контрольные запросы находятся');
|
||||
process.exit(failed ? 1 : 0);
|
||||
Reference in New Issue
Block a user