Files
wiki-montazh/packages/shared/src/index.ts
T
deonisiiandClaude Opus 5.5 59be0307cc Этап 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>
2026-10-04 12:33:37 +03:00

234 lines
6.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Общие типы API: их импортируют и сервер, и клиент, чтобы формат ответов не расходился.
export type Role = 'ADMIN' | 'EDITOR' | 'VIEWER';
export type ArticleStatus = 'DRAFT' | 'PUBLISHED';
export type Visibility = 'PRIVATE' | 'PUBLIC';
/** Ключ цвета плашки раздела. Сами цвета лежат в CSS-токенах (--plq-*). */
export type PlaqueColor = 'yellow' | 'orange' | 'blue' | 'green' | 'ink';
export const PLAQUE_COLORS: PlaqueColor[] = ['yellow', 'orange', 'blue', 'green', 'ink'];
export interface HealthResponse {
status: 'ok';
db: 'ok';
time: string;
}
export interface UserDto {
id: string;
email: string;
name: string;
role: Role;
}
export interface SpaceDto {
id: string;
name: string;
slug: string;
icon: string | null;
order: number;
}
export interface SectionDto {
id: string;
spaceId: string;
name: string;
slug: string;
/** Короткий код на плашке: «ВВ», «ВОК». */
code: string;
color: PlaqueColor;
icon: string | null;
order: number;
}
/** Статья в списках: без тела. */
export interface ArticleListItem {
id: string;
slug: string;
title: string;
summary: string;
sectionId: string;
order: number;
tags: string[];
equipment: string[];
docCode: string | null;
pinned: boolean;
status: ArticleStatus;
visibility: Visibility;
version: number;
updatedAt: string;
/** Сколько рисунков в статье и сколько они весят (для «Скачать раздел»). */
imageCount: number;
bytes: number;
}
export interface AttachmentDto {
id: string;
filename: string;
url: string;
size: number;
}
export interface FactDto {
/** Подпись: «Запас при зачистке кабеля». */
label: string;
/** Значение с **жирным** в Markdown-разметке. */
value: string;
}
export interface ArticleDto extends ArticleListItem {
bodyMd: string;
bodyHtml: string;
attachments: AttachmentDto[];
/** Адреса картинок статьи (полные и превью): нужны для офлайн-кеша. */
images: string[];
authorName: string | null;
/** Заголовки H2 для оглавления. */
toc: TocEntry[];
/** Разобранная шпаргалка (только у закреплённой статьи со структурой шпаргалки). */
cheat: CheatSheet | null;
}
/** Всё дерево одним запросом: его хватает для главной, меню и офлайна. */
export interface TreeResponse {
spaces: SpaceDto[];
sections: SectionDto[];
articles: ArticleListItem[];
}
export interface Highlight {
t: string;
hit: boolean;
}
export interface SearchFact {
value: Highlight[];
label: Highlight[];
articleSlug: string;
articleTitle: string;
}
export interface SearchArticle {
slug: string;
title: Highlight[];
section: string;
sectionId: string;
snippet: Highlight[];
pinned: boolean;
}
export interface SearchResponse {
q: string;
facts: SearchFact[];
articles: SearchArticle[];
}
export interface RevisionDto {
id: string;
version: number;
createdAt: string;
authorName: string | null;
comment: string | null;
}
export interface AdminUserDto extends UserDto {
blocked: boolean;
createdAt: string;
lastSeenAt: string | null;
}
export interface InviteDto {
id: string;
token: string;
role: Role;
expiresAt: string;
usedAt: string | null;
url: string;
}
export const ROLE_LABEL: Record<Role, string> = {
ADMIN: 'Админ',
EDITOR: 'Редактор',
VIEWER: 'Читатель',
};
/** Русское склонение: plural(3, ['статья','статьи','статей']) → «статьи». */
export function plural(n: number, forms: [string, string, string]): string {
const a = Math.abs(n) % 100;
const b = a % 10;
if (a > 10 && a < 20) return forms[2];
if (b > 1 && b < 5) return forms[1];
if (b === 1) return forms[0];
return forms[2];
}
// ---------- Нормализация текста для поиска (одинаковая при индексации и при запросе) ----------
/** Нижний регистр, ё→е, все виды тире → дефис, лишние пробелы убраны. */
export function normalizeSearch(s: string): string {
return s
.toLowerCase()
.replace(/ё/g, 'е')
// \p{Pd}: все виды тире и дефисов, плюс математический минус
.replace(/[\p{Pd}−]/gu, '-')
// \p{Zs}: все виды пробелов, включая неразрывный и узкий
.replace(/\p{Zs}/gu, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* «Сжатый» вид: только буквы и цифры. Так «MG12» находит «MG-12»,
* а «ral7024» находит «RAL 7024».
*/
export function compactSearch(s: string): string {
return normalizeSearch(s).replace(/[^\p{L}\p{N}]+/gu, '');
}
/** Короткое название статьи для меню: без «Название раздела — » в начале. */
export function shortTitle(title: string, sectionName?: string): string {
let t = title;
if (sectionName && t.toLowerCase().startsWith(sectionName.toLowerCase())) {
const rest = t.slice(sectionName.length).replace(/^\s*[—–:-]\s*/, '');
if (rest && rest !== t.slice(sectionName.length)) t = rest;
}
return t.charAt(0).toUpperCase() + t.slice(1);
}
// ---------- Шпаргалка ----------
export interface Seg {
t: string;
bold?: boolean;
}
export interface CheatLine {
/** Текст с выделением жирного. */
segs: Seg[];
/** Значение (для «Цифр»): «20 см». */
value?: string;
/** Статьи-источники: slug из [[...]]. */
links: string[];
}
export interface CheatColor {
/** «RAL 5017» */
code: string;
/** «Уголок фотоэлемента» */
label: string;
}
export interface CheatSheet {
bans: CheatLine[];
facts: CheatLine[];
colors: CheatColor[];
always: CheatLine[];
/** true, если нашёлся хотя бы один из разделов. */
ok: boolean;
}
export interface TocEntry {
id: string;
text: string;
}