Files
wiki-montazh/packages/md/src/frontmatter.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

100 lines
3.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.
// Разбор шапки статьи (front matter).
//
// Почему не библиотека YAML: в наших статьях встречаются строки вида
// summary: Карта стойки: верх — оптика и коммутатор
// equipment: [уголок 130х130х100х1,8, FTP Cat5e]
// Строгий YAML на первой падает (двоеточие в значении), а вторую режет по запятой
// внутри «1,8». Поэтому разбираем сами по простым правилам:
// - ключ отделяется ПЕРВЫМ двоеточием;
// - список [a, b] делится по «запятая + пробел», запятая без пробела остаётся в значении.
export interface FrontMatter {
title?: string;
slug?: string;
section?: string;
order?: number;
tags: string[];
equipment: string[];
/** Пути к исходникам: originals/file.pdf */
source: string[];
doc_code?: string;
summary?: string;
pinned: boolean;
/** Остальные ключи как есть. */
extra: Record<string, string>;
}
function unquote(s: string): string {
const t = s.trim();
if (t.length >= 2 && ((t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")))) {
return t.slice(1, -1);
}
return t;
}
function parseList(raw: string): string[] {
const t = raw.trim();
if (!t) return [];
if (t.startsWith('[') && t.endsWith(']')) {
return t
.slice(1, -1)
.split(/,\s+/)
.map(unquote)
.filter(Boolean);
}
return [unquote(t)];
}
export function parseFrontMatter(src: string): { meta: FrontMatter; body: string } {
const meta: FrontMatter = { tags: [], equipment: [], source: [], pinned: false, extra: {} };
// Убираем BOM и приводим переводы строк к \n
const text = (src.charCodeAt(0) === 0xfeff ? src.slice(1) : src).replace(/\r\n?/g, '\n');
const m = text.match(/^---\n([\s\S]*?)\n---\n?/);
if (!m) return { meta, body: text };
const lines = (m[1] ?? '').split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i] ?? '';
const c = line.indexOf(':');
if (c < 1 || /^\s/.test(line) || line.startsWith('#')) continue;
const key = line.slice(0, c).trim();
let value = line.slice(c + 1).trim();
// Многострочный список:
// tags:
// - один
// - два
if (!value) {
const items: string[] = [];
while (i + 1 < lines.length && /^\s*-\s+/.test(lines[i + 1] ?? '')) {
items.push(unquote((lines[++i] ?? '').replace(/^\s*-\s+/, '')));
}
if (items.length) value = `[${items.join(', ')}]`;
}
switch (key) {
case 'title':
case 'slug':
case 'section':
case 'summary':
case 'doc_code':
meta[key] = unquote(value);
break;
case 'order':
meta.order = Number.parseInt(value, 10) || 0;
break;
case 'pinned':
meta.pinned = /^(true|yes|да|1)$/i.test(value);
break;
case 'tags':
case 'equipment':
case 'source':
meta[key] = parseList(value);
break;
default:
meta.extra[key] = unquote(value);
}
}
return { meta, body: text.slice(m[0].length) };
}