feat: enhance markdown rendering
Adds remark-breaks for newline-to-br conversion and a custom remarkSplitBlocks plugin to split paragraphs at hard breaks. Code blocks over 15KB are truncated with a 'Show all' toggle for better performance.
This commit is contained in:
@@ -1,16 +1,59 @@
|
||||
import { unified } from 'unified';
|
||||
import { visit } from 'unist-util-visit';
|
||||
import remarkParse from 'remark-parse';
|
||||
import remarkGfm from 'remark-gfm';
|
||||
import remarkRehype from 'remark-rehype';
|
||||
import remarkBreaks from 'remark-breaks';
|
||||
import remarkMath from 'remark-math';
|
||||
import rehypeKatex from 'rehype-katex';
|
||||
|
||||
function remarkSplitBlocks() {
|
||||
return (tree: any) => {
|
||||
visit(tree, 'paragraph', (node, index, parent) => {
|
||||
const breakIndex = node.children.findIndex((child: any) => child.type === 'break');
|
||||
|
||||
if (breakIndex !== -1) {
|
||||
const beforeBreak = node.children.slice(0, breakIndex);
|
||||
const afterBreak = node.children.slice(breakIndex + 1);
|
||||
|
||||
node.children = beforeBreak;
|
||||
|
||||
const newParagraph = {
|
||||
type: 'paragraph',
|
||||
children: afterBreak,
|
||||
};
|
||||
|
||||
let rootChildIndex = -1;
|
||||
if (parent.type === 'root') {
|
||||
rootChildIndex = index!;
|
||||
} else {
|
||||
rootChildIndex = tree.children.findIndex((child: any) =>
|
||||
child === parent || (child.children && child.children.includes(node))
|
||||
);
|
||||
|
||||
if (rootChildIndex === -1) {
|
||||
rootChildIndex = tree.children.indexOf(parent);
|
||||
}
|
||||
}
|
||||
|
||||
if (rootChildIndex !== -1) {
|
||||
tree.children.splice(rootChildIndex + 1, 0, newParagraph);
|
||||
}
|
||||
|
||||
return index! + 1;
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export default defineNuxtPlugin((nuxtApp) => {
|
||||
const remark =
|
||||
unified()
|
||||
.use(remarkParse)
|
||||
.use(remarkGfm)
|
||||
.use(remarkMath)
|
||||
.use(remarkBreaks)
|
||||
.use(remarkSplitBlocks)
|
||||
.use(remarkRehype, { allowDangerousHtml: true })
|
||||
.use(rehypeKatex, { output: 'mathml' });
|
||||
|
||||
|
||||
Reference in New Issue
Block a user