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

486 lines
18 KiB
TypeScript

// 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;
}
/**
* Делит абзац по переводам строк: в :::блоке каждая строка исходника становится
* отдельной строкой на экране (Markdown сам по себе склеил бы их в один абзац).
*/
function splitLines(nodes: MdNode[]): MdNode[][] {
const lines: MdNode[][] = [[]];
for (const n of nodes) {
if (n.type === 'break') {
lines.push([]);
} else if (n.type === 'text' && n.value?.includes('\n')) {
n.value.split('\n').forEach((part, i) => {
if (i > 0) lines.push([]);
if (part) lines.at(-1)!.push({ type: 'text', value: part });
});
} else {
lines.at(-1)!.push(n);
}
}
return lines.filter((l) => l.length);
}
/** Строки внутри :::блока: каждый абзац и каждый пункт списка становится отдельной строкой. */
function directiveLines(node: MdNode): MdNode[][] {
const lines: MdNode[][] = [];
for (const c of node.children ?? []) {
if (c.type === 'paragraph') lines.push(...splitLines(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) };
}