/
githubmirror
/
marktext
Обзор
Документация
Войти
/
githubmirror
/
marktext
Код
Запросы
0
Пакеты
0
Релизы
0
Аналитика
Безопасность
develop
packages/muya/src/state/getTOC.ts
72 строки
2 KB
Ran Luo
fix(muya): show and slug TOC headings by rendered plain text (#3516) (#4811)
02 июл 2026, 18:24
Не верифицирован
02 июл 2026, 18:24
dd072c1
Код
Авторство
О чём код?
import type Content from '../block/base/content'; import type Parent from '../block/base/parent'; import type { Muya } from '../muya'; import { tokenizer, tokensToPlainText } from '../inlineRenderer/lexer'; import { getUniqueId } from '../utils'; import { generateGithubSlug } from '../utils/slug'; export interface ITocItem { content: string; lvl: number; slug: string; githubSlug: string; } interface IHeadingBlock extends Parent { meta: { level: number }; } const slugCache = new WeakMap<Parent, string>(); export function stableSlug(block: Parent): string { let slug = slugCache.get(block); if (slug == null) { slug = getUniqueId(); slugCache.set(block, slug); } return slug; } export function getTOC(muya: Muya): ITocItem[] { const { scrollPage } = muya.editor; if (!scrollPage) return []; const items: ITocItem[] = []; for (const node of scrollPage.children.iterator()) { const { blockName } = node; if (blockName !== 'atx-heading' && blockName !== 'setext-heading') continue; const block = node as IHeadingBlock; const head = block.children.head as Content | null; const text = head?.text ?? ''; const source = blockName === 'setext-heading' ? text.trim() : text.replace(/^\s*#{1,6}\s+/, '').trim(); // Show and slug the heading by its rendered text — inline markdown // (`**bold**`, `[label](url)`, images) stripped to what a reader sees — // instead of the raw source (#4811). Slugging the same plain text keeps // `githubSlug` in step with the anchor id the HTML export injects from // `heading.textContent` (state/markdownToHtml.ts). const { superSubScript, footnote } = muya.options; const content = tokensToPlainText( tokenizer(source, { hasBeginRules: false, options: { superSubScript, footnote }, }), ).trim(); items.push({ content, lvl: block.meta.level, slug: stableSlug(block), githubSlug: generateGithubSlug(content), }); } return items; }