|
| 1 | +import MarkdownIt from 'markdown-it'; |
| 2 | +import markdownItTaskLists from 'markdown-it-task-lists'; |
| 3 | +import markdownItGithubAlerts from 'markdown-it-github-alerts'; |
| 4 | +import markdownItKatex from '@neilsustc/markdown-it-katex'; |
| 5 | +import markdownItFootnote from 'markdown-it-footnote'; |
| 6 | +import markdownItDeflist from 'markdown-it-deflist'; |
| 7 | +import * as markdownItEmoji from 'markdown-it-emoji'; |
| 8 | +import markdownItSub from 'markdown-it-sub'; |
| 9 | +import markdownItSup from 'markdown-it-sup'; |
| 10 | +import hljs from 'highlight.js'; |
| 11 | +import { slugifyHeading } from './slugify'; |
| 12 | +import SlugifyMode from './slugifyMode'; |
| 13 | + |
| 14 | +export interface MarkdownRenderOptions { |
| 15 | + breaks?: boolean; |
| 16 | + linkify?: boolean; |
| 17 | + enableMath?: boolean; |
| 18 | + slugifyMode?: SlugifyMode; |
| 19 | + mathMacros?: Record<string, string>; |
| 20 | +} |
| 21 | + |
| 22 | +interface MathOptions { |
| 23 | + throwOnError?: boolean; |
| 24 | + macros?: Record<string, string>; |
| 25 | +} |
| 26 | + |
| 27 | +interface EngineRecord { |
| 28 | + md: MarkdownIt; |
| 29 | + slugCount: Map<string, number>; |
| 30 | +} |
| 31 | + |
| 32 | +export class MarkdownRenderer { |
| 33 | + private engines = new Map<string, EngineRecord>(); |
| 34 | + |
| 35 | + public render(text: string, options: MarkdownRenderOptions = {}): string { |
| 36 | + const enableMath = options.enableMath !== false; |
| 37 | + const slugifyMode = options.slugifyMode ?? SlugifyMode.GitHub; |
| 38 | + const key = this.composeEngineKey(enableMath, slugifyMode, options.mathMacros); |
| 39 | + const engineRecord = this.ensureEngine(key, enableMath, slugifyMode, options.mathMacros); |
| 40 | + |
| 41 | + engineRecord.slugCount.clear(); |
| 42 | + |
| 43 | + engineRecord.md.set({ |
| 44 | + breaks: options.breaks === true, |
| 45 | + linkify: options.linkify !== false, |
| 46 | + }); |
| 47 | + |
| 48 | + const env = Object.create(null); |
| 49 | + return engineRecord.md.render(text, env); |
| 50 | + } |
| 51 | + |
| 52 | + private composeEngineKey(enableMath: boolean, slugifyMode: SlugifyMode, macros?: Record<string, string>): string { |
| 53 | + const macroEntries = macros ? Object.keys(macros).sort().map((k) => `${k}:${macros[k]}`) : []; |
| 54 | + return `${enableMath ? 'math' : 'nomath'}|${slugifyMode}|${macroEntries.join(',')}`; |
| 55 | + } |
| 56 | + |
| 57 | + private ensureEngine(key: string, enableMath: boolean, slugifyMode: SlugifyMode, macros?: Record<string, string>): EngineRecord { |
| 58 | + let record = this.engines.get(key); |
| 59 | + if (!record) { |
| 60 | + const slugCount = new Map<string, number>(); |
| 61 | + const md = this.createEngine(enableMath, slugCount, slugifyMode, macros); |
| 62 | + record = { md, slugCount }; |
| 63 | + this.engines.set(key, record); |
| 64 | + } |
| 65 | + return record; |
| 66 | + } |
| 67 | + |
| 68 | + private createEngine(enableMath: boolean, slugCount: Map<string, number>, slugifyMode: SlugifyMode, macros?: Record<string, string>): MarkdownIt { |
| 69 | + const md = new MarkdownIt({ |
| 70 | + html: true, |
| 71 | + highlight: (str: string, lang?: string) => { |
| 72 | + if (lang) { |
| 73 | + const normalized = this.normalizeHighlightLang(lang); |
| 74 | + if (normalized && hljs.getLanguage(normalized)) { |
| 75 | + try { |
| 76 | + return hljs.highlight(str, { language: normalized, ignoreIllegals: true }).value; |
| 77 | + } catch { |
| 78 | + // ignore highlighting errors and fallback to default rendering |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + return ''; |
| 83 | + } |
| 84 | + }); |
| 85 | + |
| 86 | + md.use(markdownItTaskLists, { enabled: true, label: true, labelAfter: false }); |
| 87 | + md.use(markdownItGithubAlerts, { matchCaseSensitive: false }); |
| 88 | + md.use(markdownItFootnote); |
| 89 | + md.use(markdownItDeflist); |
| 90 | + md.use(markdownItEmoji.full || markdownItEmoji); |
| 91 | + md.use(markdownItSub); |
| 92 | + md.use(markdownItSup); |
| 93 | + |
| 94 | + if (enableMath) { |
| 95 | + require('katex/contrib/mhchem'); |
| 96 | + const katexOptions: MathOptions = { throwOnError: false }; |
| 97 | + if (macros && Object.keys(macros).length > 0) { |
| 98 | + katexOptions.macros = JSON.parse(JSON.stringify(macros)); |
| 99 | + } |
| 100 | + md.use(markdownItKatex, katexOptions); |
| 101 | + } |
| 102 | + |
| 103 | + this.addNamedHeaders(md, slugCount, slugifyMode); |
| 104 | + return md; |
| 105 | + } |
| 106 | + |
| 107 | + private addNamedHeaders(md: MarkdownIt, slugCount: Map<string, number>, slugifyMode: SlugifyMode): void { |
| 108 | + const originalHeadingOpen = md.renderer.rules.heading_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); |
| 109 | + |
| 110 | + md.renderer.rules.heading_open = (tokens, idx, options, env, self) => { |
| 111 | + const raw = tokens[idx + 1]?.content ?? ''; |
| 112 | + const baseSlug = slugifyHeading(raw, env ?? Object.create(null), slugifyMode) || 'section'; |
| 113 | + const finalSlug = this.resolveUniqueSlug(slugCount, baseSlug); |
| 114 | + tokens[idx].attrs = [...(tokens[idx].attrs || []), ['id', finalSlug]]; |
| 115 | + |
| 116 | + return originalHeadingOpen(tokens, idx, options, env, self); |
| 117 | + }; |
| 118 | + } |
| 119 | + |
| 120 | + private resolveUniqueSlug(slugCount: Map<string, number>, base: string): string { |
| 121 | + const previous = slugCount.get(base); |
| 122 | + if (previous === undefined) { |
| 123 | + slugCount.set(base, 0); |
| 124 | + return base; |
| 125 | + } |
| 126 | + |
| 127 | + const next = previous + 1; |
| 128 | + slugCount.set(base, next); |
| 129 | + return `${base}-${next}`; |
| 130 | + } |
| 131 | + |
| 132 | + private normalizeHighlightLang(lang: string): string { |
| 133 | + switch (lang.toLowerCase()) { |
| 134 | + case 'tsx': |
| 135 | + case 'typescriptreact': |
| 136 | + return 'jsx'; |
| 137 | + case 'json5': |
| 138 | + case 'jsonc': |
| 139 | + return 'json'; |
| 140 | + case 'c#': |
| 141 | + case 'csharp': |
| 142 | + return 'cs'; |
| 143 | + default: |
| 144 | + return lang.toLowerCase(); |
| 145 | + } |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +export const markdownRenderer = new MarkdownRenderer(); |
0 commit comments