Этап 2: общий Markdown-рендер и импорт стартового контента
- packages/md: unified + remark-gfm + remark-directive, свой плагин [[slug]], блоки keyfacts/danger/warning/tip/info, чек-листы, шаги, таблицы, фото, rehype-sanitize, разбор шпаргалки, терпимый разбор front matter, тесты - pnpm seed: пространство, разделы, 12 статей, 58 картинок (sharp → WebP 1600 + 480, без EXIF), исходники как Attachment, администратор, отчёт - поисковые поля статьи (tsvector с весами, нормализованный и сжатый текст) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
aa04c1f5db
commit
768daf7c5f
@@ -13,13 +13,12 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"hast-util-to-string": "^3.0.1",
|
||||
"@kb/shared": "workspace:^",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"rehype-stringify": "^10.0.1",
|
||||
"remark-directive": "^4.0.0",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.2",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-visit": "^5.1.0"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// Правило адресов картинок. Одно и то же на сервере и на клиенте.
|
||||
//
|
||||
// В Markdown автор пишет путь как есть: 
|
||||
// При загрузке сервер делает из картинки два WebP-файла:
|
||||
// /uploads/assets/shkon/fig-1.webp (до 1600 px, для просмотра и зума)
|
||||
// /uploads/assets/shkon/fig-1.480.webp (превью 480 px, для сетки и списка)
|
||||
|
||||
export interface AssetUrls {
|
||||
full: string;
|
||||
thumb: string;
|
||||
/** Имя файла для подписи-заглушки, если картинка не загрузилась. */
|
||||
file: string;
|
||||
/** Ключ картинки в папке uploads без расширения: assets/shkon/fig-1 */
|
||||
key: string | null;
|
||||
}
|
||||
|
||||
export function assetKey(src: string): string | null {
|
||||
if (/^[a-z][a-z0-9+.-]*:/i.test(src) || src.startsWith('//')) return null; // внешний адрес
|
||||
const clean = src
|
||||
.split(/[?#]/)[0]!
|
||||
.replace(/^\.?\/+/, '')
|
||||
.replace(/^uploads\//, '');
|
||||
return clean.replace(/(\.480)?\.[a-z0-9]+$/i, '');
|
||||
}
|
||||
|
||||
export function assetUrls(src: string): AssetUrls {
|
||||
const file = src.split(/[?#]/)[0]!.split('/').pop() ?? src;
|
||||
const key = assetKey(src);
|
||||
if (key === null) return { full: src, thumb: src, file, key };
|
||||
return { full: `/uploads/${key}.webp`, thumb: `/uploads/${key}.480.webp`, file, key };
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Разбор статьи-шпаргалки на структурные части для экрана «Шпаргалка»:
|
||||
// запреты, цифры, цвета, «всегда». Разделы узнаём по словам в заголовках H2,
|
||||
// эмодзи в заголовках не обязательны.
|
||||
//
|
||||
// Ничего не выдумываем: если раздела в статье нет, список будет пустым,
|
||||
// а если структура совсем другая, экран покажет статью обычным рендером.
|
||||
|
||||
import { type MdNode, parseMarkdown, plainText } from './parse.js';
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
function segsOf(nodes: MdNode[]): { segs: Seg[]; links: string[] } {
|
||||
const segs: Seg[] = [];
|
||||
const links: string[] = [];
|
||||
for (const n of nodes) {
|
||||
if (n.type === 'wikiLink') {
|
||||
if (n.slug) links.push(n.slug);
|
||||
} else if (n.type === 'strong') {
|
||||
segs.push({ t: plainText(n), bold: true });
|
||||
} else {
|
||||
segs.push({ t: plainText(n) });
|
||||
}
|
||||
}
|
||||
// Убираем хвост из стрелок и разделителей перед ссылками: «… шинки → » и « · »
|
||||
for (let i = segs.length - 1; i >= 0; i--) {
|
||||
const s = segs[i]!;
|
||||
if (s.bold) break;
|
||||
s.t = s.t.replace(/[\s→·]+$/u, '');
|
||||
if (s.t) break;
|
||||
segs.pop();
|
||||
}
|
||||
if (segs[0] && !segs[0].bold) segs[0].t = segs[0].t.replace(/^[\s·]+/u, '');
|
||||
return { segs: segs.filter((s) => s.t), links };
|
||||
}
|
||||
|
||||
const itemNodes = (li: MdNode): MdNode[] => (li.children ?? []).flatMap((p) => p.children ?? []);
|
||||
|
||||
export function parseCheatSheet(md: string): CheatSheet {
|
||||
const tree = parseMarkdown(md);
|
||||
const sheet: CheatSheet = { bans: [], facts: [], colors: [], always: [], ok: false };
|
||||
let part: 'bans' | 'facts' | 'colors' | 'always' | null = null;
|
||||
|
||||
for (const node of tree.children ?? []) {
|
||||
if (node.type === 'heading') {
|
||||
const t = plainText(node).toLowerCase();
|
||||
part = /запрещ|запрет/.test(t)
|
||||
? 'bans'
|
||||
: /цифр/.test(t)
|
||||
? 'facts'
|
||||
: /цвет/.test(t)
|
||||
? 'colors'
|
||||
: /всегда/.test(t)
|
||||
? 'always'
|
||||
: null;
|
||||
continue;
|
||||
}
|
||||
if (!part) continue;
|
||||
|
||||
if (node.type === 'list') {
|
||||
for (const li of node.children ?? []) {
|
||||
const line = segsOf(itemNodes(li));
|
||||
if (part === 'colors') {
|
||||
// «Уголок фотоэлемента: **RAL 5017**»
|
||||
const code = line.segs.find((s) => s.bold)?.t ?? '';
|
||||
const label = line.segs
|
||||
.filter((s) => !s.bold)
|
||||
.map((s) => s.t)
|
||||
.join(' ')
|
||||
.replace(/[:\s]+$/u, '')
|
||||
.trim();
|
||||
if (code) sheet.colors.push({ code, label });
|
||||
} else if (part === 'facts') {
|
||||
sheet.facts.push(line);
|
||||
} else {
|
||||
sheet[part].push(line);
|
||||
}
|
||||
}
|
||||
} else if (node.type === 'table' && part === 'facts') {
|
||||
// Таблица «Что | Значение | Где»
|
||||
for (const row of (node.children ?? []).slice(1)) {
|
||||
const cells = row.children ?? [];
|
||||
const what = segsOf(cells[0]?.children ?? []);
|
||||
const where = segsOf(cells.slice(2).flatMap((c) => c.children ?? []));
|
||||
sheet.facts.push({
|
||||
segs: what.segs,
|
||||
value: plainText(cells[1] ?? { type: 'text', value: '' }).trim(),
|
||||
links: [...what.links, ...where.links],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sheet.ok = sheet.bans.length + sheet.facts.length + sheet.always.length > 0;
|
||||
return sheet;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Разбор шапки статьи (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.replace(/^/, '').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) };
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
// Markdown-дерево (mdast) → HTML-дерево (hast) с нашими блоками.
|
||||
//
|
||||
// Разметка повторяет макет new_design/ArticleBodyXL.dc.html, только вместо инлайн-стилей
|
||||
// стоят классы kb-*; сами стили лежат в apps/web/src/styles/article.css.
|
||||
// Интерактив (галочки чек-листа, открытие фото) навешивает клиент по data-атрибутам,
|
||||
// поэтому один и тот же HTML годится и для сервера, и для предпросмотра в редакторе.
|
||||
|
||||
import { plural } from '@kb/shared';
|
||||
import { assetUrls } from './assets.js';
|
||||
import { type MdNode, plainText } from './parse.js';
|
||||
|
||||
export interface HNode {
|
||||
type: 'element' | 'text' | 'root';
|
||||
tagName?: string;
|
||||
properties?: Record<string, string | number | boolean | string[] | undefined>;
|
||||
children?: HNode[];
|
||||
value?: string;
|
||||
}
|
||||
|
||||
export interface TocItem {
|
||||
id: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface FigureInfo {
|
||||
src: string;
|
||||
full: string;
|
||||
thumb: string;
|
||||
caption: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
export interface RenderOptions {
|
||||
/** Название статьи по slug. Вернёт undefined: ссылка битая. */
|
||||
resolveLink?: (slug: string) => string | undefined;
|
||||
/** Размеры картинки по ключу (assets/shkon/fig-1): чтобы страница не прыгала при загрузке. */
|
||||
imageSize?: (key: string) => { width: number; height: number } | undefined;
|
||||
}
|
||||
|
||||
export interface RenderContext {
|
||||
opts: RenderOptions;
|
||||
toc: TocItem[];
|
||||
figures: FigureInfo[];
|
||||
links: string[];
|
||||
brokenLinks: string[];
|
||||
checkGroups: number;
|
||||
}
|
||||
|
||||
type Props = HNode['properties'];
|
||||
const h = (tagName: string, properties: Props, ...children: (HNode | string | null | undefined)[]): HNode => ({
|
||||
type: 'element',
|
||||
tagName,
|
||||
properties: properties ?? {},
|
||||
children: children
|
||||
.filter((c): c is HNode | string => c !== null && c !== undefined)
|
||||
.map((c) => (typeof c === 'string' ? { type: 'text', value: c } : c)),
|
||||
});
|
||||
const text = (value: string): HNode => ({ type: 'text', value });
|
||||
|
||||
// «flat»: внутри кнопок и плашек ссылка-чип не нужна (в кнопке не может быть ссылки),
|
||||
// там она рисуется подчёркнутым текстом, как в макете.
|
||||
type InlineMode = 'chip' | 'flat';
|
||||
|
||||
function inline(nodes: MdNode[] | undefined, ctx: RenderContext, mode: InlineMode): HNode[] {
|
||||
const out: HNode[] = [];
|
||||
for (const n of nodes ?? []) {
|
||||
switch (n.type) {
|
||||
case 'text':
|
||||
out.push(text(n.value ?? ''));
|
||||
break;
|
||||
case 'strong':
|
||||
out.push(h('strong', { className: ['kb-b'] }, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'emphasis':
|
||||
out.push(h('em', {}, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'delete':
|
||||
out.push(h('del', {}, ...inline(n.children, ctx, mode)));
|
||||
break;
|
||||
case 'inlineCode':
|
||||
out.push(h('code', { className: ['kb-code'] }, n.value ?? ''));
|
||||
break;
|
||||
case 'break':
|
||||
out.push(h('br', {}));
|
||||
break;
|
||||
case 'link':
|
||||
out.push(
|
||||
mode === 'flat'
|
||||
? h('span', { className: ['kb-ulink'] }, ...inline(n.children, ctx, mode))
|
||||
: h(
|
||||
'a',
|
||||
{ className: ['kb-a'], href: n.url ?? '', target: '_blank', rel: ['noopener', 'noreferrer'] },
|
||||
...inline(n.children, ctx, mode),
|
||||
),
|
||||
);
|
||||
break;
|
||||
case 'wikiLink': {
|
||||
const slug = n.slug ?? '';
|
||||
const title = ctx.opts.resolveLink?.(slug);
|
||||
ctx.links.push(slug);
|
||||
if (title === undefined && ctx.opts.resolveLink) ctx.brokenLinks.push(slug);
|
||||
const broken = title === undefined && !!ctx.opts.resolveLink;
|
||||
if (mode === 'flat') {
|
||||
out.push(
|
||||
h(
|
||||
'span',
|
||||
{ className: broken ? ['kb-ulink', 'kb-link--broken'] : ['kb-ulink'], dataSlug: slug },
|
||||
title ?? slug,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
out.push(
|
||||
h(
|
||||
'a',
|
||||
{
|
||||
className: broken ? ['kb-link', 'kb-link--broken'] : ['kb-link'],
|
||||
href: `/a/${slug}`,
|
||||
dataSlug: slug,
|
||||
},
|
||||
h('span', { className: ['kb-link-arrow'], ariaHidden: 'true' }, '→'),
|
||||
h('span', { className: ['kb-link-t'] }, title ?? slug),
|
||||
),
|
||||
);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'image':
|
||||
// Картинка посреди текста: показываем подпись, сам рисунок выносится в блок фото
|
||||
out.push(text(n.alt ?? ''));
|
||||
break;
|
||||
case 'textDirective':
|
||||
// remark-directive принимает «:слово» за директиву. Возвращаем текст как был.
|
||||
out.push(text(`:${n.name ?? ''}`), ...inline(n.children, ctx, mode));
|
||||
break;
|
||||
case 'html':
|
||||
// Сырой HTML из Markdown не пропускаем вообще
|
||||
break;
|
||||
default:
|
||||
if (n.children) out.push(...inline(n.children, ctx, mode));
|
||||
else if (n.value) out.push(text(n.value));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Абзац состоит только из картинок (и переводов строк между ними)? */
|
||||
function onlyImages(p: MdNode): MdNode[] | null {
|
||||
const imgs: MdNode[] = [];
|
||||
for (const c of p.children ?? []) {
|
||||
if (c.type === 'image') imgs.push(c);
|
||||
else if (c.type === 'break' || (c.type === 'text' && !(c.value ?? '').trim())) continue;
|
||||
else return null;
|
||||
}
|
||||
return imgs.length ? imgs : null;
|
||||
}
|
||||
|
||||
function figure(img: MdNode, first: boolean, ctx: RenderContext): HNode {
|
||||
const src = img.url ?? '';
|
||||
const urls = assetUrls(src);
|
||||
const caption = img.alt ?? '';
|
||||
const idx = ctx.figures.length;
|
||||
ctx.figures.push({ src, full: urls.full, thumb: urls.thumb, caption, file: urls.file });
|
||||
const size = urls.key ? ctx.opts.imageSize?.(urls.key) : undefined;
|
||||
|
||||
const imgProps: Props = {
|
||||
className: ['kb-fig-img'],
|
||||
alt: caption,
|
||||
loading: 'lazy',
|
||||
decoding: 'async',
|
||||
dataFile: urls.file,
|
||||
};
|
||||
if (first) {
|
||||
// Первое фото во всю ширину: телефон берёт превью 480, большой экран 1600
|
||||
imgProps.src = urls.full;
|
||||
if (urls.key) {
|
||||
imgProps.srcSet = `${urls.thumb} 480w, ${urls.full} 1600w`;
|
||||
imgProps.sizes = '(max-width: 760px) 100vw, 720px';
|
||||
}
|
||||
if (size) {
|
||||
imgProps.width = size.width;
|
||||
imgProps.height = size.height;
|
||||
}
|
||||
} else {
|
||||
imgProps.src = urls.thumb;
|
||||
imgProps.width = 480;
|
||||
imgProps.height = 480;
|
||||
}
|
||||
|
||||
return h(
|
||||
'figure',
|
||||
{ className: first ? ['kb-fig', 'kb-fig--first'] : ['kb-fig'] },
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', className: ['kb-fig-btn'], dataFig: idx, ariaLabel: `Увеличить: ${caption}` },
|
||||
h('img', imgProps),
|
||||
first ? h('span', { className: ['kb-fig-zoom'], ariaHidden: 'true' }, 'Увеличить') : null,
|
||||
),
|
||||
h('figcaption', { className: ['kb-fig-cap'] }, caption),
|
||||
);
|
||||
}
|
||||
|
||||
function figures(imgs: MdNode[], ctx: RenderContext): HNode {
|
||||
const [first, ...rest] = imgs;
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-figs'] },
|
||||
first ? figure(first, true, ctx) : null,
|
||||
rest.length ? h('div', { className: ['kb-figs-grid'] }, ...rest.map((i) => figure(i, false, ctx))) : null,
|
||||
);
|
||||
}
|
||||
|
||||
/** Содержимое пункта списка как инлайн (у пункта внутри лежит абзац). */
|
||||
function itemInline(item: MdNode): MdNode[] {
|
||||
const out: MdNode[] = [];
|
||||
for (const c of item.children ?? []) {
|
||||
if (c.type === 'paragraph') {
|
||||
if (out.length) out.push({ type: 'text', value: ' ' });
|
||||
out.push(...(c.children ?? []));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Строки внутри :::блока: каждый абзац и каждый пункт списка становится отдельной строкой. */
|
||||
function directiveLines(node: MdNode): MdNode[][] {
|
||||
const lines: MdNode[][] = [];
|
||||
for (const c of node.children ?? []) {
|
||||
if (c.type === 'paragraph') lines.push(c.children ?? []);
|
||||
else if (c.type === 'list') for (const li of c.children ?? []) lines.push(itemInline(li));
|
||||
else lines.push([{ type: 'text', value: plainText(c) }]);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** «Подпись: значение» → подпись отдельно. Двоеточие ищем в начале строки (до 44 знаков). */
|
||||
export function splitLabel(nodes: MdNode[]): { label: string; rest: MdNode[] } {
|
||||
const first = nodes[0];
|
||||
if (first?.type === 'text' && first.value) {
|
||||
const c = first.value.indexOf(':');
|
||||
if (c > -1 && c < 44) {
|
||||
const tail = first.value.slice(c + 1).replace(/^\s+/, '');
|
||||
const rest = tail ? [{ type: 'text', value: tail }, ...nodes.slice(1)] : nodes.slice(1);
|
||||
return { label: first.value.slice(0, c).trim(), rest };
|
||||
}
|
||||
}
|
||||
return { label: '', rest: nodes };
|
||||
}
|
||||
|
||||
function keyfacts(node: MdNode, ctx: RenderContext): HNode {
|
||||
const items = directiveLines(node).map((line) => {
|
||||
const { label, rest } = splitLabel(line);
|
||||
const len = rest.map(plainText).join('').length;
|
||||
// Длинное значение занимает всю ширину, короткое встаёт плиткой в две колонки
|
||||
const wide = len > 24;
|
||||
const segs = rest.map((n) =>
|
||||
n.type === 'strong'
|
||||
? h('span', { className: ['kb-key-v'] }, ...inline(n.children, ctx, 'flat'))
|
||||
: h('span', { className: ['kb-key-t'] }, ...inline([n], ctx, 'flat')),
|
||||
);
|
||||
return h(
|
||||
'div',
|
||||
{ className: wide ? ['kb-key-item', 'kb-key-item--wide'] : ['kb-key-item'] },
|
||||
label ? h('div', { className: ['kb-key-label'] }, label) : null,
|
||||
h('div', { className: ['kb-key-val'] }, ...segs),
|
||||
);
|
||||
});
|
||||
const n = items.length;
|
||||
return h(
|
||||
'section',
|
||||
{ className: ['kb-key'] },
|
||||
h('div', { className: ['kb-hazard'], ariaHidden: 'true' }),
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-key-head'] },
|
||||
h('div', { className: ['kb-key-title'] }, 'Главное'),
|
||||
h('div', { className: ['kb-key-count'] }, `${n} ${plural(n, ['пункт', 'пункта', 'пунктов'])}`),
|
||||
),
|
||||
h('div', { className: ['kb-key-grid'] }, ...items),
|
||||
);
|
||||
}
|
||||
|
||||
const CALLOUTS: Record<string, string> = {
|
||||
danger: 'ЗАПРЕЩЕНО',
|
||||
warning: 'ВНИМАНИЕ',
|
||||
tip: 'СОВЕТ',
|
||||
info: 'СПРАВКА',
|
||||
};
|
||||
|
||||
function callout(kind: string, node: MdNode, ctx: RenderContext): HNode {
|
||||
const paras = directiveLines(node).map((line) => h('p', {}, ...inline(line, ctx, 'flat')));
|
||||
const props: Props = { className: ['kb-callout', `kb-${kind}`] };
|
||||
if (kind === 'danger') props.role = 'alert';
|
||||
return h(
|
||||
'section',
|
||||
props,
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-callout-head'] },
|
||||
h('span', { className: ['kb-callout-icon'], ariaHidden: 'true' }),
|
||||
CALLOUTS[kind] ?? kind,
|
||||
),
|
||||
h('div', { className: ['kb-callout-body'] }, ...paras),
|
||||
);
|
||||
}
|
||||
|
||||
function checklist(list: MdNode, ctx: RenderContext): HNode {
|
||||
const gid = ctx.checkGroups++;
|
||||
const items = list.children ?? [];
|
||||
return h(
|
||||
'section',
|
||||
{ className: ['kb-check'], dataCheck: gid },
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-check-head'] },
|
||||
h('div', { className: ['kb-check-title'] }, 'Чек-лист'),
|
||||
h('div', { className: ['kb-check-count'] }, `0 из ${items.length}`),
|
||||
h('button', { type: 'button', className: ['kb-check-reset'] }, 'Сбросить'),
|
||||
),
|
||||
h('div', { className: ['kb-check-bar'] }, h('div', { className: ['kb-check-fill'] })),
|
||||
...items.map((it, i) =>
|
||||
h(
|
||||
'button',
|
||||
{ type: 'button', className: ['kb-check-row'], dataI: i, ariaPressed: 'false' },
|
||||
h('span', { className: ['kb-box'], ariaHidden: 'true' }),
|
||||
h('span', { className: ['kb-check-text'] }, ...inline(itemInline(it), ctx, 'flat')),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function steps(list: MdNode, ctx: RenderContext): HNode {
|
||||
const start = list.start ?? 1;
|
||||
return h(
|
||||
'ol',
|
||||
{ className: ['kb-steps'] },
|
||||
...(list.children ?? []).map((it, i) => {
|
||||
let nodes = itemInline(it);
|
||||
let title: HNode | null = null;
|
||||
// «1. **Заголовок.** текст»: жирное начало становится заголовком шага
|
||||
if (nodes[0]?.type === 'strong') {
|
||||
title = h('div', { className: ['kb-step-title'] }, ...inline(nodes[0].children, ctx, 'flat'));
|
||||
nodes = nodes.slice(1);
|
||||
if (nodes[0]?.type === 'text') nodes[0] = { type: 'text', value: (nodes[0].value ?? '').replace(/^\s+/, '') };
|
||||
}
|
||||
const body = inline(nodes, ctx, 'flat');
|
||||
return h(
|
||||
'li',
|
||||
{ className: ['kb-step'] },
|
||||
h('span', { className: ['kb-step-n'] }, String(start + i)),
|
||||
h('div', { className: ['kb-step-main'] }, title, body.length ? h('div', {}, ...body) : null),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function table(node: MdNode, ctx: RenderContext): HNode {
|
||||
const rows = (node.children ?? []).map((r) => r.children ?? []);
|
||||
const head = rows[0] ?? [];
|
||||
const body = rows.slice(1);
|
||||
const cell = (c: MdNode | undefined, mode: InlineMode = 'chip') => inline(c?.children, ctx, mode);
|
||||
|
||||
// Две колонки: «что → значение», значение крупно справа
|
||||
if (head.length === 2) {
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-kv'], role: 'table' },
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-kv-head'], role: 'row' },
|
||||
h('span', { role: 'columnheader' }, ...cell(head[0], 'flat')),
|
||||
h('span', { role: 'columnheader' }, ...cell(head[1], 'flat')),
|
||||
),
|
||||
...body.map((r) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-kv-row'], role: 'row' },
|
||||
h('span', { className: ['kb-kv-k'], role: 'cell' }, ...cell(r[0], 'flat')),
|
||||
h('span', { className: ['kb-kv-v'], role: 'cell' }, ...cell(r[1], 'flat')),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Три колонки и больше: каждая строка становится карточкой, первая ячейка: заголовок
|
||||
return h(
|
||||
'div',
|
||||
{ className: ['kb-cards'] },
|
||||
...body.map((r) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-card'] },
|
||||
h('div', { className: ['kb-card-title'] }, ...cell(r[0])),
|
||||
...r.slice(1).map((c, j) =>
|
||||
h(
|
||||
'div',
|
||||
{ className: ['kb-card-row'] },
|
||||
h('span', { className: ['kb-card-label'] }, plainText(head[j + 1] ?? { type: 'text', value: '' })),
|
||||
h('span', { className: ['kb-card-val'] }, ...cell(c)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function block(node: MdNode, ctx: RenderContext): HNode | null {
|
||||
switch (node.type) {
|
||||
case 'heading': {
|
||||
const t = plainText(node).trim();
|
||||
if ((node.depth ?? 2) <= 2) {
|
||||
const id = `h-${ctx.toc.length}`;
|
||||
ctx.toc.push({ id, text: t });
|
||||
return h('h2', { className: ['kb-h2'], id }, ...inline(node.children, ctx, 'flat'));
|
||||
}
|
||||
return h('h3', { className: ['kb-h3'] }, ...inline(node.children, ctx, 'flat'));
|
||||
}
|
||||
case 'paragraph': {
|
||||
const imgs = onlyImages(node);
|
||||
if (imgs) return figures(imgs, ctx);
|
||||
return h('p', { className: ['kb-p'] }, ...inline(node.children, ctx, 'chip'));
|
||||
}
|
||||
case 'containerDirective': {
|
||||
const name = node.name ?? '';
|
||||
if (name === 'keyfacts') return keyfacts(node, ctx);
|
||||
if (name in CALLOUTS) return callout(name, node, ctx);
|
||||
// Неизвестный блок показываем как справку, чтобы текст не пропал
|
||||
return callout('info', node, ctx);
|
||||
}
|
||||
case 'list': {
|
||||
const items = node.children ?? [];
|
||||
if (items.length && items.every((i) => typeof i.checked === 'boolean')) return checklist(node, ctx);
|
||||
if (node.ordered) return steps(node, ctx);
|
||||
return h(
|
||||
'ul',
|
||||
{ className: ['kb-ul'] },
|
||||
...items.map((it) => h('li', {}, h('span', {}, ...inline(itemInline(it), ctx, 'chip')))),
|
||||
);
|
||||
}
|
||||
case 'table':
|
||||
return table(node, ctx);
|
||||
case 'blockquote':
|
||||
return h('blockquote', { className: ['kb-quote'] }, ...blocks(node.children ?? [], ctx));
|
||||
case 'code':
|
||||
return h('pre', { className: ['kb-pre'] }, h('code', {}, node.value ?? ''));
|
||||
case 'thematicBreak':
|
||||
return h('hr', { className: ['kb-hr'] });
|
||||
case 'leafDirective':
|
||||
return h('p', { className: ['kb-p'] }, `::${node.name ?? ''}`, ...inline(node.children, ctx, 'chip'));
|
||||
case 'html':
|
||||
case 'definition':
|
||||
case 'footnoteDefinition':
|
||||
return null;
|
||||
default:
|
||||
return node.children ? h('div', {}, ...blocks(node.children, ctx)) : null;
|
||||
}
|
||||
}
|
||||
|
||||
function blocks(nodes: MdNode[], ctx: RenderContext): HNode[] {
|
||||
return nodes.map((n) => block(n, ctx)).filter((n): n is HNode => n !== null);
|
||||
}
|
||||
|
||||
export function toHast(tree: MdNode, ctx: RenderContext): HNode {
|
||||
return { type: 'root', children: blocks(tree.children ?? [], ctx) };
|
||||
}
|
||||
+137
-2
@@ -1,2 +1,137 @@
|
||||
// Общий Markdown-рендер (сервер + клиент). Наполняется на этапе 2.
|
||||
export const MD_PACKAGE = '@kb/md';
|
||||
// @kb/md: единственное место, где Markdown статьи превращается в HTML.
|
||||
// Используется сервером (bodyHtml при сохранении, текст для поиска) и клиентом
|
||||
// (живой предпросмотр в редакторе), поэтому результат всегда одинаковый.
|
||||
|
||||
import { unified } from 'unified';
|
||||
import rehypeSanitize, { defaultSchema } from 'rehype-sanitize';
|
||||
import rehypeStringify from 'rehype-stringify';
|
||||
import { type FigureInfo, type HNode, type RenderContext, type RenderOptions, type TocItem, splitLabel, toHast } from './hast.js';
|
||||
import { type MdNode, parseMarkdown, plainText } from './parse.js';
|
||||
|
||||
export { parseFrontMatter, type FrontMatter } from './frontmatter.js';
|
||||
export { assetUrls, assetKey, type AssetUrls } from './assets.js';
|
||||
export { parseCheatSheet, type CheatSheet, type CheatLine } from './cheatsheet.js';
|
||||
export { parseMarkdown, plainText, type MdNode } from './parse.js';
|
||||
export type { RenderOptions, TocItem, FigureInfo } from './hast.js';
|
||||
|
||||
// Белый список тегов и атрибутов. HTML мы строим сами, но на всякий случай прогоняем
|
||||
// через санитайзер: он же отсекает опасные адреса вроде javascript: в ссылках.
|
||||
const schema: typeof defaultSchema = {
|
||||
...defaultSchema,
|
||||
clobber: [], // не добавлять префикс к id заголовков (h-0, h-1): они наши, а не от автора
|
||||
strip: ['script', 'style'],
|
||||
tagNames: [
|
||||
'h2', 'h3', 'p', 'strong', 'em', 'del', 'code', 'br', 'a', 'span', 'div', 'section',
|
||||
'figure', 'figcaption', 'button', 'img', 'ul', 'ol', 'li', 'blockquote', 'pre', 'hr',
|
||||
],
|
||||
attributes: {
|
||||
'*': ['className', 'id', 'role', 'ariaHidden', 'ariaLabel', 'ariaPressed', 'data*'],
|
||||
a: ['href', 'target', 'rel'],
|
||||
img: ['src', 'srcSet', 'sizes', 'alt', 'loading', 'decoding', 'width', 'height'],
|
||||
button: ['type'],
|
||||
},
|
||||
protocols: {
|
||||
href: ['http', 'https', 'mailto', 'tel'],
|
||||
src: ['http', 'https'],
|
||||
},
|
||||
};
|
||||
|
||||
const htmlProcessor = unified().use(rehypeSanitize, schema).use(rehypeStringify);
|
||||
|
||||
export interface FactItem {
|
||||
label: string;
|
||||
/** Значение в Markdown: «только **порты 1 и 2** коммутатора». */
|
||||
value: string;
|
||||
}
|
||||
|
||||
export interface RenderResult {
|
||||
html: string;
|
||||
/** Заголовки H2 для оглавления. */
|
||||
toc: TocItem[];
|
||||
/** Все рисунки статьи по порядку (для просмотрщика и офлайн-кеша). */
|
||||
figures: FigureInfo[];
|
||||
/** Все [[slug]] из текста. */
|
||||
links: string[];
|
||||
/** [[slug]], для которых статья не нашлась. */
|
||||
brokenLinks: string[];
|
||||
/** Пункты блоков «Главное». */
|
||||
facts: FactItem[];
|
||||
/** Текст без разметки по частям: для поиска. */
|
||||
text: { keyfacts: string; body: string };
|
||||
}
|
||||
|
||||
/** Собрать Markdown обратно из инлайн-узлов (нужен только жирный). */
|
||||
function inlineMd(nodes: MdNode[]): string {
|
||||
return nodes
|
||||
.map((n) => (n.type === 'strong' ? `**${plainText(n)}**` : plainText(n)))
|
||||
.join('')
|
||||
.trim();
|
||||
}
|
||||
|
||||
function collectFacts(tree: MdNode): FactItem[] {
|
||||
const facts: FactItem[] = [];
|
||||
for (const node of tree.children ?? []) {
|
||||
if (node.type !== 'containerDirective' || node.name !== 'keyfacts') continue;
|
||||
for (const c of node.children ?? []) {
|
||||
const lines =
|
||||
c.type === 'list'
|
||||
? (c.children ?? []).map((li) => (li.children ?? []).flatMap((p) => p.children ?? []))
|
||||
: [c.children ?? []];
|
||||
for (const line of lines) {
|
||||
const { label, rest } = splitLabel(line);
|
||||
const value = inlineMd(rest);
|
||||
if (value) facts.push({ label, value });
|
||||
}
|
||||
}
|
||||
}
|
||||
return facts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Главная функция пакета: Markdown (без front matter) → HTML и всё, что из него извлекается.
|
||||
*/
|
||||
export function renderMarkdown(md: string, opts: RenderOptions = {}): RenderResult {
|
||||
const tree = parseMarkdown(md);
|
||||
const ctx: RenderContext = { opts, toc: [], figures: [], links: [], brokenLinks: [], checkGroups: 0 };
|
||||
const hast = toHast(tree, ctx);
|
||||
// HNode совместим с типом Root из hast, но описан проще: приводим тип для unified
|
||||
const clean = htmlProcessor.runSync(hast as unknown as Parameters<typeof htmlProcessor.runSync>[0]);
|
||||
const html = htmlProcessor.stringify(clean as Parameters<typeof htmlProcessor.stringify>[0]) as string;
|
||||
|
||||
const keyfacts: string[] = [];
|
||||
const body: string[] = [];
|
||||
for (const node of tree.children ?? []) {
|
||||
const t = plainText(node).replace(/\s+/g, ' ').trim();
|
||||
if (!t) continue;
|
||||
if (node.type === 'containerDirective' && node.name === 'keyfacts') keyfacts.push(blockText(node));
|
||||
else body.push(node.children && node.type !== 'paragraph' && node.type !== 'heading' ? blockText(node) : t);
|
||||
}
|
||||
|
||||
return {
|
||||
html,
|
||||
toc: ctx.toc,
|
||||
figures: ctx.figures,
|
||||
links: [...new Set(ctx.links)],
|
||||
brokenLinks: [...new Set(ctx.brokenLinks)],
|
||||
facts: collectFacts(tree),
|
||||
text: { keyfacts: keyfacts.join('\n'), body: body.join('\n') },
|
||||
};
|
||||
}
|
||||
|
||||
/** Текст блока, где пункты списка и ячейки таблицы разделены переводом строки (а не слиты в одно слово). */
|
||||
function blockText(node: MdNode): string {
|
||||
const parts: string[] = [];
|
||||
const walk = (n: MdNode) => {
|
||||
if (n.type === 'paragraph' || n.type === 'heading' || n.type === 'tableCell') {
|
||||
const t = plainText(n).replace(/\s+/g, ' ').trim();
|
||||
if (t) parts.push(t);
|
||||
return;
|
||||
}
|
||||
if (n.children) n.children.forEach(walk);
|
||||
else if (n.value?.trim()) parts.push(n.value.trim());
|
||||
};
|
||||
walk(node);
|
||||
return parts.join('\n');
|
||||
}
|
||||
|
||||
export type { HNode };
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { assetUrls, parseCheatSheet, parseFrontMatter, renderMarkdown } from './index.js';
|
||||
|
||||
describe('front matter', () => {
|
||||
it('терпит двоеточие в значении и запятую без пробела в списке', () => {
|
||||
const { meta, body } = parseFrontMatter(
|
||||
[
|
||||
'---',
|
||||
'title: Заголовок',
|
||||
'summary: Карта стойки: верх — оптика',
|
||||
'equipment: [Fortisflex MG-12 80033, уголок 130х130х100х1,8, FTP Cat5e]',
|
||||
'source: [originals/a.pdf, originals/b.pdf]',
|
||||
'pinned: true',
|
||||
'order: 3',
|
||||
'---',
|
||||
'',
|
||||
'Текст',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(meta.summary).toBe('Карта стойки: верх — оптика');
|
||||
expect(meta.equipment).toEqual(['Fortisflex MG-12 80033', 'уголок 130х130х100х1,8', 'FTP Cat5e']);
|
||||
expect(meta.source).toHaveLength(2);
|
||||
expect(meta.pinned).toBe(true);
|
||||
expect(meta.order).toBe(3);
|
||||
expect(body.trim()).toBe('Текст');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderMarkdown', () => {
|
||||
it('рисует блок «Главное» и собирает факты', () => {
|
||||
const r = renderMarkdown(':::keyfacts\n- Запас: **20 см** (под светофор)\n- Сальник: **MG-12**\n:::');
|
||||
expect(r.html).toContain('kb-key');
|
||||
expect(r.html).toContain('2 пункта');
|
||||
expect(r.facts).toEqual([
|
||||
{ label: 'Запас', value: '**20 см** (под светофор)' },
|
||||
{ label: 'Сальник', value: '**MG-12**' },
|
||||
]);
|
||||
expect(r.text.keyfacts).toContain('20 см');
|
||||
});
|
||||
|
||||
it('рисует запрет, чек-лист, шаги и таблицы', () => {
|
||||
const r = renderMarkdown(
|
||||
[
|
||||
':::danger',
|
||||
'Нельзя **так**.',
|
||||
':::',
|
||||
'',
|
||||
'- [ ] Раз',
|
||||
'- [x] Два',
|
||||
'',
|
||||
'1. **Шаг.** Сделать',
|
||||
'',
|
||||
'| Куда | Длина |',
|
||||
'|---|---|',
|
||||
'| SIP | **2 м** |',
|
||||
'',
|
||||
'| A | B | C |',
|
||||
'|---|---|---|',
|
||||
'| 1 | 2 | 3 |',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(r.html).toContain('kb-danger');
|
||||
expect(r.html).toContain('ЗАПРЕЩЕНО');
|
||||
expect(r.html).toContain('data-check="0"');
|
||||
expect(r.html).toContain('0 из 2');
|
||||
expect(r.html).toContain('kb-step-title');
|
||||
expect(r.html).toContain('kb-kv');
|
||||
expect(r.html).toContain('kb-cards');
|
||||
});
|
||||
|
||||
it('подставляет названия в [[ссылки]] и отмечает битые', () => {
|
||||
const r = renderMarkdown('См. [[shkon]] и [[net-takoy]]', {
|
||||
resolveLink: (s) => (s === 'shkon' ? 'ШКОН' : undefined),
|
||||
});
|
||||
expect(r.links).toEqual(['shkon', 'net-takoy']);
|
||||
expect(r.brokenLinks).toEqual(['net-takoy']);
|
||||
expect(r.html).toContain('href="/a/shkon"');
|
||||
expect(r.html).toContain('>ШКОН<');
|
||||
expect(r.html).toContain('kb-link--broken');
|
||||
});
|
||||
|
||||
it('собирает фото в группу и оглавление по H2', () => {
|
||||
const r = renderMarkdown('## Фото\n\n\n');
|
||||
expect(r.toc).toEqual([{ id: 'h-0', text: 'Фото' }]);
|
||||
expect(r.figures.map((f) => f.full)).toEqual(['/uploads/assets/x/fig-1.webp', '/uploads/assets/x/fig-2.webp']);
|
||||
expect(r.html).toContain('/uploads/assets/x/fig-2.480.webp');
|
||||
expect(r.html).toContain('data-fig="1"');
|
||||
});
|
||||
|
||||
it('не пропускает HTML и опасные ссылки', () => {
|
||||
const r = renderMarkdown('<script>alert(1)</script>\n\n<img src=x onerror=alert(1)>\n\n[жми](javascript:alert(1))');
|
||||
expect(r.html).not.toContain('<script');
|
||||
expect(r.html).not.toContain('onerror');
|
||||
expect(r.html).not.toContain('javascript:');
|
||||
});
|
||||
|
||||
it('не зачёркивает текст между одиночными тильдами', () => {
|
||||
expect(renderMarkdown('Изолента ~15 см и ~30 см').html).not.toContain('<del');
|
||||
});
|
||||
});
|
||||
|
||||
describe('assetUrls', () => {
|
||||
it('строит адреса WebP и превью', () => {
|
||||
expect(assetUrls('assets/shkon/fig-1.jpg')).toMatchObject({
|
||||
full: '/uploads/assets/shkon/fig-1.webp',
|
||||
thumb: '/uploads/assets/shkon/fig-1.480.webp',
|
||||
file: 'fig-1.jpg',
|
||||
});
|
||||
expect(assetUrls('/uploads/2026/10/abc.webp').thumb).toBe('/uploads/2026/10/abc.480.webp');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseCheatSheet', () => {
|
||||
it('разбирает запреты, цифры, цвета и «всегда»', () => {
|
||||
const s = parseCheatSheet(
|
||||
[
|
||||
'## ⛔ Запрещено',
|
||||
'- Подключать **УЗИП до автомата** → только шинки → [[silovoe]]',
|
||||
'## 📏 Цифры',
|
||||
'| Что | Значение | Где |',
|
||||
'|---|---|---|',
|
||||
'| Изолента: ШКОН / ШКОС | **15 см / 30 см** | [[shkon]] · [[shkos]] |',
|
||||
'## 🎨 Цвета',
|
||||
'- Уголок фотоэлемента: **RAL 5017**',
|
||||
'## ✅ Всегда',
|
||||
'- бирки на ВОК **до** сварки',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(s.ok).toBe(true);
|
||||
expect(s.bans[0]?.links).toEqual(['silovoe']);
|
||||
expect(s.bans[0]?.segs.at(-1)?.t).toBe(' → только шинки');
|
||||
expect(s.facts[0]).toMatchObject({ value: '15 см / 30 см', links: ['shkon', 'shkos'] });
|
||||
expect(s.colors).toEqual([{ code: 'RAL 5017', label: 'Уголок фотоэлемента' }]);
|
||||
expect(s.always[0]?.segs).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { unified } from 'unified';
|
||||
import remarkParse from 'remark-parse';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import remarkDirective from 'remark-directive';
|
||||
|
||||
// Упрощённый тип узла Markdown-дерева (mdast). Полные типы из @types/mdast здесь
|
||||
// только мешают: у нас есть свои узлы (wikiLink, containerDirective).
|
||||
export interface MdNode {
|
||||
type: string;
|
||||
value?: string;
|
||||
children?: MdNode[];
|
||||
depth?: number;
|
||||
ordered?: boolean;
|
||||
start?: number | null;
|
||||
checked?: boolean | null;
|
||||
url?: string;
|
||||
alt?: string | null;
|
||||
title?: string | null;
|
||||
name?: string;
|
||||
slug?: string;
|
||||
lang?: string | null;
|
||||
}
|
||||
|
||||
const WIKI_RE = /\[\[([a-z0-9][a-z0-9-]*)\]\]/g;
|
||||
|
||||
/**
|
||||
* Свой remark-плагин: превращает текст `[[slug]]` в узел { type: 'wikiLink', slug }.
|
||||
* Дальше рендер делает из него ссылку-чип с названием статьи.
|
||||
*/
|
||||
function remarkWikiLinks() {
|
||||
return (tree: MdNode) => {
|
||||
const walk = (node: MdNode) => {
|
||||
if (!node.children) return;
|
||||
// Внутри кода ссылки не трогаем
|
||||
if (node.type === 'code' || node.type === 'inlineCode') return;
|
||||
const out: MdNode[] = [];
|
||||
for (const child of node.children) {
|
||||
if (child.type !== 'text' || !child.value || !child.value.includes('[[')) {
|
||||
walk(child);
|
||||
out.push(child);
|
||||
continue;
|
||||
}
|
||||
const text = child.value;
|
||||
let last = 0;
|
||||
for (const m of text.matchAll(WIKI_RE)) {
|
||||
const at = m.index ?? 0;
|
||||
if (at > last) out.push({ type: 'text', value: text.slice(last, at) });
|
||||
out.push({ type: 'wikiLink', slug: m[1] });
|
||||
last = at + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push({ type: 'text', value: text.slice(last) });
|
||||
}
|
||||
node.children = out;
|
||||
};
|
||||
walk(tree);
|
||||
};
|
||||
}
|
||||
|
||||
const processor = unified().use(remarkParse)
|
||||
// singleTilde: false, иначе «~15 см … ~30 см» в одном абзаце станет зачёркнутым текстом
|
||||
.use(remarkGfm, { singleTilde: false })
|
||||
.use(remarkDirective)
|
||||
.use(remarkWikiLinks);
|
||||
|
||||
/** Markdown (без front matter) → дерево mdast. */
|
||||
export function parseMarkdown(md: string): MdNode {
|
||||
const tree = processor.parse(md);
|
||||
return processor.runSync(tree) as unknown as MdNode;
|
||||
}
|
||||
|
||||
/** Весь текст узла подряд, без разметки. */
|
||||
export function plainText(node: MdNode): string {
|
||||
if (node.type === 'wikiLink') return '';
|
||||
if (node.type === 'image') return node.alt ?? '';
|
||||
if (node.type === 'break') return ' ';
|
||||
if (typeof node.value === 'string') return node.value;
|
||||
return (node.children ?? []).map(plainText).join('');
|
||||
}
|
||||
@@ -157,3 +157,34 @@ export function plural(n: number, forms: [string, string, string]): string {
|
||||
if (b === 1) return forms[0];
|
||||
return forms[2];
|
||||
}
|
||||
|
||||
// ---------- Нормализация текста для поиска (одинаковая при индексации и при запросе) ----------
|
||||
|
||||
/** Нижний регистр, ё→е, все виды тире → дефис, лишние пробелы убраны. */
|
||||
export function normalizeSearch(s: string): string {
|
||||
return s
|
||||
.toLowerCase()
|
||||
.replace(/ё/g, 'е')
|
||||
.replace(/[‐-―−]/g, '-')
|
||||
.replace(/[ ]/g, ' ')
|
||||
.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);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user