Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d320aeb65 | ||
|
|
00de88da56 | ||
|
|
2a8c2b5110 | ||
|
|
62a84931e7 | ||
|
|
8920c16e6f | ||
|
|
90ad495901 | ||
|
|
9f08158607 | ||
|
|
27cdca3967 | ||
|
|
79d49181a6 | ||
|
|
f2be0df17a | ||
|
|
0467281dc5 | ||
|
|
bca00cb103 |
@@ -12,6 +12,8 @@ DATABASE_URL=postgresql://wiki:wiki_dev_password@localhost:5440/wiki?schema=publ
|
||||
# --- Сайт ---
|
||||
# Порт сайта на хосте
|
||||
WEB_PORT=8200
|
||||
# На каком адресе сервера слушать (только docker-compose.prod.yml). См. DEPLOY.md, шаг 4.
|
||||
# WEB_BIND=127.0.0.1
|
||||
# Публичный адрес сайта (CORS, ссылки-приглашения, QR в печати)
|
||||
PUBLIC_URL=http://localhost:8200
|
||||
# Секрет для подписи cookie. Сгенерировать: openssl rand -hex 32
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
# Развёртывание на сервере (wiki.suchtech.ru)
|
||||
|
||||
Нужны: сервер с Docker и Docker Compose, работающий Nginx Proxy Manager (NPM), доступ к DNS домена.
|
||||
|
||||
## 1. DNS
|
||||
|
||||
В панели домена `suchtech.ru` добавьте запись:
|
||||
|
||||
| Тип | Имя | Значение |
|
||||
|---|---|---|
|
||||
| A | `wiki` | IP-адрес сервера |
|
||||
|
||||
Проверка (может обновляться до часа): `nslookup wiki.suchtech.ru` должен вернуть IP сервера.
|
||||
|
||||
## 2. Код и настройки
|
||||
|
||||
```bash
|
||||
git clone https://git.suchtech.ru/deonisii/wiki-montazh.git
|
||||
cd wiki-montazh
|
||||
cp .env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
В `.env` обязательно поменяйте:
|
||||
|
||||
```ini
|
||||
POSTGRES_PASSWORD=<длинный случайный пароль> # openssl rand -hex 24
|
||||
SESSION_SECRET=<длинная случайная строка> # openssl rand -hex 32
|
||||
PUBLIC_URL=https://wiki.suchtech.ru
|
||||
ADMIN_EMAIL=<ваша почта>
|
||||
ADMIN_PASSWORD=<пароль администратора, не короче 8 символов>
|
||||
```
|
||||
|
||||
`DATABASE_URL`, `DB_PORT` и `COOKIE_SECURE` для боевого запуска не нужны: compose задаёт их сам.
|
||||
|
||||
## 3. Запуск
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml up -d --build
|
||||
docker compose -f docker-compose.prod.yml ps # все три сервиса должны быть healthy
|
||||
curl http://127.0.0.1:8200/api/health # {"status":"ok","db":"ok",...}
|
||||
```
|
||||
|
||||
Миграции базы применяются сами при старте контейнера `api`.
|
||||
|
||||
Импорт стартовых статей и создание администратора (можно запускать повторно, дубликатов не будет):
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml exec api node dist/seed.js
|
||||
```
|
||||
|
||||
## 4. Nginx Proxy Manager
|
||||
|
||||
Сайт слушает `127.0.0.1:8200` на сервере. В NPM: **Hosts → Proxy Hosts → Add Proxy Host**.
|
||||
|
||||
Вкладка **Details**:
|
||||
|
||||
| Поле | Значение |
|
||||
|---|---|
|
||||
| Domain Names | `wiki.suchtech.ru` |
|
||||
| Scheme | `http` |
|
||||
| Forward Hostname / IP | см. ниже |
|
||||
| Forward Port | `8200` |
|
||||
| Block Common Exploits | включить |
|
||||
| Websockets Support | не нужно |
|
||||
|
||||
Что писать в **Forward Hostname / IP**:
|
||||
|
||||
- NPM установлен прямо на сервере (не в Docker): `127.0.0.1`.
|
||||
- NPM работает в Docker (обычный случай): из контейнера `127.0.0.1` указывает на сам контейнер NPM,
|
||||
поэтому в `.env` добавьте `WEB_BIND=172.17.0.1` (адрес docker-моста: `ip addr show docker0`),
|
||||
перезапустите `web` и укажите в NPM `172.17.0.1`.
|
||||
Другой вариант: подключить контейнер `web` к сети NPM
|
||||
(`docker network connect <сеть_npm> wiki-montazh-web-1`) и указать в NPM имя `wiki-montazh-web-1`, порт `80`.
|
||||
|
||||
Вкладка **SSL**: Request a new SSL Certificate (Let's Encrypt), включить **Force SSL**, **HTTP/2 Support**, **HSTS Enabled**.
|
||||
|
||||
Вкладка **Advanced** (чтобы загружались фото до 15 МБ и документы до 30 МБ):
|
||||
|
||||
```nginx
|
||||
client_max_body_size 32m;
|
||||
```
|
||||
|
||||
Проверка: https://wiki.suchtech.ru открывает экран входа, вход работает, замок в адресной строке зелёный.
|
||||
|
||||
## 5. Резервные копии
|
||||
|
||||
Скрипт делает дамп базы и архив загруженных файлов в папку `backups/` и удаляет копии старше 14 дней.
|
||||
|
||||
```bash
|
||||
chmod +x scripts/*.sh
|
||||
./scripts/backup.sh
|
||||
```
|
||||
|
||||
Ежедневно в 03:00 через cron (`crontab -e`):
|
||||
|
||||
```cron
|
||||
0 3 * * * cd /opt/wiki-montazh && ./scripts/backup.sh >> backups/backup.log 2>&1
|
||||
```
|
||||
|
||||
Копии лежат на том же сервере: настройте вынос папки `backups/` на другой диск или в облако
|
||||
(например, `rclone` или `rsync` следующей строкой cron). Копия, которая лежит рядом с оригиналом, от поломки диска не спасает.
|
||||
|
||||
### Проверить, что копия восстанавливается
|
||||
|
||||
Безопасная проверка: дамп разворачивается во временную базу, рабочие данные не трогаются.
|
||||
|
||||
```bash
|
||||
./scripts/restore.sh --check backups/db_2026-10-04_0300.dump
|
||||
```
|
||||
|
||||
### Восстановить
|
||||
|
||||
```bash
|
||||
./scripts/restore.sh backups/db_2026-10-04_0300.dump backups/uploads_2026-10-04_0300.tar.gz
|
||||
```
|
||||
|
||||
На чистом сервере: сначала шаги 2 и 3 (без seed), затем восстановление.
|
||||
|
||||
## 6. Обновление
|
||||
|
||||
```bash
|
||||
cd /opt/wiki-montazh
|
||||
./scripts/backup.sh
|
||||
git pull
|
||||
docker compose -f docker-compose.prod.yml up -d --build
|
||||
```
|
||||
|
||||
Данные (база и файлы) лежат в томах Docker и при пересборке сохраняются.
|
||||
У пользователей приложение обновится само при следующем открытии с сетью.
|
||||
|
||||
## 7. Если что-то не так
|
||||
|
||||
| Симптом | Что проверить |
|
||||
|---|---|
|
||||
| 502 в браузере | `docker compose -f docker-compose.prod.yml ps`; адрес и порт в NPM (см. шаг 4) |
|
||||
| Не входит, хотя пароль верный | сайт должен открываться по https: cookie выдаётся только по защищённому соединению |
|
||||
| «Запрос отклонён» при сохранении | `PUBLIC_URL` в `.env` должен точно совпадать с адресом сайта |
|
||||
| Не загружается большое фото | `client_max_body_size 32m;` во вкладке Advanced в NPM |
|
||||
| Логи | `docker compose -f docker-compose.prod.yml logs -f api` |
|
||||
|
||||
## Что настроено для безопасности
|
||||
|
||||
- Пароли: argon2id. Сессия: случайный токен в httpOnly + Secure + SameSite=Lax cookie, в базе только его хеш.
|
||||
- Права проверяет сервер (`requireRole`), а не только интерфейс. Проверка: `scripts/check-roles.mjs`.
|
||||
- `helmet`, CSP (скрипты только со своего домена), запрет встраивания в чужие страницы.
|
||||
- CORS только для `PUBLIC_URL`; изменяющие запросы требуют заголовок `X-Requested-With` (защита от CSRF).
|
||||
- Ограничение частоты: 10 неудачных входов за 15 минут, 600 запросов в минуту с одного адреса.
|
||||
- Загрузки: тип файла проверяется по содержимому, картинки до 15 МБ, документы до 30 МБ; EXIF удаляется.
|
||||
- Markdown: HTML из текста не пропускается, результат проходит `rehype-sanitize`.
|
||||
- Все входные данные проверяются схемами Zod.
|
||||
- Файлы закрытых статей (`/uploads`) без входа не отдаются.
|
||||
@@ -55,6 +55,36 @@ pnpm dev # API на :3000, сайт на http://localhost:5180
|
||||
| `pnpm --filter @kb/api exec prisma studio` | посмотреть БД в браузере |
|
||||
| `pnpm --filter @kb/api exec prisma migrate dev --name <имя>` | новая миграция после правки `schema.prisma` |
|
||||
|
||||
## Проверки
|
||||
|
||||
Скрипты в `scripts/` проверяют критерии приёмки на работающем сайте (нужен установленный Chrome).
|
||||
Если сайт закрыт входом, передайте учётную запись администратора:
|
||||
|
||||
```bash
|
||||
export KB_EMAIL=admin@suchtech.ru KB_PASSWORD=...
|
||||
node scripts/check-layout.mjs # нет горизонтальной прокрутки на 375 / 412 / 1440 px
|
||||
node scripts/check-search.mjs # контрольные запросы: «узип», «MG12», «2273», «патч корд sip»…
|
||||
node scripts/check-offline.mjs # режим «самолёт»: главная, шпаргалка, открытые и скачанные статьи
|
||||
node scripts/check-roles.mjs # права гостя, читателя и редактора проверяются на сервере
|
||||
```
|
||||
|
||||
## Развёртывание и резервные копии
|
||||
|
||||
Пошагово в [DEPLOY.md](DEPLOY.md): DNS, Nginx Proxy Manager, `docker-compose.prod.yml`, бэкап и восстановление.
|
||||
|
||||
## Как устроено
|
||||
|
||||
- **Статья** хранится в Markdown (`Article.bodyMd`). При публикации сервер один раз превращает её в HTML
|
||||
пакетом `packages/md` и сохраняет (`bodyHtml`), читателю отдаётся готовый HTML.
|
||||
Тот же пакет рисует предпросмотр в редакторе, поэтому «как в редакторе» = «как на сайте».
|
||||
- **Блоки**: `:::keyfacts`, `:::danger`, `:::warning`, `:::tip`, `:::info`, чек-листы `- [ ]`,
|
||||
шаги `1. **Заголовок.** текст`, таблицы, фото ``, ссылки `[[slug]]`.
|
||||
- **Картинки** при загрузке пережимаются в WebP: `имя.webp` (до 1600 px) и `имя.480.webp` (превью). EXIF удаляется.
|
||||
- **Поиск**: PostgreSQL full-text + `pg_trgm`. Логика и комментарии в `apps/api/src/search.ts`.
|
||||
- **Офлайн**: service worker (Workbox) кеширует интерфейс и всё, что открывалось; раздел можно скачать заранее.
|
||||
- **Цвета и размеры**: только токены из `apps/web/src/styles/tokens.css`. Три темы: тёмная, светлая, «Солнце».
|
||||
- **Роли**: читатель (VIEWER) читает, редактор (EDITOR) правит статьи, админ (ADMIN) управляет людьми и структурой.
|
||||
|
||||
## Переменные окружения
|
||||
|
||||
Все перечислены с комментариями в [.env.example](.env.example).
|
||||
|
||||
@@ -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);
|
||||
+88
-3
@@ -1,9 +1,54 @@
|
||||
import express, { type ErrorRequestHandler } from 'express';
|
||||
import path from 'node:path';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import cors from 'cors';
|
||||
import express, { type ErrorRequestHandler, type RequestHandler } from 'express';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { ZodError } from 'zod';
|
||||
import type { HealthResponse } from '@kb/shared';
|
||||
import { csrfGuard, loadUser } from './auth.js';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { adminRouter } from './routes/admin.js';
|
||||
import { authRouter } from './routes/auth.js';
|
||||
import { contentRouter } from './routes/content.js';
|
||||
import { editRouter } from './routes/edit.js';
|
||||
import { meRouter } from './routes/me.js';
|
||||
|
||||
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
|
||||
const publicFiles = new Map<string, { ok: boolean; at: number }>();
|
||||
const PUBLIC_TTL = 60_000;
|
||||
|
||||
async function isPublicFile(rel: string): Promise<boolean> {
|
||||
const hit = publicFiles.get(rel);
|
||||
if (hit && Date.now() - hit.at < PUBLIC_TTL) return hit.ok;
|
||||
// Превью fig-1.480.webp относится к той же записи, что и fig-1.webp
|
||||
const assetPath = rel.replace(/\.480\.webp$/, '.webp');
|
||||
const open = { status: 'PUBLISHED', visibility: 'PUBLIC' } as const;
|
||||
const [asset, attachment] = await Promise.all([
|
||||
prisma.asset.findFirst({ where: { path: assetPath, article: open }, select: { id: true } }),
|
||||
prisma.attachment.findFirst({ where: { path: rel, article: open }, select: { id: true } }),
|
||||
]);
|
||||
const ok = !!asset || !!attachment;
|
||||
if (publicFiles.size > 5000) publicFiles.clear();
|
||||
publicFiles.set(rel, { ok, at: Date.now() });
|
||||
return ok;
|
||||
}
|
||||
|
||||
/** Файлы закрытых статей отдаём только вошедшим пользователям. */
|
||||
const uploadsGuard: RequestHandler = async (req, res, next) => {
|
||||
if (req.user) return next();
|
||||
let rel: string;
|
||||
try {
|
||||
rel = path.posix.normalize(decodeURIComponent(req.path)).replace(/^\/+/, '');
|
||||
} catch {
|
||||
res.status(400).json({ error: 'Некорректный адрес' });
|
||||
return;
|
||||
}
|
||||
if (await isPublicFile(rel)) return next();
|
||||
res.status(401).json({ error: 'Нужно войти' });
|
||||
};
|
||||
|
||||
export function createApp() {
|
||||
const app = express();
|
||||
@@ -11,7 +56,23 @@ export function createApp() {
|
||||
// (нужно для rate-limit по IP и secure-cookie).
|
||||
app.set('trust proxy', 2);
|
||||
app.disable('x-powered-by');
|
||||
|
||||
// Заголовки безопасности. API отдаёт только JSON и файлы, поэтому политика самая строгая:
|
||||
// ничего не загружать и не встраивать. (CSP для самих страниц сайта задаёт nginx, см. apps/web/nginx.conf.)
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: { useDefaults: false, directives: { defaultSrc: ["'none'"], frameAncestors: ["'none'"] } },
|
||||
crossOriginResourcePolicy: { policy: 'same-origin' },
|
||||
// HSTS выставляет Nginx Proxy Manager, который и держит сертификат
|
||||
strictTransportSecurity: false,
|
||||
}),
|
||||
);
|
||||
// CORS: запросы с cookie принимаем только со своего домена
|
||||
app.use('/api', cors({ origin: new URL(env.PUBLIC_URL).origin, credentials: true, methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] }));
|
||||
// Общий предел запросов с одного адреса: защита от перебора и случайных циклов
|
||||
app.use('/api', rateLimit({ windowMs: 60_000, limit: 600, standardHeaders: 'draft-7', legacyHeaders: false, message: { error: 'Слишком много запросов. Подождите минуту.' } }));
|
||||
app.use(express.json({ limit: '2mb' }));
|
||||
app.use(cookieParser());
|
||||
|
||||
// Healthcheck: проверяет и сам процесс, и соединение с БД.
|
||||
app.get('/api/health', async (_req, res) => {
|
||||
@@ -20,16 +81,20 @@ export function createApp() {
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Загруженные файлы. Имена картинок не меняются при замене содержимого редко,
|
||||
// поэтому кешируем на сутки, а дальше браузер перепроверяет по ETag.
|
||||
app.use(loadUser);
|
||||
|
||||
// Загруженные файлы: кешируются на сутки, дальше браузер перепроверяет по ETag.
|
||||
app.use(
|
||||
'/uploads',
|
||||
uploadsGuard,
|
||||
express.static(env.UPLOADS_DIR, {
|
||||
index: false,
|
||||
dotfiles: 'deny',
|
||||
maxAge: '1d',
|
||||
setHeaders(res, file) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
// private: общие прокси не должны хранить файлы закрытых статей
|
||||
res.setHeader('Cache-Control', 'private, max-age=86400');
|
||||
// Исходники (PDF/DOCX) всегда скачиваются, а не открываются в браузере
|
||||
if (!/\.(webp|png|jpe?g|gif)$/i.test(file)) res.setHeader('Content-Disposition', 'attachment');
|
||||
},
|
||||
@@ -39,6 +104,11 @@ export function createApp() {
|
||||
res.status(404).json({ error: 'Файл не найден' });
|
||||
});
|
||||
|
||||
app.use('/api', csrfGuard);
|
||||
app.use('/api/auth', authRouter);
|
||||
app.use('/api/me', meRouter);
|
||||
app.use('/api/edit', editRouter);
|
||||
app.use('/api/admin', adminRouter);
|
||||
app.use('/api', contentRouter);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
@@ -51,6 +121,21 @@ export function createApp() {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
return;
|
||||
}
|
||||
// Ошибка проверки входных данных (Zod): показываем первое понятное сообщение
|
||||
if (err instanceof ZodError) {
|
||||
const first = err.issues[0];
|
||||
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
|
||||
return;
|
||||
}
|
||||
if (err?.name === 'MulterError') {
|
||||
const big = err.code === 'LIMIT_FILE_SIZE';
|
||||
res.status(big ? 413 : 400).json({ error: big ? 'Файл слишком большой (картинки до 15 МБ, документы до 30 МБ)' : 'Не удалось принять файл' });
|
||||
return;
|
||||
}
|
||||
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') {
|
||||
res.status(400).json({ error: 'Некорректный запрос' });
|
||||
return;
|
||||
}
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// Сессии и проверка прав.
|
||||
//
|
||||
// Как это устроено:
|
||||
// - при входе создаём случайный токен, кладём его в httpOnly-cookie (JavaScript страницы его не видит),
|
||||
// а в БД сохраняем только SHA-256 от токена;
|
||||
// - на каждом запросе по cookie находим сессию и пользователя (req.user);
|
||||
// - requireAuth / requireRole стоят перед обработчиками: права проверяет сервер, а не только интерфейс.
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import type { NextFunction, Request, RequestHandler, Response } from 'express';
|
||||
import type { Role, User } from '@prisma/client';
|
||||
import type { UserDto } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
|
||||
export const COOKIE = 'kb_session';
|
||||
const DAY = 24 * 60 * 60 * 1000;
|
||||
export const REMEMBER_MS = 90 * DAY; // «Запомнить устройство»
|
||||
export const SHORT_MS = 1 * DAY; // без галочки: сутки, cookie живёт до закрытия браузера
|
||||
|
||||
// Добавляем свои поля в тип запроса Express (так это принято делать в его типах)
|
||||
declare global {
|
||||
// eslint-disable-next-line @typescript-eslint/no-namespace
|
||||
namespace Express {
|
||||
interface Request {
|
||||
user?: User;
|
||||
sessionId?: string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sha256 = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
|
||||
|
||||
export const toUserDto = (u: User): UserDto => ({ id: u.id, email: u.email, name: u.name, role: u.role });
|
||||
|
||||
export async function createSession(res: Response, user: User, remember: boolean, userAgent?: string) {
|
||||
const token = crypto.randomBytes(32).toString('base64url');
|
||||
const ttl = remember ? REMEMBER_MS : SHORT_MS;
|
||||
await prisma.session.create({
|
||||
data: {
|
||||
tokenHash: sha256(token),
|
||||
userId: user.id,
|
||||
expiresAt: new Date(Date.now() + ttl),
|
||||
userAgent: userAgent?.slice(0, 300),
|
||||
},
|
||||
});
|
||||
res.cookie(COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: env.COOKIE_SECURE,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
// Без maxAge cookie сессионная: пропадает при закрытии браузера
|
||||
...(remember ? { maxAge: ttl } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
export async function destroySession(req: Request, res: Response) {
|
||||
const token = req.cookies?.[COOKIE] as string | undefined;
|
||||
if (token) await prisma.session.deleteMany({ where: { tokenHash: sha256(token) } });
|
||||
res.clearCookie(COOKIE, { path: '/' });
|
||||
}
|
||||
|
||||
/** Находит пользователя по cookie. Не требует входа: просто заполняет req.user, если сессия жива. */
|
||||
export const loadUser: RequestHandler = async (req, _res, next) => {
|
||||
const token = req.cookies?.[COOKIE] as string | undefined;
|
||||
if (!token) return next();
|
||||
const session = await prisma.session.findUnique({ where: { tokenHash: sha256(token) }, include: { user: true } });
|
||||
if (!session || session.expiresAt < new Date() || session.user.blocked) return next();
|
||||
req.user = session.user;
|
||||
req.sessionId = session.id;
|
||||
// Отметку «был в сети» обновляем не чаще раза в 10 минут, чтобы не писать в БД на каждый запрос
|
||||
if (!session.user.lastSeenAt || Date.now() - session.user.lastSeenAt.getTime() > 10 * 60 * 1000) {
|
||||
void prisma.user.update({ where: { id: session.user.id }, data: { lastSeenAt: new Date() } }).catch(() => undefined);
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
export const requireAuth: RequestHandler = (req, _res, next) => {
|
||||
if (!req.user) throw new HttpError(401, 'Нужно войти');
|
||||
next();
|
||||
};
|
||||
|
||||
const RANK: Record<Role, number> = { VIEWER: 1, EDITOR: 2, ADMIN: 3 };
|
||||
|
||||
/** Доступ с роли и выше: requireRole('EDITOR') пускает редакторов и админов. */
|
||||
export const requireRole =
|
||||
(role: Role): RequestHandler =>
|
||||
(req, _res, next) => {
|
||||
if (!req.user) throw new HttpError(401, 'Нужно войти');
|
||||
if (RANK[req.user.role] < RANK[role]) throw new HttpError(403, 'Недостаточно прав');
|
||||
next();
|
||||
};
|
||||
|
||||
export const canEdit = (u?: User) => !!u && RANK[u.role] >= RANK.EDITOR;
|
||||
|
||||
/**
|
||||
* Защита от CSRF: на изменяющих запросах требуем заголовок X-Requested-With.
|
||||
* Чужой сайт не может отправить его из браузера пользователя без разрешения CORS,
|
||||
* а CORS у нас открыт только для своего домена.
|
||||
*/
|
||||
export function csrfGuard(req: Request, _res: Response, next: NextFunction) {
|
||||
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
|
||||
if (req.get('X-Requested-With') !== 'kb') throw new HttpError(403, 'Запрос отклонён');
|
||||
next();
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Админка: пользователи, приглашения, пространства и разделы. Только для роли ADMIN.
|
||||
import { Router } from 'express';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { z } from 'zod';
|
||||
import type { AdminUserDto, InviteDto } from '@kb/shared';
|
||||
import { requireRole } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { env } from '../env.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { toSectionDto, toSpaceDto } from './content.js';
|
||||
import { slugify } from './edit.js';
|
||||
|
||||
export const adminRouter = Router();
|
||||
adminRouter.use(requireRole('ADMIN'));
|
||||
|
||||
const role = z.enum(['ADMIN', 'EDITOR', 'VIEWER']);
|
||||
const INVITE_DAYS = 7;
|
||||
|
||||
// ---------- Пользователи ----------
|
||||
adminRouter.get('/users', async (_req, res) => {
|
||||
const users = await prisma.user.findMany({ orderBy: [{ blocked: 'asc' }, { name: 'asc' }] });
|
||||
const list: AdminUserDto[] = users.map((u) => ({
|
||||
id: u.id,
|
||||
email: u.email,
|
||||
name: u.name,
|
||||
role: u.role,
|
||||
blocked: u.blocked,
|
||||
createdAt: u.createdAt.toISOString(),
|
||||
lastSeenAt: u.lastSeenAt?.toISOString() ?? null,
|
||||
}));
|
||||
res.json(list);
|
||||
});
|
||||
|
||||
/** Нельзя оставить систему без действующего администратора. */
|
||||
async function assertAdminRemains(exceptId: string) {
|
||||
const others = await prisma.user.count({ where: { role: 'ADMIN', blocked: false, id: { not: exceptId } } });
|
||||
if (!others) throw new HttpError(400, 'Должен остаться хотя бы один администратор');
|
||||
}
|
||||
|
||||
adminRouter.patch('/users/:id', async (req, res) => {
|
||||
const input = z.object({ role: role.optional(), blocked: z.boolean().optional(), name: z.string().trim().min(2).max(100).optional() }).parse(req.body);
|
||||
const id = String(req.params.id);
|
||||
const user = await prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new HttpError(404, 'Пользователь не найден');
|
||||
const losesAdmin = user.role === 'ADMIN' && ((input.role && input.role !== 'ADMIN') || input.blocked === true);
|
||||
if (losesAdmin) {
|
||||
if (id === req.user!.id) throw new HttpError(400, 'Нельзя понизить или заблокировать самого себя');
|
||||
await assertAdminRemains(id);
|
||||
}
|
||||
const updated = await prisma.user.update({ where: { id }, data: input });
|
||||
// Заблокированного сразу выкидываем со всех устройств
|
||||
if (input.blocked) await prisma.session.deleteMany({ where: { userId: id } });
|
||||
res.json({ id: updated.id, role: updated.role, blocked: updated.blocked, name: updated.name });
|
||||
});
|
||||
|
||||
adminRouter.delete('/users/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (id === req.user!.id) throw new HttpError(400, 'Нельзя удалить самого себя');
|
||||
const user = await prisma.user.findUnique({ where: { id } });
|
||||
if (!user) throw new HttpError(404, 'Пользователь не найден');
|
||||
if (user.role === 'ADMIN') await assertAdminRemains(id);
|
||||
await prisma.user.delete({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Приглашения ----------
|
||||
const toInvite = (i: { id: string; token: string; role: 'ADMIN' | 'EDITOR' | 'VIEWER'; expiresAt: Date; usedAt: Date | null }): InviteDto => ({
|
||||
id: i.id,
|
||||
token: i.token,
|
||||
role: i.role,
|
||||
expiresAt: i.expiresAt.toISOString(),
|
||||
usedAt: i.usedAt?.toISOString() ?? null,
|
||||
url: `${env.PUBLIC_URL.replace(/\/$/, '')}/invite/${i.token}`,
|
||||
});
|
||||
|
||||
adminRouter.get('/invites', async (_req, res) => {
|
||||
const rows = await prisma.invite.findMany({ where: { usedAt: null, expiresAt: { gt: new Date() } }, orderBy: { createdAt: 'desc' } });
|
||||
res.json(rows.map(toInvite));
|
||||
});
|
||||
|
||||
adminRouter.post('/invites', async (req, res) => {
|
||||
const input = z.object({ role: role.default('VIEWER') }).parse(req.body);
|
||||
const invite = await prisma.invite.create({
|
||||
data: { token: nanoid(32), role: input.role, expiresAt: new Date(Date.now() + INVITE_DAYS * 86_400_000) },
|
||||
});
|
||||
res.status(201).json(toInvite(invite));
|
||||
});
|
||||
|
||||
adminRouter.delete('/invites/:id', async (req, res) => {
|
||||
await prisma.invite.deleteMany({ where: { id: String(req.params.id) } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Пространства ----------
|
||||
const spaceBody = z.object({ name: z.string().trim().min(1, 'Укажите название').max(60), icon: z.string().trim().max(4).nullish() });
|
||||
|
||||
async function freeSlug(base: string, taken: (slug: string) => Promise<boolean>) {
|
||||
for (let i = 1; ; i++) {
|
||||
const slug = i === 1 ? base : `${base}-${i}`;
|
||||
if (!(await taken(slug))) return slug;
|
||||
}
|
||||
}
|
||||
|
||||
adminRouter.post('/spaces', async (req, res) => {
|
||||
const input = spaceBody.parse(req.body);
|
||||
const slug = await freeSlug(slugify(input.name), async (s) => !!(await prisma.space.findUnique({ where: { slug: s } })));
|
||||
const last = await prisma.space.aggregate({ _max: { order: true } });
|
||||
const space = await prisma.space.create({
|
||||
data: { name: input.name, slug, icon: input.icon || input.name[0]!.toUpperCase(), order: (last._max.order ?? 0) + 1 },
|
||||
});
|
||||
res.status(201).json(toSpaceDto(space));
|
||||
});
|
||||
|
||||
adminRouter.patch('/spaces/:id', async (req, res) => {
|
||||
const input = spaceBody.partial().parse(req.body);
|
||||
const space = await prisma.space.update({ where: { id: String(req.params.id) }, data: input }).catch(() => null);
|
||||
if (!space) throw new HttpError(404, 'Пространство не найдено');
|
||||
res.json(toSpaceDto(space));
|
||||
});
|
||||
|
||||
adminRouter.delete('/spaces/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (await prisma.section.count({ where: { spaceId: id } })) throw new HttpError(400, 'Сначала удалите или перенесите разделы');
|
||||
await prisma.space.deleteMany({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- Разделы ----------
|
||||
const color = z.enum(['yellow', 'orange', 'blue', 'green', 'ink']);
|
||||
const sectionBody = z.object({
|
||||
spaceId: z.string().min(1),
|
||||
name: z.string().trim().min(1, 'Укажите название').max(80),
|
||||
code: z.string().trim().min(1, 'Укажите код').max(4),
|
||||
color: color.default('ink'),
|
||||
icon: z.string().trim().max(4).nullish(),
|
||||
});
|
||||
|
||||
adminRouter.post('/sections', async (req, res) => {
|
||||
const input = sectionBody.parse(req.body);
|
||||
if (!(await prisma.space.findUnique({ where: { id: input.spaceId } }))) throw new HttpError(400, 'Пространство не найдено');
|
||||
const slug = await freeSlug(slugify(input.name), async (s) => !!(await prisma.section.findUnique({ where: { slug: s } })));
|
||||
const last = await prisma.section.aggregate({ where: { spaceId: input.spaceId }, _max: { order: true } });
|
||||
const section = await prisma.section.create({
|
||||
data: { ...input, code: input.code.toUpperCase(), slug, order: (last._max.order ?? 0) + 1 },
|
||||
});
|
||||
res.status(201).json(toSectionDto(section));
|
||||
});
|
||||
|
||||
adminRouter.patch('/sections/:id', async (req, res) => {
|
||||
const input = sectionBody.omit({ spaceId: true }).partial().parse(req.body);
|
||||
const section = await prisma.section
|
||||
.update({ where: { id: String(req.params.id) }, data: { ...input, ...(input.code ? { code: input.code.toUpperCase() } : {}) } })
|
||||
.catch(() => null);
|
||||
if (!section) throw new HttpError(404, 'Раздел не найден');
|
||||
res.json(toSectionDto(section));
|
||||
});
|
||||
|
||||
adminRouter.delete('/sections/:id', async (req, res) => {
|
||||
const id = String(req.params.id);
|
||||
if (await prisma.article.count({ where: { sectionId: id } })) throw new HttpError(400, 'В разделе есть статьи: сначала перенесите или удалите их');
|
||||
await prisma.section.deleteMany({ where: { id } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Новый порядок разделов после перетаскивания: присылается полный список id
|
||||
adminRouter.put('/sections/order', async (req, res) => {
|
||||
const { ids } = z.object({ ids: z.array(z.string()).min(1).max(500) }).parse(req.body);
|
||||
await prisma.$transaction(ids.map((id, order) => prisma.section.updateMany({ where: { id }, data: { order } })));
|
||||
res.status(204).end();
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { Router } from 'express';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import { z } from 'zod';
|
||||
import { createSession, destroySession, requireAuth, toUserDto } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { hashPassword, verifyPassword } from '../services/password.js';
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
// Не больше 10 неудачных попыток входа с одного адреса за 15 минут
|
||||
const loginLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 10,
|
||||
skipSuccessfulRequests: true,
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { error: 'Слишком много попыток входа. Подождите 15 минут.' },
|
||||
});
|
||||
|
||||
const inviteLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 30, standardHeaders: 'draft-7', legacyHeaders: false });
|
||||
|
||||
const email = z.string().trim().toLowerCase().email('Некорректная почта').max(200);
|
||||
const loginBody = z.object({ email, password: z.string().min(1).max(200), remember: z.boolean().default(false) });
|
||||
|
||||
// Заранее посчитанный хеш: если пользователя нет, всё равно тратим время на проверку пароля,
|
||||
// чтобы по скорости ответа нельзя было узнать, зарегистрирована ли почта.
|
||||
const dummyHash = hashPassword('not-a-real-password');
|
||||
|
||||
authRouter.post('/login', loginLimiter, async (req, res) => {
|
||||
const body = loginBody.parse(req.body);
|
||||
const user = await prisma.user.findUnique({ where: { email: body.email } });
|
||||
const ok = await verifyPassword(user?.passwordHash ?? (await dummyHash), body.password);
|
||||
if (!user || !ok) throw new HttpError(401, 'Неверная почта или пароль');
|
||||
if (user.blocked) throw new HttpError(403, 'Учётная запись заблокирована');
|
||||
await createSession(res, user, body.remember, req.get('user-agent'));
|
||||
res.json({ user: toUserDto(user) });
|
||||
});
|
||||
|
||||
authRouter.post('/logout', async (req, res) => {
|
||||
await destroySession(req, res);
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
authRouter.get('/me', requireAuth, (req, res) => {
|
||||
res.json({ user: toUserDto(req.user!) });
|
||||
});
|
||||
|
||||
// ---------- Приглашения ----------
|
||||
async function findInvite(token: string) {
|
||||
const invite = await prisma.invite.findUnique({ where: { token } });
|
||||
if (!invite || invite.usedAt || invite.expiresAt < new Date()) {
|
||||
throw new HttpError(404, 'Ссылка-приглашение недействительна или уже использована');
|
||||
}
|
||||
return invite;
|
||||
}
|
||||
|
||||
authRouter.get('/invite/:token', inviteLimiter, async (req, res) => {
|
||||
const invite = await findInvite(String(req.params.token));
|
||||
res.json({ role: invite.role, expiresAt: invite.expiresAt.toISOString() });
|
||||
});
|
||||
|
||||
const acceptBody = z.object({
|
||||
email,
|
||||
name: z.string().trim().min(2, 'Укажите имя').max(100),
|
||||
password: z.string().min(8, 'Пароль не короче 8 символов').max(200),
|
||||
});
|
||||
|
||||
authRouter.post('/invite/:token', inviteLimiter, async (req, res) => {
|
||||
const body = acceptBody.parse(req.body);
|
||||
const invite = await findInvite(String(req.params.token));
|
||||
if (await prisma.user.findUnique({ where: { email: body.email } })) {
|
||||
throw new HttpError(409, 'Пользователь с такой почтой уже есть. Войдите с паролем.');
|
||||
}
|
||||
const passwordHash = await hashPassword(body.password);
|
||||
// В одной транзакции: приглашение одноразовое, два человека по одной ссылке не зарегистрируются
|
||||
const user = await prisma.$transaction(async (tx) => {
|
||||
const used = await tx.invite.updateMany({ where: { id: invite.id, usedAt: null }, data: { usedAt: new Date() } });
|
||||
if (used.count !== 1) throw new HttpError(404, 'Ссылка-приглашение уже использована');
|
||||
return tx.user.create({ data: { email: body.email, name: body.name, passwordHash, role: invite.role } });
|
||||
});
|
||||
await createSession(res, user, true, req.get('user-agent'));
|
||||
res.status(201).json({ user: toUserDto(user) });
|
||||
});
|
||||
@@ -2,8 +2,10 @@ import { Router } from 'express';
|
||||
import type { Article, Section, Space } from '@prisma/client';
|
||||
import { parseCheatSheet, renderMarkdown } from '@kb/md';
|
||||
import type { ArticleDto, ArticleListItem, SectionDto, SpaceDto, TreeResponse, PlaqueColor } from '@kb/shared';
|
||||
import { canEdit } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { search } from '../search.js';
|
||||
|
||||
export const contentRouter = Router();
|
||||
|
||||
@@ -44,18 +46,28 @@ export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({
|
||||
// Всё дерево одним запросом: пространства, разделы и список статей (без текста).
|
||||
// Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны,
|
||||
// а для офлайна один ответ кешировать проще.
|
||||
contentRouter.get('/tree', async (_req, res) => {
|
||||
const [spaces, sections, articles] = await Promise.all([
|
||||
// Кто что видит: без входа только опубликованные статьи с visibility PUBLIC;
|
||||
// читатель: все опубликованные; редактор и админ: ещё и черновики.
|
||||
contentRouter.get('/tree', async (req, res) => {
|
||||
const where = !req.user
|
||||
? { status: 'PUBLISHED' as const, visibility: 'PUBLIC' as const }
|
||||
: canEdit(req.user)
|
||||
? {}
|
||||
: { status: 'PUBLISHED' as const };
|
||||
const [spaces, allSections, articles] = await Promise.all([
|
||||
prisma.space.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.section.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.article.findMany({
|
||||
where: { status: 'PUBLISHED' },
|
||||
where,
|
||||
orderBy: [{ order: 'asc' }, { title: 'asc' }],
|
||||
include: { assets: { select: { size: true } } },
|
||||
}),
|
||||
]);
|
||||
// Гостю не показываем даже названия разделов, в которых нет публичных статей
|
||||
const used = new Set(articles.map((a) => a.sectionId));
|
||||
const sections = req.user ? allSections : allSections.filter((s) => used.has(s.id));
|
||||
const body: TreeResponse = {
|
||||
spaces: spaces.map(toSpaceDto),
|
||||
spaces: req.user || sections.length ? spaces.map(toSpaceDto) : [],
|
||||
sections: sections.map(toSectionDto),
|
||||
articles: articles.map(toListItem),
|
||||
};
|
||||
@@ -71,7 +83,9 @@ contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
author: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
if (!art || art.status !== 'PUBLISHED') throw new HttpError(404, 'Статья не найдена');
|
||||
if (!art || (art.status !== 'PUBLISHED' && !canEdit(req.user))) throw new HttpError(404, 'Статья не найдена');
|
||||
// Закрытая статья без входа: 401, клиент покажет экран входа
|
||||
if (!req.user && art.visibility !== 'PUBLIC') throw new HttpError(401, 'Нужно войти');
|
||||
|
||||
// Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье
|
||||
const { figures, toc } = renderMarkdown(art.bodyMd);
|
||||
@@ -93,3 +107,9 @@ contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
};
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Поиск. Пустой запрос: пустой ответ (подсказки рисует клиент).
|
||||
contentRouter.get('/search', async (req, res) => {
|
||||
const q = String(req.query.q ?? '').slice(0, 100);
|
||||
res.json(await search(q, !req.user));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
// Редактирование статей. Все маршруты доступны только редакторам и админам:
|
||||
// проверка стоит здесь, на сервере, а не только в интерфейсе.
|
||||
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { Router } from 'express';
|
||||
import multer from 'multer';
|
||||
import { nanoid } from 'nanoid';
|
||||
import sharp from 'sharp';
|
||||
import { z } from 'zod';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import type { RevisionDto } from '@kb/shared';
|
||||
import { requireRole } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { deriveFacts, linkAssets, renderArticle, rerenderAll, updateSearchIndex } from '../services/articles.js';
|
||||
import { storeImage, uploadPath } from '../services/images.js';
|
||||
|
||||
export const editRouter = Router();
|
||||
editRouter.use(requireRole('EDITOR'));
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
export const MAX_IMAGE = 15 * MB;
|
||||
export const MAX_DOC = 30 * MB;
|
||||
|
||||
// Файлы принимаем в память: дальше картинку всё равно пережимает sharp, а документ проверяем по содержимому
|
||||
const uploadImage = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_IMAGE, files: 1 } }).single('file');
|
||||
const uploadDoc = multer({ storage: multer.memoryStorage(), limits: { fileSize: MAX_DOC, files: 1 } }).single('file');
|
||||
|
||||
const meta = z.object({
|
||||
title: z.string().trim().min(2, 'Укажите название').max(200),
|
||||
summary: z.string().trim().max(500).default(''),
|
||||
sectionId: z.string().min(1, 'Выберите раздел'),
|
||||
tags: z.array(z.string().trim().min(1).max(60)).max(30).default([]),
|
||||
equipment: z.array(z.string().trim().min(1).max(80)).max(30).default([]),
|
||||
docCode: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(200)
|
||||
.nullish()
|
||||
.transform((v) => v || null),
|
||||
pinned: z.boolean().default(false),
|
||||
visibility: z.enum(['PRIVATE', 'PUBLIC']).default('PRIVATE'),
|
||||
order: z.number().int().min(0).max(9999).default(0),
|
||||
});
|
||||
const body = z.object({ md: z.string().max(400_000), meta });
|
||||
|
||||
const TRANSLIT: Record<string, string> = {
|
||||
а: 'a', б: 'b', в: 'v', г: 'g', д: 'd', е: 'e', ё: 'e', ж: 'zh', з: 'z', и: 'i', й: 'y', к: 'k', л: 'l', м: 'm',
|
||||
н: 'n', о: 'o', п: 'p', р: 'r', с: 's', т: 't', у: 'u', ф: 'f', х: 'h', ц: 'c', ч: 'ch', ш: 'sh', щ: 'sch',
|
||||
ъ: '', ы: 'y', ь: '', э: 'e', ю: 'yu', я: 'ya',
|
||||
};
|
||||
|
||||
/** «Стойка въезда — слаботочка» → stoyka-vezda-slabotochka */
|
||||
export function slugify(title: string): string {
|
||||
const s = [...title.toLowerCase()]
|
||||
.map((ch) => TRANSLIT[ch] ?? ch)
|
||||
.join('')
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '')
|
||||
.slice(0, 60)
|
||||
.replace(/-+$/, '');
|
||||
return s || 'statya';
|
||||
}
|
||||
|
||||
async function uniqueSlug(base: string): Promise<string> {
|
||||
for (let i = 1; ; i++) {
|
||||
const slug = i === 1 ? base : `${base}-${i}`;
|
||||
if (!(await prisma.article.findUnique({ where: { slug }, select: { id: true } }))) return slug;
|
||||
}
|
||||
}
|
||||
|
||||
async function getArticle(id: string) {
|
||||
const art = await prisma.article.findUnique({ where: { id } });
|
||||
if (!art) throw new HttpError(404, 'Статья не найдена');
|
||||
return art;
|
||||
}
|
||||
|
||||
// Данные для редактора: опубликованный текст, несохранённый черновик, вложения
|
||||
editRouter.get('/articles/:slug', async (req, res) => {
|
||||
const art = await prisma.article.findUnique({
|
||||
where: { slug: String(req.params.slug) },
|
||||
include: { attachments: { orderBy: { createdAt: 'asc' } } },
|
||||
});
|
||||
if (!art) throw new HttpError(404, 'Статья не найдена');
|
||||
res.json({
|
||||
id: art.id,
|
||||
slug: art.slug,
|
||||
status: art.status,
|
||||
version: art.version,
|
||||
updatedAt: art.updatedAt.toISOString(),
|
||||
md: art.bodyMd,
|
||||
meta: {
|
||||
title: art.title,
|
||||
summary: art.summary,
|
||||
sectionId: art.sectionId,
|
||||
tags: art.tags,
|
||||
equipment: art.equipment,
|
||||
docCode: art.docCode,
|
||||
pinned: art.pinned,
|
||||
visibility: art.visibility,
|
||||
order: art.order,
|
||||
},
|
||||
draft: art.draftMd !== null ? { md: art.draftMd, meta: art.draftMeta, at: art.draftAt?.toISOString() ?? null } : null,
|
||||
attachments: art.attachments.map((a) => ({ id: a.id, filename: a.filename, url: `/uploads/${a.path}`, size: a.size })),
|
||||
});
|
||||
});
|
||||
|
||||
// Новая статья: создаётся черновиком, читатели её не видят до публикации
|
||||
editRouter.post('/articles', async (req, res) => {
|
||||
const input = z.object({ title: meta.shape.title, sectionId: meta.shape.sectionId }).parse(req.body);
|
||||
const section = await prisma.section.findUnique({ where: { id: input.sectionId } });
|
||||
if (!section) throw new HttpError(400, 'Раздел не найден');
|
||||
const slug = await uniqueSlug(slugify(input.title));
|
||||
const last = await prisma.article.aggregate({ where: { sectionId: section.id }, _max: { order: true } });
|
||||
const art = await prisma.article.create({
|
||||
data: {
|
||||
slug,
|
||||
title: input.title,
|
||||
sectionId: section.id,
|
||||
bodyMd: '',
|
||||
bodyHtml: '',
|
||||
status: 'DRAFT',
|
||||
order: (last._max.order ?? 0) + 1,
|
||||
authorId: req.user!.id,
|
||||
},
|
||||
});
|
||||
res.status(201).json({ id: art.id, slug: art.slug });
|
||||
});
|
||||
|
||||
// Автосохранение и кнопка «Черновик»: пишем в отдельные поля, опубликованный текст не трогаем
|
||||
editRouter.put('/articles/:id/draft', async (req, res) => {
|
||||
const input = body.parse(req.body);
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const draftAt = new Date();
|
||||
await prisma.article.update({
|
||||
where: { id: art.id },
|
||||
data: { draftMd: input.md, draftMeta: input.meta as unknown as Prisma.InputJsonValue, draftAt },
|
||||
});
|
||||
res.json({ at: draftAt.toISOString() });
|
||||
});
|
||||
|
||||
editRouter.delete('/articles/:id/draft', async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.update({ where: { id: art.id }, data: { draftMd: null, draftMeta: Prisma.JsonNull, draftAt: null } }); // Prisma.JsonNull: так в JSON-поле пишется NULL
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// Публикация: новая версия, запись в историю, пересчёт HTML и поискового индекса
|
||||
editRouter.post('/articles/:id/publish', async (req, res) => {
|
||||
const input = body.extend({ comment: z.string().trim().max(200).optional() }).parse(req.body);
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const section = await prisma.section.findUnique({ where: { id: input.meta.sectionId } });
|
||||
if (!section) throw new HttpError(400, 'Раздел не найден');
|
||||
if (!input.md.trim()) throw new HttpError(400, 'Нельзя опубликовать пустую статью');
|
||||
|
||||
const md = input.md.replace(/\r\n?/g, '\n').trim() + '\n';
|
||||
const first = art.status === 'DRAFT' && art.version === 1 && !art.bodyMd;
|
||||
const changed = md !== art.bodyMd || input.meta.title !== art.title;
|
||||
const version = first ? 1 : changed ? art.version + 1 : art.version;
|
||||
const titleChanged = input.meta.title !== art.title;
|
||||
|
||||
await prisma.$transaction(async (tx) => {
|
||||
// Закреплённой (шпаргалкой) может быть только одна статья
|
||||
if (input.meta.pinned) await tx.article.updateMany({ where: { pinned: true, id: { not: art.id } }, data: { pinned: false } });
|
||||
await tx.article.update({
|
||||
where: { id: art.id },
|
||||
data: {
|
||||
...input.meta,
|
||||
bodyMd: md,
|
||||
version,
|
||||
status: 'PUBLISHED',
|
||||
updatedAt: new Date(),
|
||||
draftMd: null,
|
||||
draftMeta: Prisma.JsonNull,
|
||||
draftAt: null,
|
||||
},
|
||||
});
|
||||
if (first || changed) {
|
||||
await tx.articleRevision.upsert({
|
||||
where: { articleId_version: { articleId: art.id, version } },
|
||||
create: { articleId: art.id, version, title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment },
|
||||
update: { title: input.meta.title, bodyMd: md, authorId: req.user!.id, comment: input.comment, createdAt: new Date() },
|
||||
});
|
||||
}
|
||||
const render = await renderArticle(md, tx);
|
||||
await tx.article.update({
|
||||
where: { id: art.id },
|
||||
data: { bodyHtml: render.html, facts: deriveFacts(md, input.meta.pinned, render) as unknown as Prisma.InputJsonValue },
|
||||
});
|
||||
await updateSearchIndex(art.id, { ...input.meta, render }, tx);
|
||||
await linkAssets(art.id, render, tx);
|
||||
});
|
||||
|
||||
// Новая статья или новое название: в других статьях [[ссылки]] на неё должны показать актуальное название
|
||||
if (first || titleChanged) await rerenderAll();
|
||||
|
||||
res.json({ slug: art.slug, version, at: new Date().toISOString() });
|
||||
});
|
||||
|
||||
editRouter.post('/articles/:id/unpublish', async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.update({ where: { id: art.id }, data: { status: 'DRAFT' } });
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
editRouter.delete('/articles/:id', requireRole('ADMIN'), async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
await prisma.article.delete({ where: { id: art.id } });
|
||||
await rerenderAll();
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
// ---------- История версий ----------
|
||||
editRouter.get('/articles/:id/revisions', async (req, res) => {
|
||||
const rows = await prisma.articleRevision.findMany({
|
||||
where: { articleId: String(req.params.id) },
|
||||
orderBy: { version: 'desc' },
|
||||
include: { author: { select: { name: true } } },
|
||||
});
|
||||
const list: RevisionDto[] = rows.map((r) => ({
|
||||
id: r.id,
|
||||
version: r.version,
|
||||
createdAt: r.createdAt.toISOString(),
|
||||
authorName: r.author?.name ?? null,
|
||||
comment: r.comment,
|
||||
}));
|
||||
res.json(list);
|
||||
});
|
||||
|
||||
editRouter.get('/articles/:id/revisions/:version', async (req, res) => {
|
||||
const rev = await prisma.articleRevision.findUnique({
|
||||
where: { articleId_version: { articleId: String(req.params.id), version: Number(req.params.version) || 0 } },
|
||||
});
|
||||
if (!rev) throw new HttpError(404, 'Версия не найдена');
|
||||
res.json({ version: rev.version, title: rev.title, md: rev.bodyMd });
|
||||
});
|
||||
|
||||
// ---------- Загрузка картинок ----------
|
||||
const IMAGE_FORMATS = new Set(['jpeg', 'png', 'webp', 'gif', 'heif', 'tiff']);
|
||||
|
||||
editRouter.post('/images', uploadImage, async (req, res) => {
|
||||
const file = req.file;
|
||||
if (!file) throw new HttpError(400, 'Файл не получен');
|
||||
// Тип определяем по содержимому, а не по имени или заголовку: sharp читает сам файл
|
||||
let format: string | undefined;
|
||||
try {
|
||||
format = (await sharp(file.buffer).metadata()).format;
|
||||
} catch {
|
||||
format = undefined;
|
||||
}
|
||||
if (!format || !IMAGE_FORMATS.has(format)) throw new HttpError(400, 'Это не картинка (нужен JPG, PNG, WebP или HEIC)');
|
||||
|
||||
const now = new Date();
|
||||
const key = `${now.getFullYear()}/${String(now.getMonth() + 1).padStart(2, '0')}/${nanoid(12)}`;
|
||||
const img = await storeImage(file.buffer, key);
|
||||
const articleId = typeof req.body?.articleId === 'string' && req.body.articleId ? req.body.articleId : null;
|
||||
await prisma.asset.create({
|
||||
data: { path: img.path, mime: 'image/webp', size: img.size, width: img.width, height: img.height, uploadedById: req.user!.id, articleId },
|
||||
});
|
||||
res.status(201).json({ url: `/uploads/${img.path}`, width: img.width, height: img.height });
|
||||
});
|
||||
|
||||
// ---------- Исходники (PDF, DOCX…) ----------
|
||||
// Расширение → с каких байтов должен начинаться файл
|
||||
const DOC_SIGNATURES: Record<string, number[][]> = {
|
||||
pdf: [[0x25, 0x50, 0x44, 0x46]], // %PDF
|
||||
docx: [[0x50, 0x4b, 0x03, 0x04]], // ZIP
|
||||
xlsx: [[0x50, 0x4b, 0x03, 0x04]],
|
||||
doc: [[0xd0, 0xcf, 0x11, 0xe0]], // старый формат Office
|
||||
xls: [[0xd0, 0xcf, 0x11, 0xe0]],
|
||||
dwg: [[0x41, 0x43, 0x31, 0x30]], // AC10
|
||||
};
|
||||
|
||||
editRouter.post('/articles/:id/attachments', uploadDoc, async (req, res) => {
|
||||
const art = await getArticle(String(req.params.id));
|
||||
const file = req.file;
|
||||
if (!file) throw new HttpError(400, 'Файл не получен');
|
||||
// multer отдаёт имя в latin1: возвращаем нормальный UTF-8
|
||||
const original = Buffer.from(file.originalname, 'latin1').toString('utf8');
|
||||
const ext = path.extname(original).slice(1).toLowerCase();
|
||||
const signatures = DOC_SIGNATURES[ext];
|
||||
if (!signatures) throw new HttpError(400, 'Можно прикрепить PDF, DOC, DOCX, XLS, XLSX или DWG');
|
||||
if (!signatures.some((sig) => sig.every((b, i) => file.buffer[i] === b))) {
|
||||
throw new HttpError(400, 'Содержимое файла не соответствует расширению');
|
||||
}
|
||||
|
||||
const base = slugify(path.basename(original, path.extname(original))).replace(/-/g, '_') || 'file';
|
||||
const rel = `originals/${art.id}/${base}.${ext}`;
|
||||
const abs = uploadPath(rel);
|
||||
await fs.mkdir(path.dirname(abs), { recursive: true });
|
||||
await fs.writeFile(abs, file.buffer);
|
||||
const data = { filename: `${base}.${ext}`, size: file.size };
|
||||
const att = await prisma.attachment.upsert({
|
||||
where: { articleId_path: { articleId: art.id, path: rel } },
|
||||
create: { articleId: art.id, path: rel, ...data },
|
||||
update: data,
|
||||
});
|
||||
res.status(201).json({ id: att.id, filename: att.filename, url: `/uploads/${att.path}`, size: att.size });
|
||||
});
|
||||
|
||||
editRouter.delete('/attachments/:id', async (req, res) => {
|
||||
const att = await prisma.attachment.findUnique({ where: { id: String(req.params.id) } });
|
||||
if (!att) throw new HttpError(404, 'Файл не найден');
|
||||
await prisma.attachment.delete({ where: { id: att.id } });
|
||||
// Файл стартового импорта может быть общим для нескольких статей: удаляем с диска, только если больше не нужен
|
||||
if (!(await prisma.attachment.count({ where: { path: att.path } }))) {
|
||||
await fs.rm(uploadPath(att.path), { force: true });
|
||||
}
|
||||
res.status(204).end();
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// Личные данные пользователя: избранное и недавно открытые.
|
||||
// На устройстве они хранятся локально (работают без сети), а здесь синхронизируются между устройствами.
|
||||
import { Router } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { requireAuth } from '../auth.js';
|
||||
import { prisma } from '../db.js';
|
||||
|
||||
export const meRouter = Router();
|
||||
meRouter.use(requireAuth);
|
||||
|
||||
meRouter.get('/state', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const [favs, recent] = await Promise.all([
|
||||
prisma.favorite.findMany({ where: { userId }, orderBy: { createdAt: 'desc' }, include: { article: { select: { slug: true } } } }),
|
||||
prisma.recentView.findMany({ where: { userId }, orderBy: { viewedAt: 'desc' }, take: 12, include: { article: { select: { slug: true } } } }),
|
||||
]);
|
||||
res.json({
|
||||
favorites: favs.map((f) => f.article.slug),
|
||||
recent: recent.map((r) => ({ slug: r.article.slug, at: r.viewedAt.getTime() })),
|
||||
});
|
||||
});
|
||||
|
||||
const slugs = z.object({ slugs: z.array(z.string().max(200)).max(500) });
|
||||
|
||||
// Клиент присылает полный список избранного: сервер приводит своё к нему
|
||||
meRouter.put('/favorites', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const body = slugs.parse(req.body);
|
||||
const articles = await prisma.article.findMany({ where: { slug: { in: body.slugs } }, select: { id: true } });
|
||||
const ids = articles.map((a) => a.id);
|
||||
await prisma.$transaction([
|
||||
prisma.favorite.deleteMany({ where: { userId, articleId: { notIn: ids } } }),
|
||||
prisma.favorite.createMany({ data: ids.map((articleId) => ({ userId, articleId })), skipDuplicates: true }),
|
||||
]);
|
||||
res.status(204).end();
|
||||
});
|
||||
|
||||
meRouter.post('/recent', async (req, res) => {
|
||||
const userId = req.user!.id;
|
||||
const { slug } = z.object({ slug: z.string().max(200) }).parse(req.body);
|
||||
const article = await prisma.article.findUnique({ where: { slug }, select: { id: true } });
|
||||
if (article) {
|
||||
await prisma.recentView.upsert({
|
||||
where: { userId_articleId: { userId, articleId: article.id } },
|
||||
create: { userId, articleId: article.id },
|
||||
update: { viewedAt: new Date() },
|
||||
});
|
||||
}
|
||||
res.status(204).end();
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { assetKey, renderMarkdown, type RenderResult } from '@kb/md';
|
||||
import { assetKey, parseCheatSheet, renderMarkdown, type RenderResult } from '@kb/md';
|
||||
import { compactSearch, normalizeSearch } from '@kb/shared';
|
||||
import { prisma } from '../db.js';
|
||||
|
||||
@@ -32,6 +32,26 @@ export async function renderArticle(md: string, db: Db = prisma): Promise<Render
|
||||
});
|
||||
}
|
||||
|
||||
/** Факт в поле 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;
|
||||
@@ -89,7 +109,10 @@ export async function rerenderAll(db: Db = prisma): Promise<{ slug: string; brok
|
||||
});
|
||||
await db.article.update({
|
||||
where: { id: art.id },
|
||||
data: { bodyHtml: render.html, facts: render.facts as unknown as Prisma.InputJsonValue },
|
||||
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);
|
||||
|
||||
@@ -8,6 +8,11 @@ server {
|
||||
# Загрузка картинок до 15 МБ и документов до 30 МБ (с запасом)
|
||||
client_max_body_size 32m;
|
||||
|
||||
# Заголовки безопасности для страниц сайта.
|
||||
# CSP: скрипты, шрифты и запросы только со своего домена; картинки ещё из data: и blob: (предпросмотр, QR).
|
||||
# style-src 'unsafe-inline' нужен редактору CodeMirror и атрибутам style, которые ставит React.
|
||||
set $csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript image/svg+xml application/manifest+json;
|
||||
gzip_min_length 512;
|
||||
@@ -31,6 +36,11 @@ server {
|
||||
# Файлы с хешем в имени можно кешировать навсегда
|
||||
location /assets/ {
|
||||
add_header Cache-Control "public, max-age=31536000, immutable";
|
||||
add_header Content-Security-Policy $csp always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
@@ -43,6 +53,11 @@ server {
|
||||
# SPA: остальные адреса отдают index.html, маршруты разбирает React Router
|
||||
location / {
|
||||
add_header Cache-Control "no-cache";
|
||||
add_header Content-Security-Policy $csp always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,17 @@
|
||||
"typecheck": "tsc -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/autocomplete": "^6.20.3",
|
||||
"@codemirror/lang-markdown": "^6.5.2",
|
||||
"@codemirror/language": "^6.12.4",
|
||||
"@codemirror/state": "^6.7.6",
|
||||
"@codemirror/view": "^6.43.13",
|
||||
"@fontsource-variable/onest": "^5.3.1",
|
||||
"@kb/md": "workspace:^",
|
||||
"@kb/shared": "workspace:^",
|
||||
"@lezer/highlight": "^1.2.5",
|
||||
"@tanstack/react-query": "^5.104.1",
|
||||
"codemirror": "^6.0.2",
|
||||
"qrcode-generator": "^2.0.4",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 2.7 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 14 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.3 KiB |
+57
-11
@@ -1,17 +1,25 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { lazy, Suspense, useEffect } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Screen } from './components/Shell';
|
||||
import { BackLink, Notice } from './components/ui';
|
||||
import { pushFavorites, useAuth } from './lib/auth';
|
||||
import { useFavorites } from './lib/store';
|
||||
import { useTheme } from './lib/theme';
|
||||
import { ArticlePage } from './pages/Article';
|
||||
import { CheatSheetPage } from './pages/CheatSheet';
|
||||
import { FavoritesPage } from './pages/Favorites';
|
||||
import { HomePage } from './pages/Home';
|
||||
import { InvitePage, LoginPage } from './pages/Login';
|
||||
import { OfflinePage } from './pages/OfflinePage';
|
||||
import { SearchPage } from './pages/Search';
|
||||
import { SectionPage } from './pages/Section';
|
||||
|
||||
// Редко нужные экраны грузятся отдельными файлами, чтобы не замедлять чтение статей
|
||||
const PrintPage = lazy(() => import('./pages/Print'));
|
||||
const EditorPage = lazy(() => import('./pages/Editor'));
|
||||
const NewArticlePage = lazy(() => import('./pages/NewArticle'));
|
||||
const AdminPage = lazy(() => import('./pages/Admin'));
|
||||
|
||||
function NotFound() {
|
||||
return (
|
||||
@@ -27,19 +35,57 @@ function NotFound() {
|
||||
export function App() {
|
||||
// Тема применяется один раз здесь: вешает data-theme на <html>
|
||||
useTheme();
|
||||
const { user, loading } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
const { favs } = useFavorites();
|
||||
|
||||
// Любой запрос ответил 401 (сессия кончилась): перепроверяем, кто вошёл
|
||||
useEffect(() => {
|
||||
const onUnauthorized = () => void qc.invalidateQueries({ queryKey: ['me'] });
|
||||
window.addEventListener('kb:unauthorized', onUnauthorized);
|
||||
return () => window.removeEventListener('kb:unauthorized', onUnauthorized);
|
||||
}, [qc]);
|
||||
|
||||
// Избранное живёт на устройстве; у вошедшего пользователя копия уходит на сервер
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
const id = setTimeout(() => void pushFavorites(favs), 800);
|
||||
return () => clearTimeout(id);
|
||||
}, [favs, user]);
|
||||
|
||||
if (loading) return <div className="splash" aria-busy="true" />;
|
||||
|
||||
// Без входа доступны только экран входа, приглашение и публичные статьи
|
||||
if (!user) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<LoginPage />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
<Routes>
|
||||
<Route path="/" element={<HomePage />} />
|
||||
<Route path="/search" element={<SearchPage />} />
|
||||
<Route path="/cheatsheet" element={<CheatSheetPage />} />
|
||||
<Route path="/favorites" element={<FavoritesPage />} />
|
||||
<Route path="/offline" element={<OfflinePage />} />
|
||||
<Route path="/s/:slug" element={<SectionPage />} />
|
||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||
<Route path="/print/:slug" element={<PrintPage />} />
|
||||
<Route path="/invite/:token" element={<InvitePage />} />
|
||||
<Route path="/edit/:slug" element={<EditorPage />} />
|
||||
<Route path="/new" element={<NewArticlePage />} />
|
||||
<Route path="/admin" element={<AdminPage />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
// Поле ввода Markdown на CodeMirror 6: подсветка, автодополнение [[ссылок]], вставка картинок.
|
||||
import { forwardRef, useEffect, useImperativeHandle, useRef } from 'react';
|
||||
import { autocompletion, type CompletionContext, type CompletionResult } from '@codemirror/autocomplete';
|
||||
import { markdown } from '@codemirror/lang-markdown';
|
||||
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
|
||||
import { EditorState } from '@codemirror/state';
|
||||
import { EditorView, placeholder } from '@codemirror/view';
|
||||
import { tags } from '@lezer/highlight';
|
||||
import { minimalSetup } from 'codemirror';
|
||||
|
||||
export interface MdEditorHandle {
|
||||
/** Вставить текст на место курсора. */
|
||||
insert: (text: string) => void;
|
||||
focus: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
/** Статьи для автодополнения после «[[». */
|
||||
links: { slug: string; title: string }[];
|
||||
/** Пользователь вставил или перетащил файлы-картинки. */
|
||||
onImages: (files: File[]) => void;
|
||||
}
|
||||
|
||||
// Цвета берём из токенов темы, поэтому редактор сам перекрашивается при смене темы
|
||||
const theme = EditorView.theme({
|
||||
'&': { height: '100%', fontSize: 'var(--fs-15)', color: 'var(--ink)', backgroundColor: 'var(--sf)' },
|
||||
'.cm-scroller': { fontFamily: 'var(--font)', lineHeight: '1.65', overflow: 'auto' },
|
||||
'.cm-content': { padding: 'var(--sp-8) var(--sp-10)', caretColor: 'var(--ink)' },
|
||||
'&.cm-focused': { outline: 'none' },
|
||||
'.cm-cursor': { borderLeftColor: 'var(--ink)' },
|
||||
'.cm-selectionBackground, &.cm-focused .cm-selectionBackground': { backgroundColor: 'var(--sf2) !important' },
|
||||
'.cm-placeholder': { color: 'var(--ink2)' },
|
||||
'.cm-tooltip': { border: 'var(--bw) solid var(--ln)', borderRadius: 'var(--r-md)', backgroundColor: 'var(--sf)', color: 'var(--ink)', overflow: 'hidden' },
|
||||
'.cm-tooltip-autocomplete ul li': { padding: 'var(--sp-4) var(--sp-6) !important', fontFamily: 'var(--font)' },
|
||||
'.cm-tooltip-autocomplete ul li[aria-selected]': { backgroundColor: 'var(--ink)', color: 'var(--bg)' },
|
||||
'.cm-completionDetail': { marginLeft: 'var(--sp-4)', opacity: '0.7', fontStyle: 'normal' },
|
||||
});
|
||||
|
||||
const highlight = HighlightStyle.define([
|
||||
{ tag: tags.heading, fontWeight: '700', color: 'var(--acc)' },
|
||||
{ tag: tags.strong, fontWeight: '700', color: 'var(--acc)' },
|
||||
{ tag: tags.emphasis, fontStyle: 'italic' },
|
||||
{ tag: [tags.link, tags.url], color: 'var(--blu)' },
|
||||
{ tag: [tags.processingInstruction, tags.meta, tags.punctuation], color: 'var(--ink2)' },
|
||||
]);
|
||||
|
||||
export const MdEditor = forwardRef<MdEditorHandle, Props>(function MdEditor({ value, onChange, links, onImages }, ref) {
|
||||
const host = useRef<HTMLDivElement>(null);
|
||||
const view = useRef<EditorView | null>(null);
|
||||
// Свежие значения пропсов для обработчиков CodeMirror (он создаётся один раз)
|
||||
const latest = useRef({ onChange, links, onImages });
|
||||
useEffect(() => {
|
||||
latest.current = { onChange, links, onImages };
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Автодополнение: после «[[» показываем статьи, поиск по названию и по slug
|
||||
const wikiComplete = (ctx: CompletionContext): CompletionResult | null => {
|
||||
const m = ctx.matchBefore(/\[\[[^\]\n]*$/);
|
||||
if (!m) return null;
|
||||
const typed = m.text.slice(2).toLowerCase();
|
||||
return {
|
||||
from: m.from + 2,
|
||||
filter: false,
|
||||
options: latest.current.links
|
||||
.filter((l) => l.slug.includes(typed) || l.title.toLowerCase().includes(typed))
|
||||
.slice(0, 30)
|
||||
.map((l) => ({ label: l.title, detail: l.slug, apply: `${l.slug}]]` })),
|
||||
};
|
||||
};
|
||||
|
||||
const images = (list: FileList | null | undefined) => [...(list ?? [])].filter((f) => f.type.startsWith('image/'));
|
||||
|
||||
const v = new EditorView({
|
||||
parent: host.current!,
|
||||
state: EditorState.create({
|
||||
doc: value,
|
||||
extensions: [
|
||||
minimalSetup,
|
||||
markdown(),
|
||||
syntaxHighlighting(highlight),
|
||||
EditorView.lineWrapping,
|
||||
autocompletion({ override: [wikiComplete], icons: false }),
|
||||
placeholder('Текст статьи в Markdown. Блоки вставляются кнопками сверху.'),
|
||||
theme,
|
||||
EditorView.contentAttributes.of({ spellcheck: 'false', 'aria-label': 'Текст статьи (Markdown)' }),
|
||||
EditorView.updateListener.of((u) => {
|
||||
if (u.docChanged) latest.current.onChange(u.state.doc.toString());
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
paste(e) {
|
||||
const files = images(e.clipboardData?.files);
|
||||
if (!files.length) return false;
|
||||
e.preventDefault();
|
||||
latest.current.onImages(files);
|
||||
return true;
|
||||
},
|
||||
drop(e) {
|
||||
const files = images(e.dataTransfer?.files);
|
||||
if (!files.length) return false;
|
||||
e.preventDefault();
|
||||
latest.current.onImages(files);
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
],
|
||||
}),
|
||||
});
|
||||
view.current = v;
|
||||
return () => v.destroy();
|
||||
// Редактор создаётся один раз; внешние изменения value подхватывает эффект ниже
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Текст поменяли снаружи (загрузили статью, вернули старую версию): заменяем содержимое
|
||||
useEffect(() => {
|
||||
const v = view.current;
|
||||
if (v && v.state.doc.toString() !== value) {
|
||||
v.dispatch({ changes: { from: 0, to: v.state.doc.length, insert: value } });
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
insert(text) {
|
||||
const v = view.current;
|
||||
if (!v) return;
|
||||
const { from, to } = v.state.selection.main;
|
||||
v.dispatch({ changes: { from, to, insert: text }, selection: { anchor: from + text.length }, scrollIntoView: true });
|
||||
v.focus();
|
||||
},
|
||||
focus: () => view.current?.focus(),
|
||||
}));
|
||||
|
||||
return <div ref={host} className="cm-host" />;
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -2,9 +2,12 @@
|
||||
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 { setStored } from '../lib/store';
|
||||
import { articleHref, SPACE_KEY, useNav } from '../lib/tree';
|
||||
import { IconDoc, IconHome, IconSearch, IconStar } from './Icons';
|
||||
import { OfflineBanner } from './Offline';
|
||||
import { CodeTag } from './ui';
|
||||
import { UserMenu } from './UserMenu';
|
||||
|
||||
export type Tab = 'home' | 'search' | 'cheat' | 'fav';
|
||||
|
||||
@@ -33,7 +36,32 @@ export function TabBar({ active }: { active: Tab }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
/** Переключатель пространства. Если пространство одно, это просто подпись. */
|
||||
export function SpacePicker() {
|
||||
const nav = useNav();
|
||||
if (!nav.space) return null;
|
||||
return (
|
||||
<label 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>
|
||||
{nav.spaces.length > 1 ? (
|
||||
<select className="space-pick-select" value={nav.space.id} onChange={(e) => setStored(SPACE_KEY, e.target.value)}>
|
||||
{nav.spaces.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<span className="space-pick-name">{nav.space.name}</span>
|
||||
)}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function Sidebar() {
|
||||
const nav = useNav();
|
||||
const { theme, setTheme } = useTheme();
|
||||
const { pathname } = useLocation();
|
||||
@@ -45,15 +73,7 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
<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}
|
||||
<SpacePicker />
|
||||
|
||||
<nav className="tree" aria-label="Статьи">
|
||||
<NavLink to="/search" className="tree-link tree-link--top">
|
||||
@@ -67,6 +87,9 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
<NavLink to="/favorites" className="tree-link tree-link--top">
|
||||
Избранное
|
||||
</NavLink>
|
||||
<NavLink to="/offline" className="tree-link tree-link--top">
|
||||
Офлайн-разделы
|
||||
</NavLink>
|
||||
{nav.sections.map((s) => (
|
||||
<div key={s.id} className="tree-group">
|
||||
<Link to={`/s/${s.slug}`} className="tree-head">
|
||||
@@ -88,7 +111,7 @@ export function Sidebar({ footer }: { footer?: ReactNode }) {
|
||||
</nav>
|
||||
|
||||
<div className="sidebar-foot">
|
||||
{footer}
|
||||
<UserMenu compact />
|
||||
<div className="sidebar-foot-label">Тема</div>
|
||||
<div className="segmented segmented--3" role="group" aria-label="Тема">
|
||||
{THEME_ORDER.map((t) => (
|
||||
@@ -127,6 +150,7 @@ export function Screen({
|
||||
<div className="shell">
|
||||
<Sidebar />
|
||||
<div className="shell-main">
|
||||
<OfflineBanner />
|
||||
<main className={wide ? 'screen screen--wide' : 'screen'}>{children}</main>
|
||||
</div>
|
||||
{bar ?? (tab ? <TabBar active={tab} /> : null)}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
// Блок «кто вошёл»: имя, роль, ссылки на управление и выход.
|
||||
// В макете его нет: добавлен в стиле списков, иначе негде выйти и открыть админку.
|
||||
import { Link } from 'react-router-dom';
|
||||
import { ROLE_LABEL } from '@kb/shared';
|
||||
import { useAuth, useAuthActions } from '../lib/auth';
|
||||
|
||||
export function UserMenu({ compact }: { compact?: boolean }) {
|
||||
const { user, isEditor, isAdmin } = useAuth();
|
||||
const { logout } = useAuthActions();
|
||||
if (!user) return null;
|
||||
|
||||
return (
|
||||
<div className={compact ? 'usermenu usermenu--compact' : 'usermenu list'}>
|
||||
<div className="usermenu-who list-row">
|
||||
<span className="avatar" aria-hidden="true">
|
||||
{user.name
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]?.toUpperCase())
|
||||
.join('')}
|
||||
</span>
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">{user.name}</span>
|
||||
<span className="list-row-sub">{ROLE_LABEL[user.role]}</span>
|
||||
</span>
|
||||
</div>
|
||||
{isEditor ? (
|
||||
<Link to="/new" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Новая статья</span>
|
||||
</Link>
|
||||
) : null}
|
||||
{isAdmin ? (
|
||||
<Link to="/admin" className="list-row usermenu-link">
|
||||
<span className="list-row-main list-row-title">Управление</span>
|
||||
</Link>
|
||||
) : null}
|
||||
<button type="button" className="list-row usermenu-link usermenu-btn" onClick={() => void logout()}>
|
||||
<span className="list-row-main list-row-title">Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+11
-2
@@ -1,5 +1,6 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import type { ArticleDto, TreeResponse } from '@kb/shared';
|
||||
import { markSynced } from './offline';
|
||||
|
||||
/** Ошибка ответа API: status нужен, чтобы отличать 401 (надо войти) от 404 и от «нет сети». */
|
||||
export class ApiError extends Error {
|
||||
@@ -31,13 +32,21 @@ export async function api<T>(path: string, init?: RequestInit & { json?: unknown
|
||||
if (res.status === 204) return undefined as T;
|
||||
const data = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
// 401 на обычном запросе = сессия кончилась. Сам запрос «кто я» не считаем, иначе получится замкнутый круг.
|
||||
if (res.status === 401 && !path.startsWith('/auth/')) window.dispatchEvent(new Event('kb:unauthorized'));
|
||||
throw new ApiError(res.status, (data as { error?: string } | null)?.error ?? `Ошибка ${res.status}`);
|
||||
}
|
||||
return data as T;
|
||||
}
|
||||
|
||||
export const treeQuery = { queryKey: ['tree'] as const, queryFn: () => api<TreeResponse>('/tree') };
|
||||
export const treeQuery = {
|
||||
queryKey: ['tree'] as const,
|
||||
queryFn: async () => {
|
||||
const tree = await api<TreeResponse>('/tree');
|
||||
markSynced();
|
||||
return tree;
|
||||
},
|
||||
};
|
||||
|
||||
export const articleQuery = (slug: string) => ({
|
||||
queryKey: ['article', slug] as const,
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// Кто вошёл. Сервер хранит сессию в httpOnly-cookie, здесь только узнаём пользователя.
|
||||
import { useEffect } from 'react';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import type { Role, UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from './api';
|
||||
import { clearPrivateCaches } from './offline';
|
||||
import { getStored, type RecentItem, setStored, useStored } from './store';
|
||||
|
||||
const USER_KEY = 'kb-user';
|
||||
|
||||
/**
|
||||
* Состояние входа:
|
||||
* loading: ещё спрашиваем сервер;
|
||||
* user: вошёл (или нет сети, но на этом устройстве уже входили: тогда читаем сохранённое);
|
||||
* null: не вошёл.
|
||||
*/
|
||||
export function useAuth() {
|
||||
const [cached, setCached] = useStored<UserDto | null>(USER_KEY, null);
|
||||
const q = useQuery({
|
||||
queryKey: ['me'],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/me');
|
||||
return user;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) return null;
|
||||
throw e; // нет сети: оставляем сохранённого пользователя
|
||||
}
|
||||
},
|
||||
staleTime: 5 * 60_000,
|
||||
retry: false,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (q.data === undefined) return;
|
||||
if (q.data === null && cached) {
|
||||
// Сессия кончилась: убираем с устройства сохранённые закрытые статьи
|
||||
setCached(null);
|
||||
void clearPrivateCaches();
|
||||
} else if (q.data && JSON.stringify(q.data) !== JSON.stringify(cached)) {
|
||||
setCached(q.data);
|
||||
}
|
||||
}, [q.data, cached, setCached]);
|
||||
|
||||
// Если на устройстве уже входили, не ждём ответа сервера: сразу показываем приложение
|
||||
// (так оно открывается мгновенно и работает без сети). Сервер ответит 401: покажем экран входа.
|
||||
const user = q.data !== undefined ? q.data : (cached ?? (q.isError ? null : undefined));
|
||||
return {
|
||||
user: user ?? null,
|
||||
loading: user === undefined,
|
||||
isEditor: user?.role === 'EDITOR' || user?.role === 'ADMIN',
|
||||
isAdmin: user?.role === 'ADMIN',
|
||||
};
|
||||
}
|
||||
|
||||
export const roleAtLeast = (role: Role | undefined, min: Role) =>
|
||||
!!role && ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(role) >= ['VIEWER', 'EDITOR', 'ADMIN'].indexOf(min);
|
||||
|
||||
export function useAuthActions() {
|
||||
const qc = useQueryClient();
|
||||
return {
|
||||
/** После входа: запоминаем пользователя и перезапрашиваем всё (теперь видны закрытые статьи). */
|
||||
async onLogin(user: UserDto) {
|
||||
setStored(USER_KEY, user);
|
||||
qc.setQueryData(['me'], user);
|
||||
await syncPersonal();
|
||||
await qc.invalidateQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
async logout() {
|
||||
await api('/auth/logout', { method: 'POST' }).catch(() => undefined);
|
||||
setStored(USER_KEY, null);
|
||||
await clearPrivateCaches();
|
||||
qc.setQueryData(['me'], null);
|
||||
qc.removeQueries({ predicate: (query) => query.queryKey[0] !== 'me' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------- Синхронизация избранного и недавних между устройствами ----------
|
||||
interface PersonalState {
|
||||
favorites: string[];
|
||||
recent: RecentItem[];
|
||||
}
|
||||
|
||||
/** Объединяет локальные данные с серверными (ничего не теряя) и отправляет результат на сервер. */
|
||||
export async function syncPersonal() {
|
||||
try {
|
||||
const remote = await api<PersonalState>('/me/state');
|
||||
const favs = [...new Set([...getStored<string[]>('kb-fav', []), ...remote.favorites])];
|
||||
setStored('kb-fav', favs);
|
||||
const recent = new Map<string, number>();
|
||||
for (const r of [...remote.recent, ...getStored<RecentItem[]>('kb-recent', [])]) {
|
||||
recent.set(r.slug, Math.max(recent.get(r.slug) ?? 0, r.at));
|
||||
}
|
||||
setStored(
|
||||
'kb-recent',
|
||||
[...recent].map(([slug, at]) => ({ slug, at })).sort((a, b) => b.at - a.at).slice(0, 12),
|
||||
);
|
||||
await pushFavorites(favs);
|
||||
} catch {
|
||||
// нет сети: синхронизируемся в следующий раз
|
||||
}
|
||||
}
|
||||
|
||||
export const pushFavorites = (slugs: string[]) =>
|
||||
api('/me/favorites', { method: 'PUT', json: { slugs } }).catch(() => undefined);
|
||||
|
||||
export const pushRecentView = (slug: string) =>
|
||||
api('/me/recent', { method: 'POST', json: { slug } }).catch(() => undefined);
|
||||
@@ -0,0 +1,57 @@
|
||||
// Построчное сравнение двух текстов для «Истории версий».
|
||||
// Алгоритм: наибольшая общая подпоследовательность строк (LCS), классическая таблица.
|
||||
|
||||
export interface DiffLine {
|
||||
type: 'same' | 'add' | 'del' | 'skip';
|
||||
text: string;
|
||||
}
|
||||
|
||||
export function diffLines(before: string, after: string): DiffLine[] {
|
||||
const a = before.split('\n');
|
||||
const b = after.split('\n');
|
||||
// lcs[i][j] = длина общей части для a[i..] и b[j..]
|
||||
const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
|
||||
for (let i = a.length - 1; i >= 0; i--) {
|
||||
for (let j = b.length - 1; j >= 0; j--) {
|
||||
lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
|
||||
}
|
||||
}
|
||||
|
||||
const out: DiffLine[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < a.length && j < b.length) {
|
||||
if (a[i] === b[j]) {
|
||||
out.push({ type: 'same', text: a[i]! });
|
||||
i++;
|
||||
j++;
|
||||
} else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) {
|
||||
out.push({ type: 'del', text: a[i++]! });
|
||||
} else {
|
||||
out.push({ type: 'add', text: b[j++]! });
|
||||
}
|
||||
}
|
||||
while (i < a.length) out.push({ type: 'del', text: a[i++]! });
|
||||
while (j < b.length) out.push({ type: 'add', text: b[j++]! });
|
||||
return collapse(out);
|
||||
}
|
||||
|
||||
/** Длинные одинаковые участки сворачиваем: оставляем по 2 строки вокруг изменений. */
|
||||
function collapse(lines: DiffLine[]): DiffLine[] {
|
||||
const keep = new Array<boolean>(lines.length).fill(false);
|
||||
lines.forEach((l, idx) => {
|
||||
if (l.type === 'same') return;
|
||||
for (let k = Math.max(0, idx - 2); k <= Math.min(lines.length - 1, idx + 2); k++) keep[k] = true;
|
||||
});
|
||||
const out: DiffLine[] = [];
|
||||
let skipped = 0;
|
||||
lines.forEach((l, idx) => {
|
||||
if (keep[idx]) {
|
||||
if (skipped) out.push({ type: 'skip', text: `… ${skipped} строк без изменений …` });
|
||||
skipped = 0;
|
||||
out.push(l);
|
||||
} else skipped++;
|
||||
});
|
||||
if (skipped && out.length) out.push({ type: 'skip', text: `… ${skipped} строк без изменений …` });
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
// Офлайн: скачивание разделов в кеш браузера, статус сети, проверка «статья сохранена».
|
||||
//
|
||||
// Кеши ведёт 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);
|
||||
}
|
||||
|
||||
/** Убрать из кеша устаревшие ответы API (после публикации статьи или правок в админке). */
|
||||
export async function dropApiCache(paths: string[]) {
|
||||
if (!cacheSupported()) return;
|
||||
try {
|
||||
const cache = await caches.open(API_CACHE);
|
||||
await Promise.all(paths.map((p) => cache.delete(p)));
|
||||
} catch {
|
||||
// кеш недоступен: не страшно, он обновится сам при следующем открытии
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useMemo } from 'react';
|
||||
import { type ArticleListItem, type SectionDto, shortTitle } from '@kb/shared';
|
||||
import { useTree } from './api';
|
||||
import { useStored } from './store';
|
||||
|
||||
export const SPACE_KEY = 'kb-space';
|
||||
|
||||
export interface SectionView extends SectionDto {
|
||||
/** Статьи раздела без закреплённой шпаргалки. */
|
||||
@@ -10,12 +13,18 @@ export interface SectionView extends SectionDto {
|
||||
/** Дерево в удобном для экранов виде: разделы со статьями, поиск статьи и раздела по slug. */
|
||||
export function useNav() {
|
||||
const { data, isLoading, error } = useTree();
|
||||
// Выбранное пространство запоминается на устройстве
|
||||
const [spaceId] = useStored<string | null>(SPACE_KEY, null);
|
||||
return useMemo(() => {
|
||||
const sections = data?.sections ?? [];
|
||||
const spaces = data?.spaces ?? [];
|
||||
const space = spaces.find((s) => s.id === spaceId) ?? spaces[0] ?? null;
|
||||
const sections = (data?.sections ?? []).filter((s) => !space || s.spaceId === space.id);
|
||||
const articles = data?.articles ?? [];
|
||||
const bySection = new Map<string, SectionDto>(sections.map((s) => [s.id, s]));
|
||||
// Поиск раздела по id идёт по всем пространствам: избранное и поиск показывают статьи отовсюду
|
||||
const allById = new Map<string, SectionDto>((data?.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 inSpace = new Set(sections.map((s) => s.id));
|
||||
const pinned = articles.find((a) => a.pinned && inSpace.has(a.sectionId)) ?? articles.find((a) => a.pinned) ?? null;
|
||||
|
||||
const views: SectionView[] = sections
|
||||
.map((s) => ({ ...s, articles: articles.filter((a) => a.sectionId === s.id && !a.pinned) }))
|
||||
@@ -25,16 +34,19 @@ export function useNav() {
|
||||
return {
|
||||
isLoading,
|
||||
error,
|
||||
space: data?.spaces[0] ?? null,
|
||||
space,
|
||||
spaces,
|
||||
sections: views,
|
||||
/** Все разделы, включая пустые (для редактора и админки). */
|
||||
allSections: sections,
|
||||
articles,
|
||||
pinned,
|
||||
article: (slug: string) => bySlug.get(slug),
|
||||
sectionOf: (a: ArticleListItem | undefined) => (a ? bySection.get(a.sectionId) : undefined),
|
||||
sectionOf: (a: ArticleListItem | undefined) => (a ? allById.get(a.sectionId) : undefined),
|
||||
/** Название для меню и списков: без названия раздела в начале. */
|
||||
short: (a: ArticleListItem) => shortTitle(a.title, bySection.get(a.sectionId)?.name),
|
||||
short: (a: ArticleListItem) => shortTitle(a.title, allById.get(a.sectionId)?.name),
|
||||
};
|
||||
}, [data, isLoading, error]);
|
||||
}, [data, isLoading, error, spaceId]);
|
||||
}
|
||||
|
||||
/** Адрес статьи: закреплённая шпаргалка живёт на своём экране. */
|
||||
|
||||
@@ -7,6 +7,7 @@ import '@fontsource-variable/onest/wght.css';
|
||||
import './styles/tokens.css';
|
||||
import './styles/app.css';
|
||||
import './styles/article.css';
|
||||
import { registerSW } from 'virtual:pwa-register';
|
||||
import { App } from './App';
|
||||
import { ApiError } from './lib/api';
|
||||
|
||||
@@ -24,6 +25,23 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
});
|
||||
|
||||
// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
|
||||
registerSW({ immediate: true });
|
||||
|
||||
// Service worker сначала отдаёт сохранённую версию, а свежую получает в фоне.
|
||||
// Когда она отличается, он пишет в этот канал, и мы перезапрашиваем данные (уже из обновлённого кеша).
|
||||
if ('BroadcastChannel' in window) {
|
||||
new BroadcastChannel('kb-api-updates').onmessage = (e: MessageEvent) => {
|
||||
const url = (e.data as { payload?: { updatedURL?: string } })?.payload?.updatedURL;
|
||||
if (!url) return;
|
||||
const path = new URL(url).pathname;
|
||||
if (path === '/api/tree') void queryClient.invalidateQueries({ queryKey: ['tree'] });
|
||||
else if (path.startsWith('/api/articles/')) {
|
||||
void queryClient.invalidateQueries({ queryKey: ['article', decodeURIComponent(path.slice('/api/articles/'.length))] });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
|
||||
@@ -0,0 +1,485 @@
|
||||
// Админка: пространства и разделы (порядок перетаскиванием), пользователи и роли, приглашения.
|
||||
import { type FormEvent, useRef, useState } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { type AdminUserDto, type InviteDto, PLAQUE_COLORS, type PlaqueColor, plural, ROLE_LABEL, type Role, type SectionDto, type SpaceDto } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { BackLink, Caps, CodeTag, Notice, ThemeButton } from '../components/ui';
|
||||
import { api, ApiError, useTree } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { formatDate, formatRecent } from '../lib/format';
|
||||
import { dropApiCache } from '../lib/offline';
|
||||
import '../styles/editor.css';
|
||||
import '../styles/admin.css';
|
||||
|
||||
const ROLES: Role[] = ['ADMIN', 'EDITOR', 'VIEWER'];
|
||||
const initials = (name: string) =>
|
||||
name
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((w) => w[0]?.toUpperCase())
|
||||
.join('');
|
||||
|
||||
/** После любой правки структуры: сбросить кеш дерева и перезапросить его. */
|
||||
function useRefreshTree() {
|
||||
const qc = useQueryClient();
|
||||
return async () => {
|
||||
await dropApiCache(['/api/tree']);
|
||||
await qc.invalidateQueries({ queryKey: ['tree'] });
|
||||
};
|
||||
}
|
||||
|
||||
const errText = (e: unknown) => (e instanceof ApiError ? e.message : 'Не получилось. Проверьте связь.');
|
||||
|
||||
export default function AdminPage() {
|
||||
const { isAdmin } = useAuth();
|
||||
const { data: tree } = useTree();
|
||||
const [spaceId, setSpaceId] = useState<string | null>(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
if (!isAdmin) {
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
</div>
|
||||
<Notice title="Недостаточно прав">Этот экран доступен только администраторам.</Notice>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
const spaces = tree?.spaces ?? [];
|
||||
const space = spaces.find((s) => s.id === spaceId) ?? spaces[0];
|
||||
|
||||
return (
|
||||
<Screen tab="home" wide>
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
<ThemeButton />
|
||||
</div>
|
||||
<h1 className="cheat-title">Управление</h1>
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="adm-grid">
|
||||
<div className="adm-col">
|
||||
<Spaces spaces={spaces} active={space} onPick={setSpaceId} onError={setError} counts={tree} />
|
||||
{space ? <Sections key={space.id} space={space} onError={setError} /> : null}
|
||||
</div>
|
||||
<div className="adm-col">
|
||||
<Users onError={setError} />
|
||||
<Invites onError={setError} />
|
||||
</div>
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Пространства ----------
|
||||
function Spaces({
|
||||
spaces,
|
||||
active,
|
||||
onPick,
|
||||
onError,
|
||||
counts,
|
||||
}: {
|
||||
spaces: SpaceDto[];
|
||||
active: SpaceDto | undefined;
|
||||
onPick: (id: string) => void;
|
||||
onError: (e: string) => void;
|
||||
counts: ReturnType<typeof useTree>['data'];
|
||||
}) {
|
||||
const refresh = useRefreshTree();
|
||||
const [form, setForm] = useState<{ id: string | null; name: string; icon: string } | null>(null);
|
||||
|
||||
const save = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
try {
|
||||
const json = { name: form.name, icon: form.icon || null };
|
||||
if (form.id) await api(`/admin/spaces/${form.id}`, { method: 'PATCH', json });
|
||||
else onPick((await api<SpaceDto>('/admin/spaces', { method: 'POST', json })).id);
|
||||
setForm(null);
|
||||
onError('');
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string) => {
|
||||
try {
|
||||
await api(`/admin/spaces/${id}`, { method: 'DELETE' });
|
||||
setForm(null);
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="block">
|
||||
<Caps>Пространства</Caps>
|
||||
<div className="adm-spaces">
|
||||
{spaces.map((s) => {
|
||||
const secs = counts?.sections.filter((x) => x.spaceId === s.id) ?? [];
|
||||
const arts = counts?.articles.filter((a) => secs.some((x) => x.id === a.sectionId)).length ?? 0;
|
||||
return (
|
||||
<div key={s.id} className={s.id === active?.id ? 'adm-space adm-space--on' : 'adm-space'}>
|
||||
<button type="button" className="adm-space-pick" onClick={() => onPick(s.id)} aria-pressed={s.id === active?.id}>
|
||||
<span className="space-icon">{s.icon || s.name[0]}</span>
|
||||
<span className="adm-space-name">{s.name}</span>
|
||||
<span className="adm-space-n">
|
||||
{secs.length} {plural(secs.length, ['раздел', 'раздела', 'разделов'])} · {arts} {plural(arts, ['статья', 'статьи', 'статей'])}
|
||||
</span>
|
||||
</button>
|
||||
<button type="button" className="adm-link" onClick={() => setForm({ id: s.id, name: s.name, icon: s.icon ?? '' })}>
|
||||
Изменить
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{form ? (
|
||||
<form className="adm-form" onSubmit={save}>
|
||||
<label className="ed-field adm-form-grow">
|
||||
<span className="ed-label">Название пространства</span>
|
||||
<input className="ed-input" required autoFocus value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field adm-form-short">
|
||||
<span className="ed-label">Значок</span>
|
||||
<input className="ed-input" maxLength={2} value={form.icon} onChange={(e) => setForm({ ...form, icon: e.target.value })} />
|
||||
</label>
|
||||
<div className="adm-form-actions">
|
||||
<button type="submit" className="btn btn--solid">
|
||||
Сохранить
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setForm(null)}>
|
||||
Отмена
|
||||
</button>
|
||||
{form.id ? (
|
||||
<button type="button" className="btn adm-danger" onClick={() => void remove(form.id!)}>
|
||||
Удалить
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="btn btn--dashed adm-add" onClick={() => setForm({ id: null, name: '', icon: '' })}>
|
||||
+ Пространство
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Разделы ----------
|
||||
interface SectionForm {
|
||||
id: string | null;
|
||||
name: string;
|
||||
code: string;
|
||||
color: PlaqueColor;
|
||||
}
|
||||
|
||||
function Sections({ space, onError }: { space: SpaceDto; onError: (e: string) => void }) {
|
||||
const { data: tree } = useTree();
|
||||
const refresh = useRefreshTree();
|
||||
const server = (tree?.sections ?? []).filter((s) => s.spaceId === space.id);
|
||||
// Пока тащим строку, показываем локальный порядок; после сохранения возвращаемся к серверному
|
||||
const [local, setLocal] = useState<SectionDto[] | null>(null);
|
||||
const [dragId, setDragId] = useState<string | null>(null);
|
||||
const [form, setForm] = useState<SectionForm | null>(null);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const list = local ?? server;
|
||||
const count = (id: string) => tree?.articles.filter((a) => a.sectionId === id).length ?? 0;
|
||||
|
||||
const saveOrder = async (items: SectionDto[]) => {
|
||||
try {
|
||||
await api('/admin/sections/order', { method: 'PUT', json: { ids: items.map((s) => s.id) } });
|
||||
await refresh();
|
||||
onError('');
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
} finally {
|
||||
setLocal(null);
|
||||
}
|
||||
};
|
||||
|
||||
const move = (items: SectionDto[], from: number, to: number) => {
|
||||
const next = [...items];
|
||||
const [x] = next.splice(from, 1);
|
||||
next.splice(to, 0, x!);
|
||||
return next;
|
||||
};
|
||||
|
||||
// Перетаскивание за ручку ⋮⋮. Сделано на событиях указателя, а не на HTML5 drag-and-drop:
|
||||
// тот не работает на сенсорных экранах.
|
||||
const onPointerMove = (e: React.PointerEvent) => {
|
||||
if (!dragId) return;
|
||||
const rows = [...(listRef.current?.querySelectorAll<HTMLElement>('[data-id]') ?? [])];
|
||||
const over = rows.findIndex((r) => {
|
||||
const b = r.getBoundingClientRect();
|
||||
return e.clientY >= b.top && e.clientY < b.bottom;
|
||||
});
|
||||
const from = list.findIndex((s) => s.id === dragId);
|
||||
if (over >= 0 && from >= 0 && over !== from) setLocal(move(list, from, over));
|
||||
};
|
||||
const endDrag = () => {
|
||||
if (!dragId) return;
|
||||
setDragId(null);
|
||||
if (local) void saveOrder(local);
|
||||
};
|
||||
|
||||
// С клавиатуры: стрелки вверх и вниз на ручке
|
||||
const onKey = (e: React.KeyboardEvent, index: number) => {
|
||||
const to = e.key === 'ArrowUp' ? index - 1 : e.key === 'ArrowDown' ? index + 1 : -1;
|
||||
if (to < 0 || to >= list.length) return;
|
||||
e.preventDefault();
|
||||
const next = move(list, index, to);
|
||||
setLocal(next);
|
||||
void saveOrder(next);
|
||||
};
|
||||
|
||||
const save = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!form) return;
|
||||
try {
|
||||
const json = { name: form.name, code: form.code, color: form.color };
|
||||
if (form.id) await api(`/admin/sections/${form.id}`, { method: 'PATCH', json });
|
||||
else await api('/admin/sections', { method: 'POST', json: { ...json, spaceId: space.id } });
|
||||
setForm(null);
|
||||
onError('');
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (id: string) => {
|
||||
try {
|
||||
await api(`/admin/sections/${id}`, { method: 'DELETE' });
|
||||
setForm(null);
|
||||
onError('');
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="block">
|
||||
<Caps right="перетащите за ⋮⋮ · порядок как на главной">Разделы {space.name}</Caps>
|
||||
<div className="list" ref={listRef} onPointerMove={onPointerMove} onPointerUp={endDrag} onPointerCancel={endDrag}>
|
||||
{list.map((s, i) => (
|
||||
<div key={s.id} data-id={s.id} className={s.id === dragId ? 'adm-sec adm-sec--drag' : 'adm-sec'}>
|
||||
<button
|
||||
type="button"
|
||||
className="adm-handle"
|
||||
aria-label={`Переместить раздел «${s.name}». Стрелки вверх и вниз меняют порядок`}
|
||||
onPointerDown={(e) => {
|
||||
e.currentTarget.setPointerCapture(e.pointerId);
|
||||
setDragId(s.id);
|
||||
}}
|
||||
onKeyDown={(e) => onKey(e, i)}
|
||||
>
|
||||
⋮⋮
|
||||
</button>
|
||||
<span className="adm-pos">{String(i + 1).padStart(2, '0')}</span>
|
||||
<CodeTag code={s.code} />
|
||||
<span className="adm-sec-name">{s.name}</span>
|
||||
<span className="adm-sec-n">{count(s.id)} ст.</span>
|
||||
<button type="button" className="adm-link" onClick={() => setForm({ id: s.id, name: s.name, code: s.code, color: s.color })}>
|
||||
Изменить
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
{!list.length ? <div className="sheet-empty">Разделов пока нет</div> : null}
|
||||
</div>
|
||||
|
||||
{form ? (
|
||||
<form className="adm-form" onSubmit={save}>
|
||||
<label className="ed-field adm-form-grow">
|
||||
<span className="ed-label">Название раздела</span>
|
||||
<input className="ed-input" required autoFocus value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field adm-form-short">
|
||||
<span className="ed-label">Код</span>
|
||||
<input className="ed-input" required maxLength={4} value={form.code} onChange={(e) => setForm({ ...form, code: e.target.value.toUpperCase() })} />
|
||||
</label>
|
||||
<div className="ed-field adm-form-wide">
|
||||
<span className="ed-label">Цвет плашки</span>
|
||||
<div className="adm-colors" role="radiogroup" aria-label="Цвет плашки">
|
||||
{PLAQUE_COLORS.map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={form.color === c}
|
||||
aria-label={c}
|
||||
className={form.color === c ? `adm-color adm-color--on plaque--${c}` : `adm-color plaque--${c}`}
|
||||
onClick={() => setForm({ ...form, color: c })}
|
||||
>
|
||||
{form.code || 'АБ'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="adm-form-actions">
|
||||
<button type="submit" className="btn btn--solid">
|
||||
Сохранить
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setForm(null)}>
|
||||
Отмена
|
||||
</button>
|
||||
{form.id ? (
|
||||
<button type="button" className="btn adm-danger" onClick={() => void remove(form.id!)}>
|
||||
Удалить
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="btn btn--dashed adm-add" onClick={() => setForm({ id: null, name: '', code: '', color: 'ink' })}>
|
||||
+ Раздел
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Пользователи ----------
|
||||
function Users({ onError }: { onError: (e: string) => void }) {
|
||||
const { user: me } = useAuth();
|
||||
const qc = useQueryClient();
|
||||
const users = useQuery({ queryKey: ['admin-users'], queryFn: () => api<AdminUserDto[]>('/admin/users') });
|
||||
const patch = useMutation({
|
||||
mutationFn: ({ id, ...json }: { id: string; role?: Role; blocked?: boolean }) => api(`/admin/users/${id}`, { method: 'PATCH', json }),
|
||||
onSuccess: () => onError(''),
|
||||
onError: (e) => onError(errText(e)),
|
||||
onSettled: () => qc.invalidateQueries({ queryKey: ['admin-users'] }),
|
||||
});
|
||||
const remove = useMutation({
|
||||
mutationFn: (id: string) => api(`/admin/users/${id}`, { method: 'DELETE' }),
|
||||
onError: (e) => onError(errText(e)),
|
||||
onSettled: () => qc.invalidateQueries({ queryKey: ['admin-users'] }),
|
||||
});
|
||||
const [openId, setOpenId] = useState<string | null>(null);
|
||||
|
||||
return (
|
||||
<section className="block">
|
||||
<Caps>Пользователи · {users.data?.length ?? '…'}</Caps>
|
||||
<div className="list">
|
||||
{users.data?.map((u) => (
|
||||
<div key={u.id} className={u.blocked ? 'adm-user adm-user--blocked' : 'adm-user'}>
|
||||
<div className="adm-user-row">
|
||||
<span className="avatar" aria-hidden="true">
|
||||
{initials(u.name)}
|
||||
</span>
|
||||
<button type="button" className="adm-user-main" onClick={() => setOpenId(openId === u.id ? null : u.id)} aria-expanded={openId === u.id}>
|
||||
<span className="adm-user-name">
|
||||
{u.name}
|
||||
{u.id === me?.id ? ' (вы)' : ''}
|
||||
</span>
|
||||
<span className="adm-user-sub">
|
||||
{u.email} · {u.blocked ? 'заблокирован' : u.lastSeenAt ? `был ${formatRecent(new Date(u.lastSeenAt).getTime())}` : 'ещё не входил'}
|
||||
</span>
|
||||
</button>
|
||||
<div className="adm-roles" role="group" aria-label={`Роль: ${u.name}`}>
|
||||
{ROLES.map((r) => (
|
||||
<button
|
||||
key={r}
|
||||
type="button"
|
||||
className={u.role === r ? 'adm-role adm-role--on' : 'adm-role'}
|
||||
aria-pressed={u.role === r}
|
||||
disabled={patch.isPending}
|
||||
onClick={() => u.role !== r && patch.mutate({ id: u.id, role: r })}
|
||||
>
|
||||
{ROLE_LABEL[r]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{openId === u.id ? (
|
||||
<div className="adm-user-more">
|
||||
<span className="adm-user-sub">Зарегистрирован {formatDate(u.createdAt)}</span>
|
||||
<button type="button" className="btn" disabled={u.id === me?.id} onClick={() => patch.mutate({ id: u.id, blocked: !u.blocked })}>
|
||||
{u.blocked ? 'Разблокировать' : 'Заблокировать'}
|
||||
</button>
|
||||
<button type="button" className="btn adm-danger" disabled={u.id === me?.id} onClick={() => remove.mutate(u.id)}>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Приглашения ----------
|
||||
function Invites({ onError }: { onError: (e: string) => void }) {
|
||||
const qc = useQueryClient();
|
||||
const invites = useQuery({ queryKey: ['admin-invites'], queryFn: () => api<InviteDto[]>('/admin/invites') });
|
||||
const [role, setRole] = useState<Role>('VIEWER');
|
||||
const [copied, setCopied] = useState<string | null>(null);
|
||||
const latest = invites.data?.[0];
|
||||
|
||||
const copy = async (inv: InviteDto) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(inv.url);
|
||||
} catch {
|
||||
// Буфер обмена недоступен (не https): ссылку можно выделить и скопировать вручную
|
||||
}
|
||||
setCopied(inv.id);
|
||||
setTimeout(() => setCopied((c) => (c === inv.id ? null : c)), 1800);
|
||||
};
|
||||
|
||||
const create = async () => {
|
||||
try {
|
||||
const inv = await api<InviteDto>('/admin/invites', { method: 'POST', json: { role } });
|
||||
await qc.invalidateQueries({ queryKey: ['admin-invites'] });
|
||||
await copy(inv);
|
||||
onError('');
|
||||
} catch (err) {
|
||||
onError(errText(err));
|
||||
}
|
||||
};
|
||||
|
||||
const revoke = async (id: string) => {
|
||||
await api(`/admin/invites/${id}`, { method: 'DELETE' }).catch((e) => onError(errText(e)));
|
||||
await qc.invalidateQueries({ queryKey: ['admin-invites'] });
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="adm-invite">
|
||||
<div className="adm-invite-title">Приглашение по ссылке</div>
|
||||
<div className="adm-invite-text">Ссылка одноразовая и действует 7 дней. Новый пользователь получит роль «{ROLE_LABEL[role]}».</div>
|
||||
<div className="adm-roles adm-roles--wide" role="group" aria-label="Роль для приглашения">
|
||||
{ROLES.map((r) => (
|
||||
<button key={r} type="button" className={role === r ? 'adm-role adm-role--on' : 'adm-role'} aria-pressed={role === r} onClick={() => setRole(r)}>
|
||||
{ROLE_LABEL[r]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button type="button" className="btn btn--solid btn--lg" onClick={() => void create()}>
|
||||
{copied && copied === latest?.id ? 'Ссылка скопирована' : 'Пригласить по ссылке'}
|
||||
</button>
|
||||
{invites.data?.map((inv) => (
|
||||
<div key={inv.id} className="adm-invite-row">
|
||||
<input className="adm-invite-url" readOnly value={inv.url} aria-label="Ссылка-приглашение" onFocus={(e) => e.target.select()} />
|
||||
<span className="adm-invite-meta">
|
||||
{ROLE_LABEL[inv.role]} · до {formatDate(inv.expiresAt)}
|
||||
</span>
|
||||
<button type="button" className="btn" onClick={() => void copy(inv)}>
|
||||
{copied === inv.id ? 'Скопировано' : 'Скопировать'}
|
||||
</button>
|
||||
<button type="button" className="btn adm-danger" onClick={() => void revoke(inv.id)}>
|
||||
Отозвать
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -3,12 +3,16 @@ import { Link, Navigate, useParams } from 'react-router-dom';
|
||||
import { ArticleBody, type Figure } from '../components/ArticleBody';
|
||||
import { IconList, IconPrint, IconStar, IconTheme, IconUp } from '../components/Icons';
|
||||
import { Lightbox } from '../components/Lightbox';
|
||||
import { OfflinePill } from '../components/Offline';
|
||||
import { useIsCached } from '../lib/offline';
|
||||
import { PrintSheet } from '../components/PrintSheet';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { BackLink, Notice, Sheet, Skeleton } from '../components/ui';
|
||||
import { ApiError, useArticle } from '../lib/api';
|
||||
import { fileExt, formatBytes, formatDate, num2 } from '../lib/format';
|
||||
import { pushRecentView, useAuth } from '../lib/auth';
|
||||
import { pushRecent, useFavorites } from '../lib/store';
|
||||
import { LoginPage } from './Login';
|
||||
import { useTheme } from '../lib/theme';
|
||||
import { useNav } from '../lib/tree';
|
||||
|
||||
@@ -51,6 +55,7 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
const fav = useFavorites();
|
||||
const theme = useTheme();
|
||||
const { scrolled, progress } = useReadProgress();
|
||||
const cached = useIsCached(art?.slug);
|
||||
const [tocOpen, setTocOpen] = useState(false);
|
||||
const [printOpen, setPrintOpen] = useState(false);
|
||||
const [lightbox, setLightbox] = useState<{ figures: Figure[]; start: number } | null>(null);
|
||||
@@ -58,9 +63,13 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
const listItem = nav.article(slug);
|
||||
const section = nav.sectionOf(art ?? listItem);
|
||||
|
||||
const { user, isEditor } = useAuth();
|
||||
const artSlug = art?.slug;
|
||||
useEffect(() => {
|
||||
if (art) pushRecent(art.slug);
|
||||
}, [art]);
|
||||
if (!artSlug) return;
|
||||
pushRecent(artSlug);
|
||||
if (user) void pushRecentView(artSlug);
|
||||
}, [artSlug, user]);
|
||||
|
||||
// При переходе на другую статью начинаем чтение сверху
|
||||
useEffect(() => {
|
||||
@@ -102,6 +111,9 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
</nav>
|
||||
);
|
||||
|
||||
// Закрытая статья, а пользователь не вошёл: показываем экран входа (после входа статья откроется)
|
||||
if (!art && error instanceof ApiError && error.status === 401) return <LoginPage />;
|
||||
|
||||
if (!art) {
|
||||
const notFound = error instanceof ApiError && error.status === 404;
|
||||
return (
|
||||
@@ -184,7 +196,7 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
{nav.space?.name} / {section ? <Link to={`/s/${section.slug}`}>{section.name}</Link> : null} /{' '}
|
||||
<strong>{nav.short(art)}</strong>
|
||||
</div>
|
||||
<span id="article-offline-slot-desk" />
|
||||
{cached ? <OfflinePill long /> : null}
|
||||
<button type="button" className="btn btn--ghost" onClick={() => fav.toggle(slug)} aria-pressed={isFav}>
|
||||
{isFav ? '★ В избранном' : '☆ В избранное'}
|
||||
</button>
|
||||
@@ -192,16 +204,28 @@ function ArticleView({ slug }: { slug: string }) {
|
||||
<IconPrint size={20} />
|
||||
Печать / PDF
|
||||
</button>
|
||||
<span id="article-edit-slot" />
|
||||
{isEditor ? (
|
||||
<Link className="btn btn--solid" to={`/edit/${slug}`}>
|
||||
Редактировать
|
||||
</Link>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="art-layout">
|
||||
<article className="art">
|
||||
<div className="topline art-topline">
|
||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||
<span id="article-offline-slot" />
|
||||
<span className="topline-right">
|
||||
{cached ? <OfflinePill /> : null}
|
||||
{isEditor ? (
|
||||
<Link className="btn" to={`/edit/${slug}`}>
|
||||
Править
|
||||
</Link>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
<div className="art-over">{section?.name}</div>
|
||||
{art.status === 'DRAFT' ? <span className="badge-draft">Черновик: читатели не видят</span> : null}
|
||||
<h1 className="art-title">{art.title}</h1>
|
||||
{art.summary ? <p className="art-summary">{art.summary}</p> : null}
|
||||
<div className="art-meta-mobile">{meta}</div>
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
// Редактор статьи: Markdown слева, живой предпросмотр (тем же рендером, что на сервере), свойства справа.
|
||||
// На телефоне упрощённый вид с переключателем Текст / Просмотр / Свойства.
|
||||
|
||||
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { renderMarkdown } from '@kb/md';
|
||||
import type { AttachmentDto, RevisionDto, Visibility } from '@kb/shared';
|
||||
import { ArticleBody } from '../components/ArticleBody';
|
||||
import { MdEditor, type MdEditorHandle } from '../components/MdEditor';
|
||||
import { Notice, Sheet, Skeleton } from '../components/ui';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { diffLines } from '../lib/diff';
|
||||
import { fileExt, formatBytes, formatDate } from '../lib/format';
|
||||
import { dropApiCache } from '../lib/offline';
|
||||
import { useNav } from '../lib/tree';
|
||||
import '../styles/editor.css';
|
||||
|
||||
interface Meta {
|
||||
title: string;
|
||||
summary: string;
|
||||
sectionId: string;
|
||||
tags: string[];
|
||||
equipment: string[];
|
||||
docCode: string | null;
|
||||
pinned: boolean;
|
||||
visibility: Visibility;
|
||||
order: number;
|
||||
}
|
||||
|
||||
interface EditData {
|
||||
id: string;
|
||||
slug: string;
|
||||
status: 'DRAFT' | 'PUBLISHED';
|
||||
version: number;
|
||||
updatedAt: string;
|
||||
md: string;
|
||||
meta: Meta;
|
||||
draft: { md: string; meta: Meta | null; at: string | null } | null;
|
||||
attachments: AttachmentDto[];
|
||||
}
|
||||
|
||||
// Заготовки блоков (из макета). dot: цвет метки на кнопке.
|
||||
const SNIPPETS: { label: string; dot: string; text: string }[] = [
|
||||
{ label: 'Главное', dot: 'var(--brand)', text: '\n:::keyfacts\n- Параметр: **значение**\n:::\n' },
|
||||
{ label: 'Запрет', dot: 'var(--redS)', text: '\n:::danger\nЧто запрещено: **коротко и конкретно**.\n:::\n' },
|
||||
{ label: 'Внимание', dot: 'var(--ambln)', text: '\n:::warning\nНа что обратить **внимание**.\n:::\n' },
|
||||
{ label: 'Совет', dot: 'var(--grnS)', text: '\n:::tip\nСовет или исключение из правила.\n:::\n' },
|
||||
{ label: 'Справка', dot: 'var(--blu)', text: '\n:::info\nУточнить у заказчика: …\n:::\n' },
|
||||
{ label: 'Чек-лист', dot: 'var(--ink2)', text: '\n- [ ] Пункт\n- [ ] Пункт\n' },
|
||||
{ label: 'Таблица', dot: 'var(--ink2)', text: '\n| Что | Значение |\n|---|---|\n| Параметр | **1 м** |\n' },
|
||||
];
|
||||
|
||||
const AUTOSAVE_MS = 10_000;
|
||||
const hhmm = (d: Date | string) => new Date(d).toTimeString().slice(0, 5);
|
||||
|
||||
/** Поле с «чипами»: теги, оборудование. Enter или запятая с пробелом добавляет значение. */
|
||||
function ChipsInput({ label, values, onChange, placeholder }: { label: string; values: string[]; onChange: (v: string[]) => void; placeholder: string }) {
|
||||
const [text, setText] = useState('');
|
||||
const add = () => {
|
||||
const v = text.trim();
|
||||
if (v && !values.includes(v)) onChange([...values, v]);
|
||||
setText('');
|
||||
};
|
||||
return (
|
||||
<div className="ed-field">
|
||||
<span className="ed-label">{label}</span>
|
||||
<div className="ed-chips">
|
||||
{values.map((v) => (
|
||||
<button key={v} type="button" className="ed-chip" onClick={() => onChange(values.filter((x) => x !== v))} aria-label={`Убрать: ${v}`}>
|
||||
{v} ✕
|
||||
</button>
|
||||
))}
|
||||
<input
|
||||
className="ed-chips-input"
|
||||
value={text}
|
||||
placeholder={placeholder}
|
||||
aria-label={label}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onBlur={add}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
add();
|
||||
} else if (e.key === 'Backspace' && !text && values.length) onChange(values.slice(0, -1));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function EditorPage() {
|
||||
const { slug = '' } = useParams();
|
||||
const { isEditor } = useAuth();
|
||||
const { data, error, isLoading } = useQuery({
|
||||
queryKey: ['edit', slug],
|
||||
queryFn: () => api<EditData>(`/edit/articles/${encodeURIComponent(slug)}`),
|
||||
enabled: isEditor,
|
||||
staleTime: Infinity,
|
||||
gcTime: 0,
|
||||
});
|
||||
|
||||
if (!isEditor) {
|
||||
return (
|
||||
<div className="ed-wrap">
|
||||
<Notice title="Недостаточно прав">Редактировать статьи могут редакторы и администраторы.</Notice>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!data) {
|
||||
return (
|
||||
<div className="ed-wrap">
|
||||
{isLoading ? <Skeleton /> : <Notice title="Не удалось открыть статью" tone="error">{error instanceof ApiError ? error.message : 'Проверьте связь.'}</Notice>}
|
||||
<Link to="/" className="btn">
|
||||
На главную
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
// key: при переходе к другой статье состояние редактора создаётся заново
|
||||
return <Editor key={data.id} data={data} />;
|
||||
}
|
||||
|
||||
function Editor({ data }: { data: EditData }) {
|
||||
const nav = useNav();
|
||||
const qc = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const editor = useRef<MdEditorHandle>(null);
|
||||
const fileInput = useRef<HTMLInputElement>(null);
|
||||
const docInput = useRef<HTMLInputElement>(null);
|
||||
|
||||
// Если есть несохранённая публикация (черновик), продолжаем с неё
|
||||
const [md, setMd] = useState(data.draft?.md ?? data.md);
|
||||
const [meta, setMeta] = useState<Meta>(data.draft?.meta ?? data.meta);
|
||||
const [attachments, setAttachments] = useState(data.attachments);
|
||||
const [version, setVersion] = useState(data.version);
|
||||
const [published, setPublished] = useState(data.status === 'PUBLISHED');
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [tab, setTab] = useState<'text' | 'preview' | 'meta'>('text');
|
||||
const [status, setStatus] = useState(
|
||||
data.draft?.at ? `Черновик · сохранён ${hhmm(data.draft.at)}` : published ? `Опубликовано · v${data.version} · ${formatDate(data.updatedAt)}` : 'Черновик',
|
||||
);
|
||||
const [errorText, setErrorText] = useState('');
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
|
||||
const change = (next: string) => {
|
||||
setMd(next);
|
||||
setDirty(true);
|
||||
setStatus('Черновик · есть несохранённые изменения');
|
||||
};
|
||||
const changeMeta = (patch: Partial<Meta>) => {
|
||||
setMeta((m) => ({ ...m, ...patch }));
|
||||
setDirty(true);
|
||||
setStatus('Черновик · есть несохранённые изменения');
|
||||
};
|
||||
|
||||
// Предпросмотр: тот же рендер, что на сервере. useDeferredValue не даёт ему тормозить набор текста.
|
||||
const deferred = useDeferredValue(md);
|
||||
const preview = useMemo(
|
||||
() => renderMarkdown(deferred, { resolveLink: (s) => nav.article(s)?.title }),
|
||||
[deferred, nav],
|
||||
);
|
||||
const links = useMemo(() => nav.articles.map((a) => ({ slug: a.slug, title: a.title })), [nav.articles]);
|
||||
|
||||
// Актуальные значения для таймера автосохранения
|
||||
const state = useRef({ md, meta, dirty, busy });
|
||||
useEffect(() => {
|
||||
state.current = { md, meta, dirty, busy };
|
||||
});
|
||||
|
||||
const saveDraft = useCallback(
|
||||
async (silent = false) => {
|
||||
const s = state.current;
|
||||
if (silent && (!s.dirty || s.busy)) return;
|
||||
try {
|
||||
const r = await api<{ at: string }>(`/edit/articles/${data.id}/draft`, { method: 'PUT', json: { md: s.md, meta: s.meta } });
|
||||
// Пока шёл запрос, текст могли поменять: тогда «несохранённое» остаётся
|
||||
if (state.current.md === s.md && state.current.meta === s.meta) setDirty(false);
|
||||
setStatus(`Черновик сохранён · ${hhmm(r.at)}`);
|
||||
setErrorText('');
|
||||
} catch (e) {
|
||||
if (!silent) setErrorText(e instanceof ApiError ? e.message : 'Не удалось сохранить');
|
||||
setStatus('Не сохранено: нет связи. Текст остаётся в этом окне');
|
||||
}
|
||||
},
|
||||
[data.id],
|
||||
);
|
||||
|
||||
// Автосохранение черновика каждые 10 секунд
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => void saveDraft(true), AUTOSAVE_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [saveDraft]);
|
||||
|
||||
// Предупреждение при закрытии вкладки с несохранённым текстом
|
||||
useEffect(() => {
|
||||
if (!dirty) return;
|
||||
const warn = (e: BeforeUnloadEvent) => e.preventDefault();
|
||||
window.addEventListener('beforeunload', warn);
|
||||
return () => window.removeEventListener('beforeunload', warn);
|
||||
}, [dirty]);
|
||||
|
||||
const publish = async () => {
|
||||
setBusy(true);
|
||||
setErrorText('');
|
||||
try {
|
||||
const r = await api<{ version: number; at: string }>(`/edit/articles/${data.id}/publish`, { method: 'POST', json: { md, meta } });
|
||||
setVersion(r.version);
|
||||
setPublished(true);
|
||||
setDirty(false);
|
||||
setStatus(`Опубликовано · v${r.version} · ${hhmm(r.at)}`);
|
||||
// Читатели должны увидеть новую версию, а не сохранённую в кеше
|
||||
await dropApiCache(['/api/tree', `/api/articles/${data.slug}`]);
|
||||
await qc.invalidateQueries({ predicate: (q) => ['tree', 'article', 'search', 'revisions'].includes(String(q.queryKey[0])) });
|
||||
} catch (e) {
|
||||
setErrorText(e instanceof ApiError ? e.message : 'Не удалось опубликовать');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const unpublish = async () => {
|
||||
await api(`/edit/articles/${data.id}/unpublish`, { method: 'POST' });
|
||||
setPublished(false);
|
||||
setStatus('Снято с публикации · читатели статью не видят');
|
||||
await dropApiCache(['/api/tree', `/api/articles/${data.slug}`]);
|
||||
await qc.invalidateQueries({ queryKey: ['tree'] });
|
||||
};
|
||||
|
||||
// Картинки: загружаем по очереди и сразу вставляем  на место курсора
|
||||
const uploadImages = async (files: File[]) => {
|
||||
let done = 0;
|
||||
setStatus(`Загрузка фото: 0 из ${files.length}…`);
|
||||
for (const file of files) {
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
form.append('articleId', data.id);
|
||||
const r = await api<{ url: string }>('/edit/images', { method: 'POST', body: form });
|
||||
editor.current?.insert(`\n\n`);
|
||||
done++;
|
||||
setStatus(`Загрузка фото: ${done} из ${files.length}…`);
|
||||
} catch (e) {
|
||||
setErrorText(`${file.name}: ${e instanceof ApiError ? e.message : 'не загрузилось'}`);
|
||||
}
|
||||
}
|
||||
if (done) setStatus(`Фото добавлено · ${done} шт.`);
|
||||
};
|
||||
|
||||
const uploadDoc = async (file: File | undefined) => {
|
||||
if (!file) return;
|
||||
try {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
const att = await api<AttachmentDto>(`/edit/articles/${data.id}/attachments`, { method: 'POST', body: form });
|
||||
setAttachments((list) => [...list.filter((a) => a.id !== att.id), att]);
|
||||
setErrorText('');
|
||||
} catch (e) {
|
||||
setErrorText(e instanceof ApiError ? e.message : 'Файл не загрузился');
|
||||
}
|
||||
};
|
||||
|
||||
const removeDoc = async (id: string) => {
|
||||
await api(`/edit/attachments/${id}`, { method: 'DELETE' });
|
||||
setAttachments((list) => list.filter((a) => a.id !== id));
|
||||
};
|
||||
|
||||
const back = () => navigate(published ? `/a/${data.slug}` : '/');
|
||||
|
||||
const toolbar = (
|
||||
<div className="ed-toolbar" role="toolbar" aria-label="Вставить блок">
|
||||
{SNIPPETS.map((s) => (
|
||||
<button key={s.label} type="button" className="ed-tool" onClick={() => editor.current?.insert(s.text)}>
|
||||
<span className="ed-tool-dot" style={{ background: s.dot }} aria-hidden="true" />
|
||||
{s.label}
|
||||
</button>
|
||||
))}
|
||||
<button type="button" className="ed-tool" onClick={() => fileInput.current?.click()}>
|
||||
<span className="ed-tool-dot" style={{ background: 'var(--ink2)' }} aria-hidden="true" />
|
||||
Фото
|
||||
</button>
|
||||
<button type="button" className="ed-tool" onClick={() => editor.current?.insert('[[')}>
|
||||
<span className="ed-tool-dot" style={{ background: 'var(--ink2)' }} aria-hidden="true" />
|
||||
Ссылка на статью
|
||||
</button>
|
||||
<input
|
||||
ref={fileInput}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
void uploadImages([...(e.target.files ?? [])]);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
const metaPanel = (
|
||||
<div className="ed-meta">
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Название</span>
|
||||
<input className="ed-input" value={meta.title} onChange={(e) => changeMeta({ title: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Краткое описание</span>
|
||||
<textarea className="ed-input ed-input--area" rows={3} value={meta.summary} onChange={(e) => changeMeta({ summary: e.target.value })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Раздел</span>
|
||||
<select className="ed-input" value={meta.sectionId} onChange={(e) => changeMeta({ sectionId: e.target.value })}>
|
||||
{nav.allSections.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<ChipsInput label="Теги" values={meta.tags} onChange={(tags) => changeMeta({ tags })} placeholder="+ тег" />
|
||||
<ChipsInput label="Оборудование" values={meta.equipment} onChange={(equipment) => changeMeta({ equipment })} placeholder="+ модель" />
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Шифр документа</span>
|
||||
<input className="ed-input" value={meta.docCode ?? ''} onChange={(e) => changeMeta({ docCode: e.target.value || null })} />
|
||||
</label>
|
||||
<label className="ed-field">
|
||||
<span className="ed-label">Кто видит</span>
|
||||
<select className="ed-input" value={meta.visibility} onChange={(e) => changeMeta({ visibility: e.target.value as Visibility })}>
|
||||
<option value="PRIVATE">Только вошедшие пользователи</option>
|
||||
<option value="PUBLIC">Все, у кого есть ссылка (без входа)</option>
|
||||
</select>
|
||||
</label>
|
||||
<label className="ed-check">
|
||||
<input type="checkbox" checked={meta.pinned} onChange={(e) => changeMeta({ pinned: e.target.checked })} />
|
||||
Закрепить как шпаргалку
|
||||
</label>
|
||||
|
||||
<div className="ed-field">
|
||||
<span className="ed-label">Исходный файл</span>
|
||||
{attachments.map((a) => (
|
||||
<div key={a.id} className="ed-file">
|
||||
<span className="ed-file-ext">{fileExt(a.filename)}</span>
|
||||
<a className="ed-file-name" href={a.url} download={a.filename}>
|
||||
{a.filename} · {formatBytes(a.size)}
|
||||
</a>
|
||||
<button type="button" className="ed-file-del" onClick={() => void removeDoc(a.id)} aria-label={`Удалить ${a.filename}`}>
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" className="btn btn--dashed" onClick={() => docInput.current?.click()}>
|
||||
+ Прикрепить PDF или DOCX
|
||||
</button>
|
||||
<input
|
||||
ref={docInput}
|
||||
type="file"
|
||||
accept=".pdf,.doc,.docx,.xls,.xlsx,.dwg"
|
||||
hidden
|
||||
onChange={(e) => {
|
||||
void uploadDoc(e.target.files?.[0]);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="ed-drop"
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
void uploadImages([...e.dataTransfer.files].filter((f) => f.type.startsWith('image/')));
|
||||
}}
|
||||
>
|
||||
<span className="ed-drop-title">Перетащите фото сюда</span>
|
||||
<span className="ed-drop-text">или Ctrl+V в тексте · JPG, PNG до 15 МБ</span>
|
||||
</div>
|
||||
|
||||
<button type="button" className="btn" onClick={() => setHistoryOpen(true)}>
|
||||
История версий · v{version}
|
||||
</button>
|
||||
{published ? (
|
||||
<button type="button" className="btn" onClick={() => void unpublish()}>
|
||||
Снять с публикации
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="ed">
|
||||
<header className="ed-head">
|
||||
<button type="button" className="ed-back" onClick={back} aria-label="Назад">
|
||||
‹
|
||||
</button>
|
||||
<div className="ed-head-text">
|
||||
<div className="ed-title">{meta.title || 'Без названия'}</div>
|
||||
<div className="ed-status" role="status">
|
||||
{status}
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" className="btn ed-only-desk" onClick={() => setHistoryOpen(true)}>
|
||||
История версий
|
||||
</button>
|
||||
<button type="button" className="btn btn--outline ed-only-desk" onClick={() => void saveDraft()} disabled={busy}>
|
||||
Черновик
|
||||
</button>
|
||||
<button type="button" className="btn btn--solid ed-only-desk" onClick={() => void publish()} disabled={busy}>
|
||||
Опубликовать
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="ed-tabs segmented segmented--3" role="group" aria-label="Вид">
|
||||
{(
|
||||
[
|
||||
['text', 'Текст'],
|
||||
['preview', 'Просмотр'],
|
||||
['meta', 'Свойства'],
|
||||
] as const
|
||||
).map(([id, label]) => (
|
||||
<button key={id} type="button" className={tab === id ? 'seg seg--on' : 'seg'} aria-pressed={tab === id} onClick={() => setTab(id)}>
|
||||
{label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{toolbar}
|
||||
|
||||
{errorText ? (
|
||||
<div className="form-error ed-error" role="alert">
|
||||
{errorText}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={`ed-cols ed-cols--${tab}`}>
|
||||
<section className="ed-col ed-col--text">
|
||||
<div className="ed-col-head">MARKDOWN</div>
|
||||
<MdEditor ref={editor} value={md} onChange={change} links={links} onImages={(files) => void uploadImages(files)} />
|
||||
</section>
|
||||
<section className="ed-col ed-col--preview">
|
||||
<div className="ed-col-head">ПРЕДПРОСМОТР · 390 PX</div>
|
||||
<div className="ed-preview">
|
||||
<div className="ed-preview-phone">
|
||||
{preview.brokenLinks.length ? (
|
||||
<div className="form-error">Битые ссылки: {preview.brokenLinks.map((s) => `[[${s}]]`).join(', ')}</div>
|
||||
) : null}
|
||||
<ArticleBody html={preview.html} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<section className="ed-col ed-col--meta">{metaPanel}</section>
|
||||
</div>
|
||||
|
||||
<footer className="ed-foot">
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={() => void saveDraft()} disabled={busy}>
|
||||
Черновик
|
||||
</button>
|
||||
<button type="button" className="btn btn--solid btn--lg" onClick={() => void publish()} disabled={busy}>
|
||||
Опубликовать
|
||||
</button>
|
||||
</footer>
|
||||
|
||||
{historyOpen ? (
|
||||
<History
|
||||
articleId={data.id}
|
||||
current={md}
|
||||
onClose={() => setHistoryOpen(false)}
|
||||
onRestore={(text) => {
|
||||
change(text);
|
||||
setHistoryOpen(false);
|
||||
setStatus('Возвращена старая версия · нажмите «Опубликовать», чтобы она стала текущей');
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** История версий: список, сравнение выбранной версии с текстом в редакторе, откат. */
|
||||
function History({ articleId, current, onClose, onRestore }: { articleId: string; current: string; onClose: () => void; onRestore: (md: string) => void }) {
|
||||
const [picked, setPicked] = useState<number | null>(null);
|
||||
const list = useQuery({ queryKey: ['revisions', articleId], queryFn: () => api<RevisionDto[]>(`/edit/articles/${articleId}/revisions`) });
|
||||
const rev = useQuery({
|
||||
queryKey: ['revision', articleId, picked],
|
||||
queryFn: () => api<{ version: number; md: string }>(`/edit/articles/${articleId}/revisions/${picked}`),
|
||||
enabled: picked !== null,
|
||||
});
|
||||
// Что изменится в редакторе, если вернуть выбранную версию: было «сейчас», станет «версия»
|
||||
const diff = useMemo(() => (rev.data ? diffLines(current, rev.data.md) : []), [rev.data, current]);
|
||||
const changed = diff.some((l) => l.type === 'add' || l.type === 'del');
|
||||
|
||||
return (
|
||||
<Sheet title="История версий" subtitle={picked ? `Сравнение: текст в редакторе → v${picked}` : 'Выберите версию, чтобы сравнить'} onClose={onClose}>
|
||||
<div className="sheet-scroll">
|
||||
{list.isLoading ? <div className="sheet-empty">Загрузка…</div> : null}
|
||||
{list.data?.length === 0 ? <div className="sheet-empty">Опубликованных версий пока нет</div> : null}
|
||||
{list.data?.map((r) => (
|
||||
<button key={r.id} type="button" className={picked === r.version ? 'rev-row rev-row--on' : 'rev-row'} onClick={() => setPicked(r.version)}>
|
||||
<span className="rev-v">v{r.version}</span>
|
||||
<span className="rev-main">{[r.comment, r.authorName].filter(Boolean).join(' · ') || 'Без комментария'}</span>
|
||||
<span className="rev-date">{formatDate(r.createdAt)}</span>
|
||||
</button>
|
||||
))}
|
||||
{picked !== null && rev.data ? (
|
||||
<div className="rev-diff">
|
||||
{changed ? (
|
||||
<pre className="diff">
|
||||
{diff.map((l, i) => (
|
||||
<span key={i} className={`diff-line diff-line--${l.type}`}>
|
||||
{l.type === 'add' ? '+ ' : l.type === 'del' ? '− ' : ' '}
|
||||
{l.text || ' '}
|
||||
{'\n'}
|
||||
</span>
|
||||
))}
|
||||
</pre>
|
||||
) : (
|
||||
<div className="sheet-empty">Эта версия совпадает с текстом в редакторе</div>
|
||||
)}
|
||||
<button type="button" className="btn btn--solid btn--lg btn--block" disabled={!changed} onClick={() => onRestore(rev.data.md)}>
|
||||
Вернуть версию v{picked}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { Screen, SpacePicker } from '../components/Shell';
|
||||
import { UserMenu } from '../components/UserMenu';
|
||||
import { Caps, CodeTag, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { useArticle } from '../lib/api';
|
||||
import { formatRecent } from '../lib/format';
|
||||
@@ -57,6 +58,12 @@ export function HomePage() {
|
||||
<ThemeButton />
|
||||
</header>
|
||||
|
||||
{nav.spaces.length > 1 ? (
|
||||
<div className="home-space">
|
||||
<SpacePicker />
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Поле на главной только открывает экран поиска: печатать удобнее там, где сразу видны результаты */}
|
||||
<div className="home-search">
|
||||
<label className="search-field">
|
||||
@@ -180,6 +187,22 @@ export function HomePage() {
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{/* В макете этих ссылок нет: без них с телефона не попасть на экран офлайн-разделов */}
|
||||
<nav className="list home-more" aria-label="Ещё">
|
||||
<Link to="/offline" className="list-row">
|
||||
<span className="list-row-main">
|
||||
<span className="list-row-title">Офлайн-разделы</span>
|
||||
<span className="list-row-sub">Скачать заранее, если на объекте нет связи</span>
|
||||
</span>
|
||||
<span className="list-row-chev" aria-hidden="true">
|
||||
›
|
||||
</span>
|
||||
</Link>
|
||||
</nav>
|
||||
<div className="home-more">
|
||||
<UserMenu />
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { type FormEvent, useEffect, useState } from 'react';
|
||||
import { useNavigate, useParams } from 'react-router-dom';
|
||||
import { ROLE_LABEL, type Role, type UserDto } from '@kb/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuthActions } from '../lib/auth';
|
||||
|
||||
function AuthFrame({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="login">
|
||||
<div className="hazard hazard--lg" aria-hidden="true" />
|
||||
<main className="login-main">
|
||||
<div>
|
||||
<div className="login-site">wiki.suchtech.ru</div>
|
||||
<h1 className="login-title">Памятки монтажника</h1>
|
||||
</div>
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordField({ value, onChange, label, autoComplete }: { value: string; onChange: (v: string) => void; label: string; autoComplete: string }) {
|
||||
const [shown, setShown] = useState(false);
|
||||
return (
|
||||
<label className="field">
|
||||
<span className="field-label">{label}</span>
|
||||
<span className="field-box">
|
||||
<input
|
||||
className="field-input"
|
||||
type={shown ? 'text' : 'password'}
|
||||
autoComplete={autoComplete}
|
||||
required
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
/>
|
||||
<button type="button" className="field-toggle" onClick={() => setShown(!shown)} aria-pressed={shown}>
|
||||
{shown ? 'Скрыть' : 'Показать'}
|
||||
</button>
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function Remember({ on, toggle }: { on: boolean; toggle: () => void }) {
|
||||
return (
|
||||
<button type="button" role="switch" aria-checked={on} className="remember" onClick={toggle}>
|
||||
<span className={on ? 'bigbox bigbox--on' : 'bigbox'} aria-hidden="true" />
|
||||
<span>
|
||||
<span className="remember-title">Запомнить устройство</span>
|
||||
<span className="remember-text">Не спрашивать пароль 90 дней</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [remember, setRemember] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [inviteOpen, setInviteOpen] = useState(false);
|
||||
const [inviteLink, setInviteLink] = useState('');
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>('/auth/login', { method: 'POST', json: { email, password, remember } });
|
||||
await onLogin(user);
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось войти');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// «Есть ссылка-приглашение»: принимаем и полную ссылку, и один код из неё
|
||||
const openInvite = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
const token = inviteLink.trim().split('/').filter(Boolean).pop();
|
||||
if (token) navigate(`/invite/${token}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
type="email"
|
||||
inputMode="email"
|
||||
autoComplete="username"
|
||||
placeholder="ivanov@suchtech.ru"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<PasswordField label="Пароль" autoComplete="current-password" value={password} onChange={setPassword} />
|
||||
<Remember on={remember} toggle={() => setRemember(!remember)} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Входим…' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
{inviteOpen ? (
|
||||
<form className="login-form" onSubmit={openInvite}>
|
||||
<label className="field">
|
||||
<span className="field-label">Ссылка-приглашение</span>
|
||||
<input
|
||||
className="field-input field-input--box"
|
||||
autoFocus
|
||||
placeholder="Вставьте ссылку от администратора"
|
||||
value={inviteLink}
|
||||
onChange={(e) => setInviteLink(e.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="btn btn--outline btn--lg">
|
||||
Продолжить
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button type="button" className="login-link" onClick={() => setInviteOpen(true)}>
|
||||
Есть ссылка-приглашение
|
||||
</button>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
|
||||
export function InvitePage() {
|
||||
const { token = '' } = useParams();
|
||||
const { onLogin } = useAuthActions();
|
||||
const navigate = useNavigate();
|
||||
const [role, setRole] = useState<Role | null>(null);
|
||||
const [invalid, setInvalid] = useState('');
|
||||
const [name, setName] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
api<{ role: Role }>(`/auth/invite/${encodeURIComponent(token)}`)
|
||||
.then((r) => setRole(r.role))
|
||||
.catch((e) => setInvalid(e instanceof ApiError ? e.message : 'Не удалось проверить ссылку'));
|
||||
}, [token]);
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const { user } = await api<{ user: UserDto }>(`/auth/invite/${encodeURIComponent(token)}`, {
|
||||
method: 'POST',
|
||||
json: { name, email, password },
|
||||
});
|
||||
await onLogin(user);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось зарегистрироваться');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthFrame>
|
||||
{invalid ? (
|
||||
<>
|
||||
<div className="form-error" role="alert">
|
||||
{invalid}
|
||||
</div>
|
||||
<button type="button" className="btn btn--outline btn--lg" onClick={() => navigate('/')}>
|
||||
На экран входа
|
||||
</button>
|
||||
</>
|
||||
) : !role ? (
|
||||
<div className="login-note">Проверяем приглашение…</div>
|
||||
) : (
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<div className="login-note">
|
||||
Вас пригласили с ролью «{ROLE_LABEL[role]}». Придумайте пароль, чтобы входить с любого устройства.
|
||||
</div>
|
||||
<label className="field">
|
||||
<span className="field-label">Имя и фамилия</span>
|
||||
<input className="field-input field-input--box" autoComplete="name" required minLength={2} value={name} onChange={(e) => setName(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">Почта</span>
|
||||
<input className="field-input field-input--box" type="email" inputMode="email" autoComplete="username" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
</label>
|
||||
<PasswordField label="Пароль (не короче 8 символов)" autoComplete="new-password" value={password} onChange={setPassword} />
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy}>
|
||||
{busy ? 'Создаём…' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</AuthFrame>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { type FormEvent, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { BackLink, Notice } from '../components/ui';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { useNav } from '../lib/tree';
|
||||
import '../styles/editor.css';
|
||||
|
||||
// Новая статья: спрашиваем название и раздел, создаём черновик и открываем редактор.
|
||||
export default function NewArticlePage() {
|
||||
const nav = useNav();
|
||||
const { isEditor } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [title, setTitle] = useState('');
|
||||
const [sectionId, setSectionId] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const section = sectionId || nav.allSections[0]?.id || '';
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const r = await api<{ slug: string }>('/edit/articles', { method: 'POST', json: { title, sectionId: section } });
|
||||
navigate(`/edit/${r.slug}`, { replace: true });
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Не удалось создать статью');
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
</div>
|
||||
<h1 className="cheat-title">Новая статья</h1>
|
||||
{!isEditor ? (
|
||||
<Notice title="Недостаточно прав">Создавать статьи могут редакторы и администраторы.</Notice>
|
||||
) : (
|
||||
<form className="login-form" onSubmit={submit}>
|
||||
<label className="field">
|
||||
<span className="field-label">Название</span>
|
||||
<input className="field-input field-input--box" required minLength={2} autoFocus value={title} onChange={(e) => setTitle(e.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span className="field-label">Раздел</span>
|
||||
<select className="field-input field-input--box" value={section} onChange={(e) => setSectionId(e.target.value)}>
|
||||
{nav.allSections.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
{error ? (
|
||||
<div className="form-error" role="alert">
|
||||
{error}
|
||||
</div>
|
||||
) : null}
|
||||
<button type="submit" className="btn btn--solid btn--xl" disabled={busy || !section}>
|
||||
Создать черновик
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { SectionOfflineCard } from '../components/Offline';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { BackLink, Notice, ThemeButton } from '../components/ui';
|
||||
import { cacheSupported } from '../lib/offline';
|
||||
import { useNav } from '../lib/tree';
|
||||
|
||||
export function OfflinePage() {
|
||||
const nav = useNav();
|
||||
return (
|
||||
<Screen tab="home">
|
||||
<div className="topline">
|
||||
<BackLink to="/">Главная</BackLink>
|
||||
<ThemeButton />
|
||||
</div>
|
||||
<h1 className="off-title">Офлайн-разделы</h1>
|
||||
<p className="cheat-intro">Скачайте разделы заранее: в подвалах и паркингах связи часто нет.</p>
|
||||
{!cacheSupported() ? (
|
||||
<Notice title="Браузер не поддерживает офлайн">
|
||||
Откройте сайт по https в обычной вкладке Chrome или Safari.
|
||||
</Notice>
|
||||
) : (
|
||||
nav.sections.map((s) => <SectionOfflineCard key={s.id} section={s} />)
|
||||
)}
|
||||
<p className="off-note">
|
||||
Главная, шпаргалка и статьи, которые вы уже открывали, сохраняются сами. Исходные PDF офлайн недоступны.
|
||||
</p>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +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 { Notice } from '../components/ui';
|
||||
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>))}</>;
|
||||
}
|
||||
|
||||
// Поиск появится на этапе 4.
|
||||
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">
|
||||
<Notice title="Поиск">Скоро здесь будет поиск по цифрам, артикулам и словам.</Notice>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { plural } from '@kb/shared';
|
||||
import { SectionOfflineRow } from '../components/Offline';
|
||||
import { Screen } from '../components/Shell';
|
||||
import { cacheSupported } from '../lib/offline';
|
||||
import { BackLink, Notice, Plaque, Skeleton, ThemeButton } from '../components/ui';
|
||||
import { num2 } from '../lib/format';
|
||||
import { articleHref, useNav } from '../lib/tree';
|
||||
@@ -42,8 +44,7 @@ export function SectionPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Сюда на этапе 5 встаёт строка «Сохранено для офлайна» */}
|
||||
<div id="section-offline-slot" data-section={section.id} />
|
||||
{cacheSupported() ? <SectionOfflineRow section={section} /> : null}
|
||||
|
||||
<div className="art-cards">
|
||||
{section.articles.map((a, i) => (
|
||||
@@ -51,6 +52,7 @@ export function SectionPage() {
|
||||
<div className="art-card-head">
|
||||
<span className="art-card-n">{num2(i + 1)}</span>
|
||||
<span className="art-card-title">{nav.short(a)}</span>
|
||||
{a.status === 'DRAFT' ? <span className="badge-draft">Черновик</span> : null}
|
||||
</div>
|
||||
{a.summary ? <div className="art-card-text">{a.summary}</div> : null}
|
||||
{a.tags.length ? (
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
/* Админка (макеты 07 и D7). */
|
||||
|
||||
.adm-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-10);
|
||||
}
|
||||
.adm-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-10);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.adm-spaces {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
|
||||
gap: var(--sp-5);
|
||||
}
|
||||
.adm-space {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
}
|
||||
.adm-space--on {
|
||||
border: 2px solid var(--ink);
|
||||
}
|
||||
.adm-space-pick {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-8) var(--sp-8) var(--sp-2);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.space-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: var(--r-tag);
|
||||
background: var(--brand);
|
||||
color: var(--brand-ink);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
}
|
||||
.adm-space-name {
|
||||
font-weight: 700;
|
||||
}
|
||||
.adm-space-n {
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.adm-link {
|
||||
flex: none;
|
||||
min-height: var(--tap-sm);
|
||||
padding: 0 var(--sp-6);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink2);
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 600;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.adm-space .adm-link {
|
||||
align-self: flex-start;
|
||||
padding-left: var(--sp-8);
|
||||
}
|
||||
.adm-add {
|
||||
min-height: 52px;
|
||||
border-radius: var(--r-btn);
|
||||
}
|
||||
|
||||
.adm-sec {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
min-height: var(--h-row);
|
||||
padding: var(--sp-2) var(--sp-3) var(--sp-2) var(--sp-2);
|
||||
background: var(--sf);
|
||||
}
|
||||
.adm-sec + .adm-sec {
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
/* Строка, которую тащат: жёлтая, как в макете */
|
||||
.adm-sec--drag {
|
||||
background: var(--brand);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
.adm-sec--drag .codetag {
|
||||
border-color: var(--brand-ink);
|
||||
}
|
||||
.adm-sec--drag .adm-link,
|
||||
.adm-sec--drag .adm-handle {
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
.adm-handle {
|
||||
flex: none;
|
||||
width: var(--tap-sm);
|
||||
height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink2);
|
||||
font-size: var(--fs-18);
|
||||
letter-spacing: -3px;
|
||||
cursor: grab;
|
||||
/* Палец на ручке двигает строку, а не прокручивает страницу */
|
||||
touch-action: none;
|
||||
}
|
||||
.adm-pos {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
opacity: 0.7;
|
||||
}
|
||||
.adm-sec-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-weight: 600;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
.adm-sec-n {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.adm-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-6);
|
||||
padding: var(--sp-7);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
}
|
||||
.adm-form-grow {
|
||||
flex: 1 1 200px;
|
||||
}
|
||||
.adm-form-short {
|
||||
flex: 0 0 96px;
|
||||
}
|
||||
.adm-form-wide,
|
||||
.adm-form-actions {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
.adm-form-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
.adm-danger {
|
||||
border-color: var(--redS);
|
||||
color: var(--red);
|
||||
}
|
||||
.adm-colors {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
.adm-color {
|
||||
min-width: var(--tap);
|
||||
height: var(--tap-sm);
|
||||
padding: 0 var(--sp-5);
|
||||
border: 2px solid transparent;
|
||||
border-radius: var(--r-plaque);
|
||||
color: var(--plq-ink-text);
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
}
|
||||
.adm-color.plaque--ink {
|
||||
color: var(--bg);
|
||||
}
|
||||
.adm-color--on {
|
||||
outline: 3px solid var(--ink);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.adm-user + .adm-user {
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
.adm-user--blocked .adm-user-main,
|
||||
.adm-user--blocked .avatar {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.adm-user-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-4) var(--sp-6);
|
||||
min-height: 68px;
|
||||
padding: var(--sp-4) var(--sp-7);
|
||||
}
|
||||
.adm-user-main {
|
||||
flex: 1 1 160px;
|
||||
min-width: 0;
|
||||
min-height: var(--tap-sm);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.adm-user-name {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.adm-user-sub {
|
||||
display: block;
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.adm-user-more {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
padding: 0 var(--sp-7) var(--sp-6);
|
||||
}
|
||||
.adm-user-more .adm-user-sub {
|
||||
flex: 1 1 100%;
|
||||
}
|
||||
.adm-roles {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: var(--sp-1);
|
||||
padding: 3px;
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf2);
|
||||
}
|
||||
.adm-roles--wide {
|
||||
align-self: flex-start;
|
||||
}
|
||||
.adm-role {
|
||||
height: var(--h-chip);
|
||||
padding: 0 var(--sp-5);
|
||||
border: 0;
|
||||
border-radius: 7px;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
.adm-role--on {
|
||||
background: var(--ink);
|
||||
color: var(--bg);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.adm-invite {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-5);
|
||||
padding: var(--sp-9);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
}
|
||||
.adm-invite-title {
|
||||
font-weight: 700;
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.adm-invite-text {
|
||||
font-size: var(--fs-15);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.adm-invite-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
padding-top: var(--sp-5);
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
.adm-invite-url {
|
||||
flex: 1 1 100%;
|
||||
min-width: 0;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf2);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-14);
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.adm-invite-meta {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.adm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1.25fr);
|
||||
gap: var(--sp-12);
|
||||
align-items: start;
|
||||
}
|
||||
}
|
||||
@@ -1976,3 +1976,562 @@ img {
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
/* ---------- Экран поиска ---------- */
|
||||
.search-top {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 4;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-6);
|
||||
margin: calc(var(--sp-6) * -1) calc(var(--sp-8) * -1) 0;
|
||||
padding: calc(var(--sp-6) + env(safe-area-inset-top)) var(--sp-8) var(--sp-6);
|
||||
background: var(--bg);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
}
|
||||
.search-top .search-field {
|
||||
box-shadow: 0 0 0 var(--focus-ring) var(--hl);
|
||||
}
|
||||
.search-top .chips--scroll {
|
||||
margin-bottom: calc(var(--sp-2) * -1);
|
||||
}
|
||||
mark {
|
||||
background: var(--hl);
|
||||
color: var(--brand-ink);
|
||||
border-radius: var(--r-plaque);
|
||||
}
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
clip-path: inset(50%);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.search-empty-title {
|
||||
font-size: var(--fs-20);
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
}
|
||||
.search-empty-text {
|
||||
font-size: var(--fs-16);
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.search-offline {
|
||||
padding: var(--sp-5) var(--sp-7);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--ambbg);
|
||||
border: var(--bw) solid var(--ambln);
|
||||
color: var(--amb);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
}
|
||||
.hint-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--sp-6);
|
||||
width: 100%;
|
||||
min-height: var(--h-row-sm);
|
||||
padding: 0 var(--sp-8);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--ink);
|
||||
}
|
||||
.hint-row + .hint-row {
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
.hint-row-q {
|
||||
font-size: var(--fs-17);
|
||||
font-weight: 700;
|
||||
}
|
||||
.hint-row-d {
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.fact-card,
|
||||
.result-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--sp-7) var(--sp-8);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
text-decoration: none;
|
||||
min-width: 0;
|
||||
}
|
||||
.fact-card {
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
.result-card {
|
||||
gap: var(--sp-2);
|
||||
}
|
||||
.fact-card-value {
|
||||
font-size: var(--fs-24);
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-tight);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.fact-card-label {
|
||||
font-size: var(--fs-16);
|
||||
line-height: 1.35;
|
||||
}
|
||||
.result-card-sec {
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
.result-card-title {
|
||||
font-size: var(--fs-18);
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
.result-card-snip {
|
||||
font-size: var(--fs-15);
|
||||
color: var(--ink2);
|
||||
line-height: 1.4;
|
||||
}
|
||||
@media (min-width: 1024px) {
|
||||
.search-top {
|
||||
margin: calc(var(--sp-20) * -1) 0 0;
|
||||
padding: var(--sp-20) 0 var(--sp-6);
|
||||
}
|
||||
.search-top .chips--scroll {
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Офлайн ---------- */
|
||||
.offline-banner {
|
||||
display: flex;
|
||||
gap: var(--sp-6);
|
||||
align-items: flex-start;
|
||||
padding: calc(var(--sp-6) + env(safe-area-inset-top)) var(--sp-8) var(--sp-6);
|
||||
background: var(--brand);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
.offline-banner + .screen {
|
||||
padding-top: var(--sp-6);
|
||||
}
|
||||
.offline-banner-title {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
.offline-banner-text {
|
||||
display: block;
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.warn-tri {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 0;
|
||||
height: 0;
|
||||
margin-top: var(--sp-1);
|
||||
border-left: 12px solid transparent;
|
||||
border-right: 12px solid transparent;
|
||||
border-bottom: 20px solid var(--brand-ink);
|
||||
}
|
||||
.warn-tri::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: -2px;
|
||||
top: 6px;
|
||||
width: 4px;
|
||||
height: 8px;
|
||||
background: var(--brand);
|
||||
}
|
||||
.progress {
|
||||
display: block;
|
||||
height: 4px;
|
||||
margin-top: var(--sp-3);
|
||||
border-radius: var(--r-xs);
|
||||
background: var(--sf2);
|
||||
overflow: hidden;
|
||||
}
|
||||
.progress span {
|
||||
display: block;
|
||||
height: 100%;
|
||||
background: var(--grnS);
|
||||
transition: width 0.2s;
|
||||
}
|
||||
.progress--lg {
|
||||
height: 10px;
|
||||
margin: 0;
|
||||
border-radius: 5px;
|
||||
border: var(--bw) solid var(--ln);
|
||||
}
|
||||
.off-title {
|
||||
font-size: var(--fs-24);
|
||||
font-weight: 700;
|
||||
}
|
||||
.off-note {
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.off-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-5);
|
||||
padding: var(--sp-7);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-card);
|
||||
background: var(--sf);
|
||||
}
|
||||
.off-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-6);
|
||||
}
|
||||
.off-card-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-weight: 700;
|
||||
line-height: var(--lh-snug);
|
||||
}
|
||||
.off-card-size,
|
||||
.off-card-pct {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.off-card-done {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
min-height: var(--h-chip);
|
||||
color: var(--grn);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.off-card-loading {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
}
|
||||
.off-card-btn {
|
||||
min-height: 52px;
|
||||
border-radius: var(--r-btn);
|
||||
font-size: var(--fs-16);
|
||||
white-space: normal;
|
||||
}
|
||||
.btn--lg.btn--block {
|
||||
white-space: normal;
|
||||
}
|
||||
@media (min-width: 1024px) {
|
||||
.home-more {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Вход ---------- */
|
||||
.splash {
|
||||
min-height: 100dvh;
|
||||
background: var(--bg);
|
||||
}
|
||||
.hazard {
|
||||
height: 10px;
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 10px, var(--brand-ink) 10px 20px);
|
||||
}
|
||||
.hazard--lg {
|
||||
height: calc(14px + env(safe-area-inset-top));
|
||||
background: repeating-linear-gradient(-45deg, var(--brand) 0 12px, var(--brand-ink) 12px 24px);
|
||||
}
|
||||
.login {
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
.login-main {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
gap: var(--sp-9);
|
||||
padding: var(--sp-12) var(--sp-10);
|
||||
}
|
||||
.login-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-9);
|
||||
}
|
||||
.login-site {
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.login-title {
|
||||
font-size: var(--fs-32);
|
||||
font-weight: 700;
|
||||
line-height: 1.05;
|
||||
letter-spacing: -0.02em;
|
||||
margin-top: var(--sp-3);
|
||||
}
|
||||
.login-note {
|
||||
font-size: var(--fs-16);
|
||||
color: var(--ink2);
|
||||
line-height: var(--lh-normal);
|
||||
}
|
||||
.login-link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
}
|
||||
.field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.field-label {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.field-box,
|
||||
.field-input--box {
|
||||
height: var(--h-field);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-box {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 0 var(--sp-3) 0 var(--sp-8);
|
||||
}
|
||||
.field-box:focus-within,
|
||||
.field-input--box:focus {
|
||||
box-shadow: 0 0 0 var(--focus-ring) var(--hl);
|
||||
outline: 0;
|
||||
}
|
||||
.field-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.field-input--box {
|
||||
flex: none;
|
||||
padding: 0 var(--sp-8);
|
||||
border: 2px solid var(--ink);
|
||||
background: var(--sf);
|
||||
}
|
||||
.field-input::placeholder {
|
||||
color: var(--ink2);
|
||||
}
|
||||
.field-toggle {
|
||||
flex: none;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-6);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
color: var(--ink2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.remember {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-7);
|
||||
min-height: var(--h-btn);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
color: var(--ink);
|
||||
}
|
||||
.remember-title {
|
||||
display: block;
|
||||
font-weight: 700;
|
||||
}
|
||||
.remember-text {
|
||||
display: block;
|
||||
font-size: var(--fs-14);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.bigbox {
|
||||
flex: none;
|
||||
position: relative;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--sf);
|
||||
}
|
||||
.bigbox--on {
|
||||
border-color: var(--grnS);
|
||||
background: var(--grnS);
|
||||
}
|
||||
.bigbox--on::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 9px;
|
||||
top: 3px;
|
||||
width: 8px;
|
||||
height: 15px;
|
||||
border: solid var(--on-strong);
|
||||
border-width: 0 3px 3px 0;
|
||||
transform: rotate(45deg);
|
||||
}
|
||||
.form-error {
|
||||
padding: var(--sp-6) var(--sp-7);
|
||||
border: 2px solid var(--redS);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- Блок пользователя ---------- */
|
||||
.avatar {
|
||||
flex: none;
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
background: var(--sf2);
|
||||
border: var(--bw) solid var(--ln);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: var(--fs-14);
|
||||
font-weight: 700;
|
||||
}
|
||||
.usermenu-btn {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
font-size: inherit;
|
||||
}
|
||||
.usermenu-link {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin: calc(var(--sp-4) * -1) calc(var(--sp-4) * -1) var(--sp-2);
|
||||
}
|
||||
.usermenu--compact .list-row {
|
||||
min-height: var(--h-chip);
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border: 0;
|
||||
border-radius: var(--r-sm);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.usermenu--compact .usermenu-who {
|
||||
min-height: var(--h-row-sm);
|
||||
}
|
||||
.usermenu--compact .avatar {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
}
|
||||
.badge-draft {
|
||||
flex: none;
|
||||
padding: var(--sp-1) var(--sp-4);
|
||||
border-radius: var(--r-tag);
|
||||
border: var(--bw) solid var(--ambln);
|
||||
background: var(--ambbg);
|
||||
color: var(--amb);
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
}
|
||||
.topline-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
|
||||
/* ---------- Переключатель пространства ---------- */
|
||||
.space-pick {
|
||||
min-height: 52px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
padding: 0 var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--sf2);
|
||||
}
|
||||
.space-pick-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.space-pick-icon {
|
||||
flex: none;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: var(--r-tag);
|
||||
background: var(--brand);
|
||||
color: var(--brand-ink);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-weight: 700;
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.space-pick-label {
|
||||
display: block;
|
||||
font-size: 0.6875rem;
|
||||
color: var(--ink2);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--caps);
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.space-pick-name,
|
||||
.space-pick-select {
|
||||
display: block;
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.space-pick-select {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
}
|
||||
.space-pick-select option {
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
}
|
||||
@media (min-width: 1024px) {
|
||||
.sidebar .space-pick {
|
||||
margin: 0 var(--sp-6) var(--sp-6);
|
||||
}
|
||||
.home-space {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,443 @@
|
||||
/* Редактор статьи (макеты 06 и D6) и общие поля форм админки. */
|
||||
|
||||
.ed-wrap {
|
||||
max-width: 560px;
|
||||
margin: 0 auto;
|
||||
padding: var(--sp-12) var(--sp-8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-8);
|
||||
}
|
||||
|
||||
.ed {
|
||||
height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.ed-head {
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
padding: calc(var(--sp-1) + env(safe-area-inset-top)) var(--sp-8) var(--sp-1) var(--sp-4);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-back {
|
||||
flex: none;
|
||||
min-width: var(--tap-sm);
|
||||
min-height: var(--tap);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-24);
|
||||
cursor: pointer;
|
||||
}
|
||||
.ed-head-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.ed-title {
|
||||
font-size: var(--fs-16);
|
||||
font-weight: 700;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ed-status {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ed-only-desk {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ed-tabs {
|
||||
flex: none;
|
||||
margin: var(--sp-4) var(--sp-8) 0;
|
||||
}
|
||||
.ed-tabs + .ed-toolbar {
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-head,
|
||||
.ed-tabs {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.ed-toolbar {
|
||||
flex: none;
|
||||
display: flex;
|
||||
gap: var(--sp-3);
|
||||
overflow-x: auto;
|
||||
padding: var(--sp-5) var(--sp-8);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
.ed-toolbar::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.ed-tool {
|
||||
flex: none;
|
||||
height: var(--tap);
|
||||
padding: 0 var(--sp-7);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-4);
|
||||
}
|
||||
.ed-tool-dot {
|
||||
flex: none;
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 2px;
|
||||
}
|
||||
.ed-error {
|
||||
flex: none;
|
||||
margin: var(--sp-4) var(--sp-8) 0;
|
||||
}
|
||||
|
||||
.ed-cols {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
}
|
||||
.ed-col {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
}
|
||||
.ed-cols--text .ed-col--text,
|
||||
.ed-cols--preview .ed-col--preview,
|
||||
.ed-cols--meta .ed-col--meta {
|
||||
display: flex;
|
||||
}
|
||||
.ed-col--text,
|
||||
.ed-col--meta {
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-col-head {
|
||||
display: none;
|
||||
}
|
||||
.cm-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.cm-host .cm-editor {
|
||||
height: 100%;
|
||||
}
|
||||
.ed-preview {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-8);
|
||||
}
|
||||
.ed-preview-phone {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-8);
|
||||
}
|
||||
.ed-preview .kb-link--broken {
|
||||
border-color: var(--redS);
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.ed-meta {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: var(--sp-9);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-7);
|
||||
}
|
||||
.ed-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-3);
|
||||
min-width: 0;
|
||||
}
|
||||
.ed-label {
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
}
|
||||
.ed-input {
|
||||
width: 100%;
|
||||
min-height: var(--tap-sm);
|
||||
padding: var(--sp-4) var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--sf);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-15);
|
||||
}
|
||||
.ed-input--area {
|
||||
resize: vertical;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.ed-chips {
|
||||
display: flex;
|
||||
gap: var(--sp-2);
|
||||
flex-wrap: wrap;
|
||||
padding: var(--sp-3);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.ed-chip {
|
||||
padding: var(--sp-2) var(--sp-4);
|
||||
border: 0;
|
||||
border-radius: var(--r-tag);
|
||||
background: var(--sf2);
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-13);
|
||||
cursor: pointer;
|
||||
min-height: 32px;
|
||||
}
|
||||
.ed-chips-input {
|
||||
flex: 1;
|
||||
min-width: 90px;
|
||||
min-height: 32px;
|
||||
padding: 0 var(--sp-4);
|
||||
border: 0;
|
||||
outline: 0;
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
font-size: var(--fs-13);
|
||||
}
|
||||
.ed-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
min-height: var(--tap-sm);
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 600;
|
||||
}
|
||||
.ed-check input {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
accent-color: var(--grnS);
|
||||
}
|
||||
.ed-file {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
padding: var(--sp-5) var(--sp-6);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
}
|
||||
.ed-file-ext {
|
||||
flex: none;
|
||||
font-size: 0.6875rem;
|
||||
font-weight: 700;
|
||||
padding: var(--sp-3) var(--sp-2);
|
||||
border: 2px solid var(--ink);
|
||||
border-radius: var(--r-plaque);
|
||||
}
|
||||
.ed-file-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-13);
|
||||
word-break: break-all;
|
||||
}
|
||||
.ed-file-del {
|
||||
flex: none;
|
||||
width: var(--tap-sm);
|
||||
height: var(--tap-sm);
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--ink2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.ed-drop {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--sp-2);
|
||||
min-height: 96px;
|
||||
padding: var(--sp-6);
|
||||
border: 2px dashed var(--ln);
|
||||
border-radius: var(--r-btn);
|
||||
text-align: center;
|
||||
}
|
||||
.ed-drop-title {
|
||||
font-size: var(--fs-15);
|
||||
font-weight: 700;
|
||||
}
|
||||
.ed-drop-text {
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
|
||||
.ed-foot {
|
||||
flex: none;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1.4fr;
|
||||
gap: var(--sp-4);
|
||||
padding: var(--sp-5) var(--sp-8) calc(var(--sp-8) + env(safe-area-inset-bottom));
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: var(--sf);
|
||||
}
|
||||
|
||||
/* История версий */
|
||||
.rev-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-5);
|
||||
width: 100%;
|
||||
min-height: var(--tap);
|
||||
padding: var(--sp-5) var(--sp-9);
|
||||
border: 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.rev-row--on {
|
||||
background: var(--sf2);
|
||||
box-shadow: inset 4px 0 0 var(--hl);
|
||||
}
|
||||
.rev-v {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
font-weight: 700;
|
||||
}
|
||||
.rev-main {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.rev-date {
|
||||
flex: none;
|
||||
font-size: var(--fs-13);
|
||||
color: var(--ink2);
|
||||
}
|
||||
.rev-diff {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--sp-6);
|
||||
padding: var(--sp-6) var(--sp-9) 0;
|
||||
border-top: var(--bw) solid var(--ln);
|
||||
}
|
||||
.diff {
|
||||
margin: 0;
|
||||
max-height: 40dvh;
|
||||
overflow: auto;
|
||||
padding: var(--sp-5);
|
||||
border: var(--bw) solid var(--ln);
|
||||
border-radius: var(--r-md);
|
||||
background: var(--bg);
|
||||
font-family: var(--font);
|
||||
font-size: var(--fs-13);
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.diff-line {
|
||||
display: block;
|
||||
}
|
||||
.diff-line--add {
|
||||
background: var(--grnbg);
|
||||
color: var(--grn);
|
||||
}
|
||||
.diff-line--del {
|
||||
background: var(--redbg);
|
||||
color: var(--red);
|
||||
text-decoration: line-through;
|
||||
}
|
||||
.diff-line--skip {
|
||||
color: var(--ink2);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ---------- Компьютер: три колонки ---------- */
|
||||
@media (min-width: 1024px) {
|
||||
.ed-head {
|
||||
gap: var(--sp-6);
|
||||
height: 68px;
|
||||
padding: 0 var(--sp-12);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
}
|
||||
.ed-title {
|
||||
font-size: var(--fs-18);
|
||||
}
|
||||
.ed-status {
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.ed-only-desk {
|
||||
display: inline-flex;
|
||||
}
|
||||
.ed-tabs,
|
||||
.ed-foot {
|
||||
display: none;
|
||||
}
|
||||
.ed-toolbar {
|
||||
flex-wrap: wrap;
|
||||
padding: var(--sp-5) var(--sp-12);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-tool {
|
||||
height: var(--h-chip);
|
||||
padding: 0 var(--sp-6);
|
||||
border-radius: 9px;
|
||||
font-size: var(--fs-14);
|
||||
}
|
||||
.ed-error {
|
||||
margin: var(--sp-4) var(--sp-12) 0;
|
||||
}
|
||||
.ed-cols {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) 320px;
|
||||
}
|
||||
.ed-col,
|
||||
.ed-cols .ed-col {
|
||||
display: flex;
|
||||
border-right: var(--bw) solid var(--ln);
|
||||
}
|
||||
.ed-col--meta {
|
||||
border-right: 0;
|
||||
}
|
||||
.ed-col-head {
|
||||
display: block;
|
||||
flex: none;
|
||||
padding: var(--sp-4) var(--sp-10);
|
||||
font-size: var(--fs-12);
|
||||
font-weight: 700;
|
||||
color: var(--ink2);
|
||||
border-bottom: var(--bw) solid var(--ln);
|
||||
background: var(--sf);
|
||||
}
|
||||
.ed-preview {
|
||||
padding: var(--sp-10);
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
}
|
||||
.ed-preview-phone {
|
||||
width: 390px;
|
||||
max-width: 100%;
|
||||
}
|
||||
.ed .sheet-wrap {
|
||||
left: 0;
|
||||
}
|
||||
.ed .scrim {
|
||||
left: 0;
|
||||
}
|
||||
.ed .sheet {
|
||||
width: 640px;
|
||||
}
|
||||
}
|
||||
+62
-1
@@ -1,8 +1,69 @@
|
||||
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] },
|
||||
// Если в фоне пришла новая версия, сообщаем странице: она перерисует данные (см. main.tsx)
|
||||
broadcastUpdate: { channelName: 'kb-api-updates', options: { headersToCheck: ['etag'] } },
|
||||
expiration: { maxEntries: 600 },
|
||||
},
|
||||
},
|
||||
{
|
||||
// Картинки статей: так же
|
||||
urlPattern: ({ url }) => url.pathname.startsWith('/uploads/') && url.pathname.endsWith('.webp'),
|
||||
handler: 'StaleWhileRevalidate',
|
||||
options: {
|
||||
cacheName: 'kb-img',
|
||||
cacheableResponse: { statuses: [200] },
|
||||
expiration: { maxEntries: 3000, purgeOnQuotaError: true },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
],
|
||||
server: {
|
||||
port: 5180,
|
||||
// В разработке запросы к API и картинкам уходят на локальный сервер API
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Боевой запуск: docker compose -f docker-compose.prod.yml up -d --build
|
||||
# Перед запуском заполните .env (см. .env.example и DEPLOY.md).
|
||||
#
|
||||
# Отличия от docker-compose.yml:
|
||||
# - БД не видна снаружи (нет проброса порта);
|
||||
# - сайт слушает только 127.0.0.1: наружу его отдаёт Nginx Proxy Manager по https;
|
||||
# - секреты обязательны: без них compose не стартует;
|
||||
# - cookie только по https (COOKIE_SECURE=true).
|
||||
name: wiki-montazh
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:16-alpine
|
||||
restart: always
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:?Задайте POSTGRES_USER в .env}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Задайте POSTGRES_PASSWORD в .env}
|
||||
POSTGRES_DB: ${POSTGRES_DB:?Задайте POSTGRES_DB в .env}
|
||||
volumes:
|
||||
- db_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/api/Dockerfile
|
||||
restart: always
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?schema=public
|
||||
PUBLIC_URL: ${PUBLIC_URL:?Задайте PUBLIC_URL в .env, например https://wiki.suchtech.ru}
|
||||
SESSION_SECRET: ${SESSION_SECRET:?Задайте SESSION_SECRET в .env}
|
||||
COOKIE_SECURE: "true"
|
||||
ADMIN_EMAIL: ${ADMIN_EMAIL:-}
|
||||
ADMIN_PASSWORD: ${ADMIN_PASSWORD:-}
|
||||
ADMIN_NAME: ${ADMIN_NAME:-Администратор}
|
||||
volumes:
|
||||
- uploads:/data/uploads
|
||||
- ./kb-seed:/kb-seed:ro
|
||||
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/web/Dockerfile
|
||||
restart: always
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
ports:
|
||||
# Если Nginx Proxy Manager работает в Docker на этом же сервере, замените 127.0.0.1
|
||||
# на адрес docker-моста (обычно 172.17.0.1) или подключите web к сети NPM (см. DEPLOY.md).
|
||||
- "${WEB_BIND:-127.0.0.1}:${WEB_PORT:-8200}:80"
|
||||
|
||||
volumes:
|
||||
db_data:
|
||||
uploads:
|
||||
+5
-1
@@ -28,6 +28,10 @@ export default tseslint.config(
|
||||
{
|
||||
files: ['apps/web/**/*.{ts,tsx}'],
|
||||
plugins: { 'react-hooks': reactHooks },
|
||||
rules: { ...reactHooks.configs.recommended.rules },
|
||||
rules: {
|
||||
...reactHooks.configs.recommended.rules,
|
||||
// Правило для React Compiler, которым проект не пользуется
|
||||
'react-hooks/preserve-manual-memoization': 'off',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -23,3 +23,9 @@
|
||||
- Длинные абзацы превращены в **чек-листы** (галочки при работе).
|
||||
- Отдельная **шпаргалка** со всеми цифрами и запретами на одном экране.
|
||||
- Перекрёстные ссылки между статьями: `[[slug]]`.
|
||||
|
||||
## Замечания при импорте на сайт (добавлено при разработке)
|
||||
|
||||
- **Шапки статей не являются строгим YAML.** В `razmeshenie-oborudovaniya.md` значение `summary` содержит двоеточие («Карта стойки: верх — …»), в `uzel-fotoelementa.md` в списке `equipment` есть запятая внутри значения («уголок 130х130х100х1,8»). Тексты не менялись: импорт разбирает шапку по своим правилам (ключ отделяется первым двоеточием, список делится по «запятая + пробел»). Если статьи будут править в сторонних редакторах, такие значения лучше брать в кавычки.
|
||||
- **Шифр документа указан не везде.** `doc_code` есть у 4 статей из 12; у остальных на сайте строка «Шифр» не показывается. Если шифры существуют, стоит дописать.
|
||||
- **Версии и даты.** В исходниках нет номера версии и даты документа, поэтому на сайте у всех статей «v1» и дата импорта. Реальные даты утверждения документов нужно уточнить у заказчика.
|
||||
|
||||
@@ -104,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 {
|
||||
@@ -174,15 +177,22 @@ export function normalizeSearch(s: string): string {
|
||||
// \p{Zs}: все виды пробелов, включая неразрывный и узкий
|
||||
.replace(/\p{Zs}/gu, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
// Десятичная точка → запятая: «2.5» и «2,5» ищутся одинаково
|
||||
.replace(/(\d)\.(?=\d)/g, '$1,')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* «Сжатый» вид: только буквы и цифры. Так «MG12» находит «MG-12»,
|
||||
* «Сжатый» вид: только буквы и цифры (и запятая внутри числа). Так «MG12» находит «MG-12»,
|
||||
* а «ral7024» находит «RAL 7024».
|
||||
*/
|
||||
export function compactSearch(s: string): string {
|
||||
return normalizeSearch(s).replace(/[^\p{L}\p{N}]+/gu, '');
|
||||
return (
|
||||
normalizeSearch(s)
|
||||
.replace(/[^\p{L}\p{N},]+/gu, '')
|
||||
// Запятую оставляем только между цифрами: «1,2 м» не должно совпасть с «12 мм»
|
||||
.replace(/(?<!\d),|,(?!\d)/g, '')
|
||||
);
|
||||
}
|
||||
|
||||
/** Короткое название статьи для меню: без «Название раздела — » в начале. */
|
||||
|
||||
Generated
+227
@@ -108,6 +108,21 @@ importers:
|
||||
|
||||
apps/web:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete':
|
||||
specifier: ^6.20.3
|
||||
version: 6.20.3
|
||||
'@codemirror/lang-markdown':
|
||||
specifier: ^6.5.2
|
||||
version: 6.5.2
|
||||
'@codemirror/language':
|
||||
specifier: ^6.12.4
|
||||
version: 6.12.4
|
||||
'@codemirror/state':
|
||||
specifier: ^6.7.6
|
||||
version: 6.7.6
|
||||
'@codemirror/view':
|
||||
specifier: ^6.43.13
|
||||
version: 6.43.13
|
||||
'@fontsource-variable/onest':
|
||||
specifier: ^5.3.1
|
||||
version: 5.3.1
|
||||
@@ -117,9 +132,15 @@ importers:
|
||||
'@kb/shared':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/shared
|
||||
'@lezer/highlight':
|
||||
specifier: ^1.2.5
|
||||
version: 1.2.5
|
||||
'@tanstack/react-query':
|
||||
specifier: ^5.104.1
|
||||
version: 5.104.1(react@19.3.0)
|
||||
codemirror:
|
||||
specifier: ^6.0.2
|
||||
version: 6.0.2
|
||||
qrcode-generator:
|
||||
specifier: ^2.0.4
|
||||
version: 2.0.4
|
||||
@@ -716,6 +737,39 @@ packages:
|
||||
'@cacheable/utils@2.5.0':
|
||||
resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
resolution: {integrity: sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==}
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
resolution: {integrity: sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==}
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
resolution: {integrity: sha512-kr5fwBGiGtmz6l0LSJIbno9QrifNMUusivHbnA1H6Dmqy4HZFte3UAICix1VuKo0lMPKQr2rqB+0BkKi/S3Ejg==}
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
resolution: {integrity: sha512-pw2ReWKUqSkbvh76RAT4NYxiogRu+PWkR2ukAwO9uOgrm8uipkzjtKKtNpyeAQwHOqxEeSvAXZ6vr3AfyB9y/w==}
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
resolution: {integrity: sha512-zD4e5mS+50htS7F+TYjBPsiIFGanfVqg4HyUz6WNFikgOPf2BgKlx+TQedI1w6n/IqRBVBbBWmGFdLB/7uxO4A==}
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
resolution: {integrity: sha512-AwBOdkWYuA//WcM0xO5PfHPUcmz/O2i5o0Nsg1U69SII/loCJlFI1Romd9xp2HYb1kYJRGZotyqRghuHH5n8Kw==}
|
||||
|
||||
'@codemirror/language@6.12.4':
|
||||
resolution: {integrity: sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==}
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
resolution: {integrity: sha512-28/+iWLYxKxsvGYhSYL7zaCZqLz5+FFFDq9tVsvGv9kv8RY4fFAchJ5WX9M3YrrRlTIsECjsXPqeNgnSmNP2dg==}
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
resolution: {integrity: sha512-gUYkYhT2+n/+VGZ+8EzE5WFkYZUZYm1VOKDudIsNqh42uRVQJ0a6Yss9sdKT3MeOYfuL1N6AZA57oza0Oyr0LA==}
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
resolution: {integrity: sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==}
|
||||
|
||||
'@codemirror/view@6.43.13':
|
||||
resolution: {integrity: sha512-sihaFrUzAsYBQsL9J2t69y8nfMQGwcYmggAZsk+kjPbjYZMyuf2hU8tUNTZ+P+isb6XRr8JE22TZlJxBoVdH1A==}
|
||||
|
||||
'@emnapi/runtime@1.11.3':
|
||||
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
|
||||
|
||||
@@ -1274,6 +1328,30 @@ packages:
|
||||
'@keyv/serialize@1.1.1':
|
||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
||||
|
||||
'@lezer/common@1.5.3':
|
||||
resolution: {integrity: sha512-H0iErY4e43LpXbYDyBci5W4v/RwTgGV3YzYOlJPiGZ8RY8w51kVE+xLn1tg3Z6UmSfyETvtsUK3r7YsgDQEI7Q==}
|
||||
|
||||
'@lezer/css@1.3.8':
|
||||
resolution: {integrity: sha512-EJn1zcL9qoDptief6ipWKZKLiOpXkxSe0+t8CH9oiMVcZlq7NBWrjCqnc/41EIjeo/ITj1gFFiATdTkaJDL+Og==}
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
resolution: {integrity: sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==}
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
resolution: {integrity: sha512-oI7n6NJml729m7pjm9lvLvmXbdoMoi2f+1pwSDJkl9d68zGr7a9Btz8NdHTGQZtW2DA25ybeuv/SyDb9D5tseg==}
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
resolution: {integrity: sha512-sEvOqpl4vJQca0NugSQK02vQPbc5KrvoojnYGoqqFgFO0MtcYhwGiHKVEB+LuXYJnfyXo4QPA8ztbrEa4Fw5NA==}
|
||||
|
||||
'@lezer/lr@1.4.10':
|
||||
resolution: {integrity: sha512-rnCpTIBafOx4mRp43xOxDJbFipJm/c0cia/V5TiGlhmMa+wsSdoGmUN3w5Bqrks/09Q/D4tNAmWaT8p6NRi77A==}
|
||||
|
||||
'@lezer/markdown@1.7.2':
|
||||
resolution: {integrity: sha512-iTkYvoVcKt3WkeL7qUDyXHONZEwLio4wj8KTNi2dnjQEXBZKMV63BpQrPqfsM+OkvuRbiSTAcycYAsQzLhRNoQ==}
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4':
|
||||
resolution: {integrity: sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==}
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||
@@ -1958,6 +2036,9 @@ packages:
|
||||
citty@0.2.2:
|
||||
resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==}
|
||||
|
||||
codemirror@6.0.2:
|
||||
resolution: {integrity: sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==}
|
||||
|
||||
comma-separated-tokens@2.0.3:
|
||||
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
|
||||
|
||||
@@ -2027,6 +2108,9 @@ packages:
|
||||
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
|
||||
engines: {node: '>= 0.10'}
|
||||
|
||||
crelt@1.0.7:
|
||||
resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==}
|
||||
|
||||
cross-env@10.1.0:
|
||||
resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==}
|
||||
engines: {node: '>=20'}
|
||||
@@ -3484,6 +3568,9 @@ packages:
|
||||
resolution: {integrity: sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw==}
|
||||
engines: {node: '>=10'}
|
||||
|
||||
style-mod@4.1.4:
|
||||
resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==}
|
||||
|
||||
sucrase@3.35.1:
|
||||
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
|
||||
engines: {node: '>=16 || 14 >=14.17'}
|
||||
@@ -3797,6 +3884,9 @@ packages:
|
||||
jsdom:
|
||||
optional: true
|
||||
|
||||
w3c-keyname@2.2.8:
|
||||
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||
|
||||
which-boxed-primitive@1.1.1:
|
||||
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -4581,6 +4671,92 @@ snapshots:
|
||||
hashery: 1.5.1
|
||||
keyv: 5.6.0
|
||||
|
||||
'@codemirror/autocomplete@6.20.3':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/commands@6.11.1':
|
||||
dependencies:
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@codemirror/lang-css@6.3.1':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.8
|
||||
|
||||
'@codemirror/lang-html@6.4.12':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-css': 6.3.1
|
||||
'@codemirror/lang-javascript': 6.2.5
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/css': 1.3.8
|
||||
'@lezer/html': 1.3.13
|
||||
|
||||
'@codemirror/lang-javascript@6.2.5':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/javascript': 1.5.6
|
||||
|
||||
'@codemirror/lang-markdown@6.5.2':
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/lang-html': 6.4.12
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/markdown': 1.7.2
|
||||
|
||||
'@codemirror/language@6.12.4':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
style-mod: 4.1.4
|
||||
|
||||
'@codemirror/lint@6.9.7':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/search@6.7.2':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
crelt: 1.0.7
|
||||
|
||||
'@codemirror/state@6.7.6':
|
||||
dependencies:
|
||||
'@marijn/find-cluster-break': 1.0.4
|
||||
|
||||
'@codemirror/view@6.43.13':
|
||||
dependencies:
|
||||
'@codemirror/state': 6.7.6
|
||||
crelt: 1.0.7
|
||||
style-mod: 4.1.4
|
||||
w3c-keyname: 2.2.8
|
||||
|
||||
'@emnapi/runtime@1.11.3':
|
||||
dependencies:
|
||||
tslib: 2.8.1
|
||||
@@ -4936,6 +5112,41 @@ snapshots:
|
||||
|
||||
'@keyv/serialize@1.1.1': {}
|
||||
|
||||
'@lezer/common@1.5.3': {}
|
||||
|
||||
'@lezer/css@1.3.8':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/highlight@1.2.5':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/html@1.3.13':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/javascript@1.5.6':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
'@lezer/lr': 1.4.10
|
||||
|
||||
'@lezer/lr@1.4.10':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
|
||||
'@lezer/markdown@1.7.2':
|
||||
dependencies:
|
||||
'@lezer/common': 1.5.3
|
||||
'@lezer/highlight': 1.2.5
|
||||
|
||||
'@marijn/find-cluster-break@1.0.4': {}
|
||||
|
||||
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||
optional: true
|
||||
|
||||
@@ -5577,6 +5788,16 @@ snapshots:
|
||||
|
||||
citty@0.2.2: {}
|
||||
|
||||
codemirror@6.0.2:
|
||||
dependencies:
|
||||
'@codemirror/autocomplete': 6.20.3
|
||||
'@codemirror/commands': 6.11.1
|
||||
'@codemirror/language': 6.12.4
|
||||
'@codemirror/lint': 6.9.7
|
||||
'@codemirror/search': 6.7.2
|
||||
'@codemirror/state': 6.7.6
|
||||
'@codemirror/view': 6.43.13
|
||||
|
||||
comma-separated-tokens@2.0.3: {}
|
||||
|
||||
commander@2.20.3: {}
|
||||
@@ -5623,6 +5844,8 @@ snapshots:
|
||||
object-assign: 4.1.1
|
||||
vary: 1.1.2
|
||||
|
||||
crelt@1.0.7: {}
|
||||
|
||||
cross-env@10.1.0:
|
||||
dependencies:
|
||||
'@epic-web/invariant': 1.0.0
|
||||
@@ -7520,6 +7743,8 @@ snapshots:
|
||||
|
||||
strip-comments@2.0.1: {}
|
||||
|
||||
style-mod@4.1.4: {}
|
||||
|
||||
sucrase@3.35.1:
|
||||
dependencies:
|
||||
'@jridgewell/gen-mapping': 0.3.13
|
||||
@@ -7850,6 +8075,8 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
w3c-keyname@2.2.8: {}
|
||||
|
||||
which-boxed-primitive@1.1.1:
|
||||
dependencies:
|
||||
is-bigint: 1.1.0
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
# Резервная копия: дамп базы (pg_dump) + архив папки uploads (картинки и исходники).
|
||||
#
|
||||
# Запуск из папки проекта: ./scripts/backup.sh
|
||||
# Копии складываются в ./backups, старше KEEP_DAYS дней удаляются.
|
||||
#
|
||||
# Переменные (необязательные):
|
||||
# COMPOSE_FILE какой compose-файл использовать (по умолчанию docker-compose.prod.yml)
|
||||
# BACKUP_DIR куда класть копии (по умолчанию ./backups)
|
||||
# KEEP_DAYS сколько дней хранить (по умолчанию 14)
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.prod.yml}"
|
||||
BACKUP_DIR="${BACKUP_DIR:-./backups}"
|
||||
KEEP_DAYS="${KEEP_DAYS:-14}"
|
||||
STAMP="$(date +%Y-%m-%d_%H%M)"
|
||||
DC=(docker compose -f "$COMPOSE_FILE")
|
||||
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
# 1. База. Формат custom (-Fc): сжатый, восстанавливается через pg_restore.
|
||||
# Имя пользователя и базы берём из окружения контейнера, поэтому .env читать не нужно.
|
||||
"${DC[@]}" exec -T db sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" -Fc' > "$BACKUP_DIR/db_$STAMP.dump"
|
||||
|
||||
# 2. Загруженные файлы: архивируем прямо из контейнера api, где том смонтирован в /data/uploads
|
||||
"${DC[@]}" exec -T api sh -c 'tar -czf - -C /data uploads' > "$BACKUP_DIR/uploads_$STAMP.tar.gz"
|
||||
|
||||
# Пустой файл означает, что что-то пошло не так
|
||||
for f in "$BACKUP_DIR/db_$STAMP.dump" "$BACKUP_DIR/uploads_$STAMP.tar.gz"; do
|
||||
[ -s "$f" ] || { echo "Ошибка: пустой файл $f" >&2; exit 1; }
|
||||
done
|
||||
|
||||
# 3. Удаляем старые копии
|
||||
find "$BACKUP_DIR" -maxdepth 1 -type f \( -name 'db_*.dump' -o -name 'uploads_*.tar.gz' \) -mtime +"$KEEP_DAYS" -delete
|
||||
|
||||
echo "Готово: $BACKUP_DIR/db_$STAMP.dump ($(du -h "$BACKUP_DIR/db_$STAMP.dump" | cut -f1)), $BACKUP_DIR/uploads_$STAMP.tar.gz ($(du -h "$BACKUP_DIR/uploads_$STAMP.tar.gz" | cut -f1))"
|
||||
@@ -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,85 @@
|
||||
// Проверка прав на сервере: что может гость, читатель (VIEWER), редактор (EDITOR) и админ.
|
||||
// Создаёт временных пользователей через приглашения и удаляет их в конце.
|
||||
// Запуск: KB_EMAIL=админ KB_PASSWORD=пароль node scripts/check-roles.mjs [адрес сайта]
|
||||
const base = process.argv[2] ?? 'http://localhost:8200';
|
||||
const json = { 'X-Requested-With': 'kb', 'Content-Type': 'application/json' };
|
||||
let failed = 0;
|
||||
|
||||
async function call(method, path, { cookie, body } = {}) {
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
headers: { ...json, ...(cookie ? { Cookie: cookie } : {}) },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
const cookies = res.headers.getSetCookie?.().map((c) => c.split(';')[0]).join('; ');
|
||||
let data = null;
|
||||
try {
|
||||
data = await res.json();
|
||||
} catch {
|
||||
/* пустой ответ */
|
||||
}
|
||||
return { status: res.status, data, cookie: cookies };
|
||||
}
|
||||
|
||||
function expect(name, got, want) {
|
||||
const ok = Array.isArray(want) ? want.includes(got) : got === want;
|
||||
if (!ok) failed++;
|
||||
console.log(`${ok ? 'ok ' : 'FAIL'} ${name}: ${got}${ok ? '' : ` (ожидалось ${want})`}`);
|
||||
}
|
||||
|
||||
const admin = (await call('POST', '/api/auth/login', { body: { email: process.env.KB_EMAIL, password: process.env.KB_PASSWORD, remember: false } })).cookie;
|
||||
if (!admin) throw new Error('Не удалось войти админом: задайте KB_EMAIL и KB_PASSWORD');
|
||||
|
||||
// Пользователи с ролями через приглашения
|
||||
const stamp = Date.now();
|
||||
async function invited(role) {
|
||||
const inv = await call('POST', '/api/admin/invites', { cookie: admin, body: { role } });
|
||||
const reg = await call('POST', `/api/auth/invite/${inv.data.token}`, {
|
||||
body: { name: `Проверка ${role}`, email: `check-${role.toLowerCase()}-${stamp}@example.com`, password: 'check-password-1' },
|
||||
});
|
||||
return { cookie: reg.cookie, id: reg.data.user.id };
|
||||
}
|
||||
const viewer = await invited('VIEWER');
|
||||
const editor = await invited('EDITOR');
|
||||
|
||||
const tree = (await call('GET', '/api/tree', { cookie: admin })).data;
|
||||
const art = tree.articles.find((a) => !a.pinned);
|
||||
const edit = (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: admin })).data;
|
||||
const draftBody = { md: edit.md, meta: edit.meta };
|
||||
|
||||
console.log('--- гость');
|
||||
expect('дерево пустое', (await call('GET', '/api/tree')).data.articles.length, 0);
|
||||
expect('статья', (await call('GET', `/api/articles/${art.slug}`)).status, 401);
|
||||
expect('картинки', (await fetch(`${base}/uploads/assets/shkon/fig-1.webp`)).status, 401);
|
||||
expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { body: draftBody })).status, 401);
|
||||
expect('список пользователей', (await call('GET', '/api/admin/users')).status, 401);
|
||||
|
||||
console.log('--- читатель (VIEWER)');
|
||||
expect('статья', (await call('GET', `/api/articles/${art.slug}`, { cookie: viewer.cookie })).status, 200);
|
||||
expect('данные редактора', (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: viewer.cookie })).status, 403);
|
||||
expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { cookie: viewer.cookie, body: draftBody })).status, 403);
|
||||
expect('публикация', (await call('POST', `/api/edit/articles/${art.id}/publish`, { cookie: viewer.cookie, body: draftBody })).status, 403);
|
||||
expect('создание статьи', (await call('POST', '/api/edit/articles', { cookie: viewer.cookie, body: { title: 'x', sectionId: art.sectionId } })).status, 403);
|
||||
expect('список пользователей', (await call('GET', '/api/admin/users', { cookie: viewer.cookie })).status, 403);
|
||||
|
||||
console.log('--- редактор (EDITOR)');
|
||||
expect('данные редактора', (await call('GET', `/api/edit/articles/${art.slug}`, { cookie: editor.cookie })).status, 200);
|
||||
expect('сохранение черновика', (await call('PUT', `/api/edit/articles/${art.id}/draft`, { cookie: editor.cookie, body: draftBody })).status, 200);
|
||||
expect('сброс черновика', (await call('DELETE', `/api/edit/articles/${art.id}/draft`, { cookie: editor.cookie })).status, 204);
|
||||
expect('список пользователей', (await call('GET', '/api/admin/users', { cookie: editor.cookie })).status, 403);
|
||||
expect('создание раздела', (await call('POST', '/api/admin/sections', { cookie: editor.cookie, body: { name: 'x', spaceId: tree.spaces[0].id, code: 'X', color: 'ink' } })).status, 403);
|
||||
expect('удаление статьи', (await call('DELETE', `/api/edit/articles/${art.id}`, { cookie: editor.cookie })).status, 403);
|
||||
|
||||
console.log('--- без заголовка X-Requested-With (CSRF)');
|
||||
const noCsrf = await fetch(`${base}/api/auth/logout`, { method: 'POST', headers: { Cookie: viewer.cookie } });
|
||||
expect('запрос отклонён', noCsrf.status, 403);
|
||||
|
||||
console.log('--- блокировка');
|
||||
expect('админ блокирует читателя', (await call('PATCH', `/api/admin/users/${viewer.id}`, { cookie: admin, body: { blocked: true } })).status, 200);
|
||||
expect('заблокированный не читает', (await call('GET', `/api/articles/${art.slug}`, { cookie: viewer.cookie })).status, 401);
|
||||
|
||||
// Уборка
|
||||
for (const u of [viewer, editor]) await call('DELETE', `/api/admin/users/${u.id}`, { cookie: admin });
|
||||
|
||||
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);
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# Восстановление из резервной копии.
|
||||
#
|
||||
# ./scripts/restore.sh backups/db_2026-10-04_0300.dump backups/uploads_2026-10-04_0300.tar.gz
|
||||
#
|
||||
# ВНИМАНИЕ: текущая база и загруженные файлы будут заменены содержимым копии.
|
||||
# Для проверки копии без риска есть режим --check: дамп разворачивается во временную
|
||||
# базу, считаются статьи, временная база удаляется. Рабочие данные не трогаются.
|
||||
#
|
||||
# ./scripts/restore.sh --check backups/db_2026-10-04_0300.dump
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.prod.yml}"
|
||||
DC=(docker compose -f "$COMPOSE_FILE")
|
||||
|
||||
if [ "${1:-}" = "--check" ]; then
|
||||
DUMP="${2:?Укажите файл дампа}"
|
||||
"${DC[@]}" exec -T db sh -c 'dropdb -U "$POSTGRES_USER" --if-exists restore_check && createdb -U "$POSTGRES_USER" restore_check'
|
||||
"${DC[@]}" exec -T db sh -c 'pg_restore -U "$POSTGRES_USER" -d restore_check --no-owner' < "$DUMP"
|
||||
echo "Во временной базе:"
|
||||
"${DC[@]}" exec -T db sh -c 'psql -U "$POSTGRES_USER" -d restore_check -At -c "select '"'"'статей: '"'"' || count(*) from \"Article\"" -c "select '"'"'пользователей: '"'"' || count(*) from \"User\"" -c "select '"'"'картинок: '"'"' || count(*) from \"Asset\""'
|
||||
"${DC[@]}" exec -T db sh -c 'dropdb -U "$POSTGRES_USER" restore_check'
|
||||
echo "Копия читается, временная база удалена."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
DUMP="${1:?Укажите файл дампа базы}"
|
||||
UPLOADS="${2:-}"
|
||||
|
||||
read -r -p "Заменить текущую базу содержимым $DUMP? Введите yes: " answer
|
||||
[ "$answer" = "yes" ] || { echo "Отменено."; exit 1; }
|
||||
|
||||
# Останавливаем api, чтобы он не писал в базу во время восстановления
|
||||
"${DC[@]}" stop api
|
||||
# --clean --if-exists: сначала удаляет существующие таблицы, затем создаёт заново из дампа
|
||||
"${DC[@]}" exec -T db sh -c 'pg_restore -U "$POSTGRES_USER" -d "$POSTGRES_DB" --clean --if-exists --no-owner' < "$DUMP"
|
||||
|
||||
"${DC[@]}" start api
|
||||
if [ -n "$UPLOADS" ]; then
|
||||
# Распаковываем поверх: файлы из копии заменяют одноимённые
|
||||
"${DC[@]}" exec -T api sh -c 'tar -xzf - -C /data' < "$UPLOADS"
|
||||
fi
|
||||
|
||||
echo "Восстановлено. Проверка: curl -s http://localhost:\${WEB_PORT:-8200}/api/health"
|
||||
Reference in New Issue
Block a user