Этап 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
@@ -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