Этап 3: экраны чтения по макету
- API: GET /api/tree, GET /api/articles/:slug, раздача /uploads - экраны: Главная, Раздел, Статья, Шпаргалка, Избранное (телефон и компьютер) - блоки статьи, чек-листы с сохранением в localStorage (ключ slug + версия) - просмотр фото: щипок, двойной тап, свайп, клавиатура - липкая шапка с прогрессом, оглавление в bottom sheet, избранное, недавние - три темы (тёмная / светлая / солнце), выбор запоминается - печать и PDF: окно настроек, печатная версия статьи и шпаргалки с QR - дизайн-токены в tokens.css, шрифт Onest в сборке - scripts/check-layout.mjs: проверка отсутствия горизонтальной прокрутки - исправлены два невидимых символа, на которые ругался линтер Lighthouse mobile: Performance 95-96, Accessibility 100. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
be9be3f79e
commit
59be0307cc
@@ -1,6 +1,9 @@
|
||||
import express, { type ErrorRequestHandler } from 'express';
|
||||
import type { HealthResponse } from '@kb/shared';
|
||||
import { prisma } from './db.js';
|
||||
import { env } from './env.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { contentRouter } from './routes/content.js';
|
||||
|
||||
export function createApp() {
|
||||
const app = express();
|
||||
@@ -17,12 +20,37 @@ export function createApp() {
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
// Загруженные файлы. Имена картинок не меняются при замене содержимого редко,
|
||||
// поэтому кешируем на сутки, а дальше браузер перепроверяет по ETag.
|
||||
app.use(
|
||||
'/uploads',
|
||||
express.static(env.UPLOADS_DIR, {
|
||||
index: false,
|
||||
dotfiles: 'deny',
|
||||
maxAge: '1d',
|
||||
setHeaders(res, file) {
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
// Исходники (PDF/DOCX) всегда скачиваются, а не открываются в браузере
|
||||
if (!/\.(webp|png|jpe?g|gif)$/i.test(file)) res.setHeader('Content-Disposition', 'attachment');
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use('/uploads', (_req, res) => {
|
||||
res.status(404).json({ error: 'Файл не найден' });
|
||||
});
|
||||
|
||||
app.use('/api', contentRouter);
|
||||
|
||||
app.use('/api', (_req, res) => {
|
||||
res.status(404).json({ error: 'Не найдено' });
|
||||
});
|
||||
|
||||
// Единая обработка ошибок: клиенту короткое сообщение, подробности в лог.
|
||||
const onError: ErrorRequestHandler = (err, _req, res, _next) => {
|
||||
if (err instanceof HttpError) {
|
||||
res.status(err.status).json({ error: err.message });
|
||||
return;
|
||||
}
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'Внутренняя ошибка сервера' });
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/** Ошибка с HTTP-кодом: бросаем из обработчика, общий обработчик в app.ts превращает её в ответ. */
|
||||
export class HttpError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Router } from 'express';
|
||||
import type { Article, Section, Space } from '@prisma/client';
|
||||
import { parseCheatSheet, renderMarkdown } from '@kb/md';
|
||||
import type { ArticleDto, ArticleListItem, SectionDto, SpaceDto, TreeResponse, PlaqueColor } from '@kb/shared';
|
||||
import { prisma } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
|
||||
export const contentRouter = Router();
|
||||
|
||||
export const toSpaceDto = (s: Space): SpaceDto => ({ id: s.id, name: s.name, slug: s.slug, icon: s.icon, order: s.order });
|
||||
|
||||
export const toSectionDto = (s: Section): SectionDto => ({
|
||||
id: s.id,
|
||||
spaceId: s.spaceId,
|
||||
name: s.name,
|
||||
slug: s.slug,
|
||||
code: s.code,
|
||||
color: s.color as PlaqueColor,
|
||||
icon: s.icon,
|
||||
order: s.order,
|
||||
});
|
||||
|
||||
type ArticleWithAssets = Article & { assets: { size: number }[] };
|
||||
|
||||
export const toListItem = (a: ArticleWithAssets): ArticleListItem => ({
|
||||
id: a.id,
|
||||
slug: a.slug,
|
||||
title: a.title,
|
||||
summary: a.summary,
|
||||
sectionId: a.sectionId,
|
||||
order: a.order,
|
||||
tags: a.tags,
|
||||
equipment: a.equipment,
|
||||
docCode: a.docCode,
|
||||
pinned: a.pinned,
|
||||
status: a.status,
|
||||
visibility: a.visibility,
|
||||
version: a.version,
|
||||
updatedAt: a.updatedAt.toISOString(),
|
||||
imageCount: a.assets.length,
|
||||
bytes: a.assets.reduce((n, x) => n + x.size, 0),
|
||||
});
|
||||
|
||||
// Всё дерево одним запросом: пространства, разделы и список статей (без текста).
|
||||
// Статей сотни, не тысячи, поэтому отдельные запросы на каждый раздел не нужны,
|
||||
// а для офлайна один ответ кешировать проще.
|
||||
contentRouter.get('/tree', async (_req, res) => {
|
||||
const [spaces, sections, articles] = await Promise.all([
|
||||
prisma.space.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.section.findMany({ orderBy: { order: 'asc' } }),
|
||||
prisma.article.findMany({
|
||||
where: { status: 'PUBLISHED' },
|
||||
orderBy: [{ order: 'asc' }, { title: 'asc' }],
|
||||
include: { assets: { select: { size: true } } },
|
||||
}),
|
||||
]);
|
||||
const body: TreeResponse = {
|
||||
spaces: spaces.map(toSpaceDto),
|
||||
sections: sections.map(toSectionDto),
|
||||
articles: articles.map(toListItem),
|
||||
};
|
||||
res.json(body);
|
||||
});
|
||||
|
||||
contentRouter.get('/articles/:slug', async (req, res) => {
|
||||
const art = await prisma.article.findUnique({
|
||||
where: { slug: req.params.slug },
|
||||
include: {
|
||||
assets: { select: { size: true } },
|
||||
attachments: { orderBy: { createdAt: 'asc' } },
|
||||
author: { select: { name: true } },
|
||||
},
|
||||
});
|
||||
if (!art || art.status !== 'PUBLISHED') throw new HttpError(404, 'Статья не найдена');
|
||||
|
||||
// Список картинок берём из самого текста (а не из Asset): так порядок совпадает с порядком в статье
|
||||
const { figures, toc } = renderMarkdown(art.bodyMd);
|
||||
const cheat = art.pinned ? parseCheatSheet(art.bodyMd) : null;
|
||||
const body: ArticleDto = {
|
||||
...toListItem(art),
|
||||
bodyMd: art.bodyMd,
|
||||
bodyHtml: art.bodyHtml,
|
||||
attachments: art.attachments.map((a) => ({
|
||||
id: a.id,
|
||||
filename: a.filename,
|
||||
url: `/uploads/${a.path}`,
|
||||
size: a.size,
|
||||
})),
|
||||
images: figures.flatMap((f) => [f.thumb, f.full]),
|
||||
authorName: art.author?.name ?? null,
|
||||
toc,
|
||||
cheat: cheat?.ok ? cheat : null,
|
||||
};
|
||||
res.json(body);
|
||||
});
|
||||
Reference in New Issue
Block a user