Merge: этап 7 (редактор)
This commit is contained in:
@@ -7,8 +7,10 @@ import { csrfGuard, loadUser } from './auth.js';
|
|||||||
import { prisma } from './db.js';
|
import { prisma } from './db.js';
|
||||||
import { env } from './env.js';
|
import { env } from './env.js';
|
||||||
import { HttpError } from './http.js';
|
import { HttpError } from './http.js';
|
||||||
|
import { adminRouter } from './routes/admin.js';
|
||||||
import { authRouter } from './routes/auth.js';
|
import { authRouter } from './routes/auth.js';
|
||||||
import { contentRouter } from './routes/content.js';
|
import { contentRouter } from './routes/content.js';
|
||||||
|
import { editRouter } from './routes/edit.js';
|
||||||
import { meRouter } from './routes/me.js';
|
import { meRouter } from './routes/me.js';
|
||||||
|
|
||||||
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
|
// Кеш «этот файл относится к публичной статье?»: чтобы не ходить в БД за каждой картинкой
|
||||||
@@ -87,6 +89,8 @@ export function createApp() {
|
|||||||
app.use('/api', csrfGuard);
|
app.use('/api', csrfGuard);
|
||||||
app.use('/api/auth', authRouter);
|
app.use('/api/auth', authRouter);
|
||||||
app.use('/api/me', meRouter);
|
app.use('/api/me', meRouter);
|
||||||
|
app.use('/api/edit', editRouter);
|
||||||
|
app.use('/api/admin', adminRouter);
|
||||||
app.use('/api', contentRouter);
|
app.use('/api', contentRouter);
|
||||||
|
|
||||||
app.use('/api', (_req, res) => {
|
app.use('/api', (_req, res) => {
|
||||||
@@ -105,6 +109,11 @@ export function createApp() {
|
|||||||
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
|
res.status(400).json({ error: first?.message ?? 'Некорректные данные', field: first?.path.join('.') });
|
||||||
return;
|
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') {
|
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') {
|
||||||
res.status(400).json({ error: 'Некорректный запрос' });
|
res.status(400).json({ error: 'Некорректный запрос' });
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -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,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();
|
||||||
|
});
|
||||||
@@ -10,10 +10,17 @@
|
|||||||
"typecheck": "tsc -p tsconfig.json"
|
"typecheck": "tsc -p tsconfig.json"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"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",
|
"@fontsource-variable/onest": "^5.3.1",
|
||||||
"@kb/md": "workspace:^",
|
"@kb/md": "workspace:^",
|
||||||
"@kb/shared": "workspace:^",
|
"@kb/shared": "workspace:^",
|
||||||
|
"@lezer/highlight": "^1.2.5",
|
||||||
"@tanstack/react-query": "^5.104.1",
|
"@tanstack/react-query": "^5.104.1",
|
||||||
|
"codemirror": "^6.0.2",
|
||||||
"qrcode-generator": "^2.0.4",
|
"qrcode-generator": "^2.0.4",
|
||||||
"react": "^19.3.0",
|
"react": "^19.3.0",
|
||||||
"react-dom": "^19.3.0",
|
"react-dom": "^19.3.0",
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ import { SectionPage } from './pages/Section';
|
|||||||
|
|
||||||
// Редко нужные экраны грузятся отдельными файлами, чтобы не замедлять чтение статей
|
// Редко нужные экраны грузятся отдельными файлами, чтобы не замедлять чтение статей
|
||||||
const PrintPage = lazy(() => import('./pages/Print'));
|
const PrintPage = lazy(() => import('./pages/Print'));
|
||||||
|
const EditorPage = lazy(() => import('./pages/Editor'));
|
||||||
|
const NewArticlePage = lazy(() => import('./pages/NewArticle'));
|
||||||
|
|
||||||
function NotFound() {
|
function NotFound() {
|
||||||
return (
|
return (
|
||||||
@@ -78,6 +80,8 @@ export function App() {
|
|||||||
<Route path="/a/:slug" element={<ArticlePage />} />
|
<Route path="/a/:slug" element={<ArticlePage />} />
|
||||||
<Route path="/print/:slug" element={<PrintPage />} />
|
<Route path="/print/:slug" element={<PrintPage />} />
|
||||||
<Route path="/invite/:token" element={<InvitePage />} />
|
<Route path="/invite/:token" element={<InvitePage />} />
|
||||||
|
<Route path="/edit/:slug" element={<EditorPage />} />
|
||||||
|
<Route path="/new" element={<NewArticlePage />} />
|
||||||
<Route path="*" element={<NotFound />} />
|
<Route path="*" element={<NotFound />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</Suspense>
|
</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,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;
|
||||||
|
}
|
||||||
@@ -157,3 +157,14 @@ export async function clearPrivateCaches() {
|
|||||||
if (!cacheSupported()) return;
|
if (!cacheSupported()) return;
|
||||||
await Promise.all([caches.delete(API_CACHE), caches.delete(IMG_CACHE)]).catch(() => undefined);
|
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 {
|
||||||
|
// кеш недоступен: не страшно, он обновится сам при следующем открытии
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ export function useNav() {
|
|||||||
error,
|
error,
|
||||||
space: data?.spaces[0] ?? null,
|
space: data?.spaces[0] ?? null,
|
||||||
sections: views,
|
sections: views,
|
||||||
|
/** Все разделы, включая пустые (для редактора и админки). */
|
||||||
|
allSections: sections,
|
||||||
articles,
|
articles,
|
||||||
pinned,
|
pinned,
|
||||||
article: (slug: string) => bySlug.get(slug),
|
article: (slug: string) => bySlug.get(slug),
|
||||||
|
|||||||
@@ -28,6 +28,20 @@ const queryClient = new QueryClient({
|
|||||||
// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
|
// Service worker: кеширует интерфейс и открытые статьи, сам обновляется при выходе новой версии
|
||||||
registerSW({ immediate: true });
|
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(
|
createRoot(document.getElementById('root')!).render(
|
||||||
<StrictMode>
|
<StrictMode>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ function ArticleView({ slug }: { slug: string }) {
|
|||||||
const listItem = nav.article(slug);
|
const listItem = nav.article(slug);
|
||||||
const section = nav.sectionOf(art ?? listItem);
|
const section = nav.sectionOf(art ?? listItem);
|
||||||
|
|
||||||
const { user } = useAuth();
|
const { user, isEditor } = useAuth();
|
||||||
const artSlug = art?.slug;
|
const artSlug = art?.slug;
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!artSlug) return;
|
if (!artSlug) return;
|
||||||
@@ -204,15 +204,28 @@ function ArticleView({ slug }: { slug: string }) {
|
|||||||
<IconPrint size={20} />
|
<IconPrint size={20} />
|
||||||
Печать / PDF
|
Печать / PDF
|
||||||
</button>
|
</button>
|
||||||
|
{isEditor ? (
|
||||||
|
<Link className="btn btn--solid" to={`/edit/${slug}`}>
|
||||||
|
Редактировать
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="art-layout">
|
<div className="art-layout">
|
||||||
<article className="art">
|
<article className="art">
|
||||||
<div className="topline art-topline">
|
<div className="topline art-topline">
|
||||||
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
<BackLink to={backTo}>{section?.name ?? 'Главная'}</BackLink>
|
||||||
{cached ? <OfflinePill /> : null}
|
<span className="topline-right">
|
||||||
|
{cached ? <OfflinePill /> : null}
|
||||||
|
{isEditor ? (
|
||||||
|
<Link className="btn" to={`/edit/${slug}`}>
|
||||||
|
Править
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="art-over">{section?.name}</div>
|
<div className="art-over">{section?.name}</div>
|
||||||
|
{art.status === 'DRAFT' ? <span className="badge-draft">Черновик: читатели не видят</span> : null}
|
||||||
<h1 className="art-title">{art.title}</h1>
|
<h1 className="art-title">{art.title}</h1>
|
||||||
{art.summary ? <p className="art-summary">{art.summary}</p> : null}
|
{art.summary ? <p className="art-summary">{art.summary}</p> : null}
|
||||||
<div className="art-meta-mobile">{meta}</div>
|
<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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -52,6 +52,7 @@ export function SectionPage() {
|
|||||||
<div className="art-card-head">
|
<div className="art-card-head">
|
||||||
<span className="art-card-n">{num2(i + 1)}</span>
|
<span className="art-card-n">{num2(i + 1)}</span>
|
||||||
<span className="art-card-title">{nav.short(a)}</span>
|
<span className="art-card-title">{nav.short(a)}</span>
|
||||||
|
{a.status === 'DRAFT' ? <span className="badge-draft">Черновик</span> : null}
|
||||||
</div>
|
</div>
|
||||||
{a.summary ? <div className="art-card-text">{a.summary}</div> : null}
|
{a.summary ? <div className="art-card-text">{a.summary}</div> : null}
|
||||||
{a.tags.length ? (
|
{a.tags.length ? (
|
||||||
|
|||||||
@@ -2466,3 +2466,8 @@ mark {
|
|||||||
font-size: var(--fs-12);
|
font-size: var(--fs-12);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
}
|
}
|
||||||
|
.topline-right {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--sp-4);
|
||||||
|
}
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -45,6 +45,8 @@ export default defineConfig({
|
|||||||
options: {
|
options: {
|
||||||
cacheName: 'kb-api',
|
cacheName: 'kb-api',
|
||||||
cacheableResponse: { statuses: [200] },
|
cacheableResponse: { statuses: [200] },
|
||||||
|
// Если в фоне пришла новая версия, сообщаем странице: она перерисует данные (см. main.tsx)
|
||||||
|
broadcastUpdate: { channelName: 'kb-api-updates', options: { headersToCheck: ['etag'] } },
|
||||||
expiration: { maxEntries: 600 },
|
expiration: { maxEntries: 600 },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
+5
-1
@@ -28,6 +28,10 @@ export default tseslint.config(
|
|||||||
{
|
{
|
||||||
files: ['apps/web/**/*.{ts,tsx}'],
|
files: ['apps/web/**/*.{ts,tsx}'],
|
||||||
plugins: { 'react-hooks': reactHooks },
|
plugins: { 'react-hooks': reactHooks },
|
||||||
rules: { ...reactHooks.configs.recommended.rules },
|
rules: {
|
||||||
|
...reactHooks.configs.recommended.rules,
|
||||||
|
// Правило для React Compiler, которым проект не пользуется
|
||||||
|
'react-hooks/preserve-manual-memoization': 'off',
|
||||||
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
Generated
+227
@@ -108,6 +108,21 @@ importers:
|
|||||||
|
|
||||||
apps/web:
|
apps/web:
|
||||||
dependencies:
|
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':
|
'@fontsource-variable/onest':
|
||||||
specifier: ^5.3.1
|
specifier: ^5.3.1
|
||||||
version: 5.3.1
|
version: 5.3.1
|
||||||
@@ -117,9 +132,15 @@ importers:
|
|||||||
'@kb/shared':
|
'@kb/shared':
|
||||||
specifier: workspace:^
|
specifier: workspace:^
|
||||||
version: link:../../packages/shared
|
version: link:../../packages/shared
|
||||||
|
'@lezer/highlight':
|
||||||
|
specifier: ^1.2.5
|
||||||
|
version: 1.2.5
|
||||||
'@tanstack/react-query':
|
'@tanstack/react-query':
|
||||||
specifier: ^5.104.1
|
specifier: ^5.104.1
|
||||||
version: 5.104.1(react@19.3.0)
|
version: 5.104.1(react@19.3.0)
|
||||||
|
codemirror:
|
||||||
|
specifier: ^6.0.2
|
||||||
|
version: 6.0.2
|
||||||
qrcode-generator:
|
qrcode-generator:
|
||||||
specifier: ^2.0.4
|
specifier: ^2.0.4
|
||||||
version: 2.0.4
|
version: 2.0.4
|
||||||
@@ -716,6 +737,39 @@ packages:
|
|||||||
'@cacheable/utils@2.5.0':
|
'@cacheable/utils@2.5.0':
|
||||||
resolution: {integrity: sha512-buipgOVDkkPXNR5+xBpDw7Zk2n1EvU7qBJCNUcL7rhQ//kfpOXPAvQ511Os0vpLYJ1pZnvudNytkQt2hst3wqA==}
|
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':
|
'@emnapi/runtime@1.11.3':
|
||||||
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
|
resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
|
||||||
|
|
||||||
@@ -1274,6 +1328,30 @@ packages:
|
|||||||
'@keyv/serialize@1.1.1':
|
'@keyv/serialize@1.1.1':
|
||||||
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
|
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':
|
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||||
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}
|
||||||
engines: {node: ^22.20 || ^24.12 || >=25}
|
engines: {node: ^22.20 || ^24.12 || >=25}
|
||||||
@@ -1958,6 +2036,9 @@ packages:
|
|||||||
citty@0.2.2:
|
citty@0.2.2:
|
||||||
resolution: {integrity: sha512-+6vJA3L98yv+IdfKGZHBNiGW5KHn22e/JwID0Strsz8h4S/csAu/OuICwxrg44k5MRiZHWIo8XXuJgQTriRP4w==}
|
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:
|
comma-separated-tokens@2.0.3:
|
||||||
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
|
resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==}
|
||||||
|
|
||||||
@@ -2027,6 +2108,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
|
resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==}
|
||||||
engines: {node: '>= 0.10'}
|
engines: {node: '>= 0.10'}
|
||||||
|
|
||||||
|
crelt@1.0.7:
|
||||||
|
resolution: {integrity: sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==}
|
||||||
|
|
||||||
cross-env@10.1.0:
|
cross-env@10.1.0:
|
||||||
resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==}
|
resolution: {integrity: sha512-GsYosgnACZTADcmEyJctkJIoqAhHjttw7RsFrVoJNXbsWWqaq6Ym+7kZjq6mS45O0jij6vtiReppKQEtqWy6Dw==}
|
||||||
engines: {node: '>=20'}
|
engines: {node: '>=20'}
|
||||||
@@ -3484,6 +3568,9 @@ packages:
|
|||||||
resolution: {integrity: sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw==}
|
resolution: {integrity: sha512-ZprKx+bBLXv067WTCALv8SSz5l2+XhpYCsVtSqlMnkAXMWDq+/ekVbl1ghqP9rUHTzv6sm/DwCOiYutU/yp1fw==}
|
||||||
engines: {node: '>=10'}
|
engines: {node: '>=10'}
|
||||||
|
|
||||||
|
style-mod@4.1.4:
|
||||||
|
resolution: {integrity: sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==}
|
||||||
|
|
||||||
sucrase@3.35.1:
|
sucrase@3.35.1:
|
||||||
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
|
resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==}
|
||||||
engines: {node: '>=16 || 14 >=14.17'}
|
engines: {node: '>=16 || 14 >=14.17'}
|
||||||
@@ -3797,6 +3884,9 @@ packages:
|
|||||||
jsdom:
|
jsdom:
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
|
w3c-keyname@2.2.8:
|
||||||
|
resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}
|
||||||
|
|
||||||
which-boxed-primitive@1.1.1:
|
which-boxed-primitive@1.1.1:
|
||||||
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
|
resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==}
|
||||||
engines: {node: '>= 0.4'}
|
engines: {node: '>= 0.4'}
|
||||||
@@ -4581,6 +4671,92 @@ snapshots:
|
|||||||
hashery: 1.5.1
|
hashery: 1.5.1
|
||||||
keyv: 5.6.0
|
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':
|
'@emnapi/runtime@1.11.3':
|
||||||
dependencies:
|
dependencies:
|
||||||
tslib: 2.8.1
|
tslib: 2.8.1
|
||||||
@@ -4936,6 +5112,41 @@ snapshots:
|
|||||||
|
|
||||||
'@keyv/serialize@1.1.1': {}
|
'@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':
|
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
|
||||||
optional: true
|
optional: true
|
||||||
|
|
||||||
@@ -5577,6 +5788,16 @@ snapshots:
|
|||||||
|
|
||||||
citty@0.2.2: {}
|
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: {}
|
comma-separated-tokens@2.0.3: {}
|
||||||
|
|
||||||
commander@2.20.3: {}
|
commander@2.20.3: {}
|
||||||
@@ -5623,6 +5844,8 @@ snapshots:
|
|||||||
object-assign: 4.1.1
|
object-assign: 4.1.1
|
||||||
vary: 1.1.2
|
vary: 1.1.2
|
||||||
|
|
||||||
|
crelt@1.0.7: {}
|
||||||
|
|
||||||
cross-env@10.1.0:
|
cross-env@10.1.0:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@epic-web/invariant': 1.0.0
|
'@epic-web/invariant': 1.0.0
|
||||||
@@ -7520,6 +7743,8 @@ snapshots:
|
|||||||
|
|
||||||
strip-comments@2.0.1: {}
|
strip-comments@2.0.1: {}
|
||||||
|
|
||||||
|
style-mod@4.1.4: {}
|
||||||
|
|
||||||
sucrase@3.35.1:
|
sucrase@3.35.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@jridgewell/gen-mapping': 0.3.13
|
'@jridgewell/gen-mapping': 0.3.13
|
||||||
@@ -7850,6 +8075,8 @@ snapshots:
|
|||||||
transitivePeerDependencies:
|
transitivePeerDependencies:
|
||||||
- msw
|
- msw
|
||||||
|
|
||||||
|
w3c-keyname@2.2.8: {}
|
||||||
|
|
||||||
which-boxed-primitive@1.1.1:
|
which-boxed-primitive@1.1.1:
|
||||||
dependencies:
|
dependencies:
|
||||||
is-bigint: 1.1.0
|
is-bigint: 1.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);
|
||||||
Reference in New Issue
Block a user