UNPKG

@wcj/markdown-to-html

Version:
90 lines 4.06 kB
import { VFile } from 'vfile'; import { unified } from 'unified'; import remarkGfm from 'remark-gfm'; import rehypeAttrs from 'rehype-attr'; import remarkParse from 'remark-parse'; import remarkRehype from 'remark-rehype'; import rehypeVideo from 'rehype-video'; import rehypeKatex from 'rehype-katex'; import rehypeIgnore from 'rehype-ignore'; import rehypeRaw from 'rehype-raw'; import rehypeRewrite, { getCodeString } from 'rehype-rewrite'; import stringify from 'rehype-stringify'; import rehypePrism from 'rehype-prism-plus'; export { getCodeString }; Object.defineProperty(rehypePrism, 'name', { value: 'rehypePrism', configurable: true, }); function markdown(markdownStr = '', options = {}) { const { filterPlugins, showLineNumbers = true, katexOptions = {} } = options; const remarkPlugins = [remarkGfm, ...(options.remarkPlugins || [])]; const rehypePlugins = [ [rehypePrism, { ignoreMissing: true, showLineNumbers }], rehypeRaw, [ rehypeVideo, { test: (url) => /\.(mp4|mov)|[?&]rehype=video/i.test(url), }, ], [rehypeAttrs, { properties: 'attr', codeBlockParames: false }], rehypeIgnore, ...(options.rehypePlugins || []), [ rehypeRewrite, { rewrite: (node, index, parent) => { if (node.type == 'element' && node.tagName === 'code') { const { className = [] } = node.properties || {}; const found = (Array.isArray(className) ? className : [className]).find((str) => String(str).toLocaleLowerCase().indexOf('language-katex') > -1); const code = getCodeString(node.children); if (found && node.properties) { if (Array.isArray(node.properties.className)) { if (parent && parent.type === 'element' && parent.properties) { parent.properties.className = ['language-katex']; } node.properties.className.push('math'); node.properties.className.push('math-display'); node.children = [ { type: 'text', value: code, }, ]; } } if (/^katex/.test(code.toLocaleLowerCase())) { node.properties.className = ['math', 'math-inline']; node.children = [ { type: 'text', value: code.replace(/^KaTeX:(\s.)?/i, ''), }, ]; } } if (options.rewrite && typeof options.rewrite === 'function') { options.rewrite(node, index, parent); } }, }, ], [rehypeKatex, katexOptions], stringify, ]; const processor = unified() .use(remarkParse) .use(filterPlugins && typeof filterPlugins === 'function' ? filterPlugins('remark', remarkPlugins) : remarkPlugins) .use(remarkRehype, Object.assign(Object.assign({}, options.remarkRehypeOptions), { allowDangerousHtml: true })) .use(filterPlugins && typeof filterPlugins === 'function' ? filterPlugins('rehype', rehypePlugins) : rehypePlugins); const file = new VFile(); file.value = markdownStr; const hastNode = processor.runSync(processor.parse(file), file); if (options.hastNode) { return hastNode; } return String(processor.stringify(hastNode, file)); } export default markdown; //# sourceMappingURL=index.js.map