0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-02-24 22:46:02 -05:00
astro/packages/markdown-support/src/codeblock.ts

44 lines
1.2 KiB
TypeScript
Raw Normal View History

import { visit } from 'unist-util-visit';
/** */
export function remarkCodeBlock() {
const visitor = (node: any) => {
const { data, meta } = node;
let lang = node.lang || 'html'; // default to html matches GFM behavior.
let currentClassName = data?.hProperties?.class ?? '';
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
2021-05-21 20:53:47 +00:00
node.data.hProperties = { ...node.data.hProperties, class: `language-${lang} ${currentClassName}`.trim(), lang, meta };
return node;
};
return () => (tree: any) => visit(tree, 'code', visitor);
}
/** */
export function rehypeCodeBlock() {
const escapeCode = (code: any) => {
code.children = code.children.map((child: any) => {
if (child.type === 'text') {
return { ...child, value: child.value.replace(/\{/g, 'ASTRO_ESCAPED_LEFT_CURLY_BRACKET\0') };
}
return child;
2021-05-21 20:53:47 +00:00
});
};
const visitor = (node: any) => {
if (node.tagName === 'code') {
escapeCode(node);
return;
}
if (node.tagName !== 'pre') return;
const code = node.children[0];
if (code.tagName !== 'code') return;
node.properties = { ...code.properties };
return node;
};
return () => (tree: any) => visit(tree, 'element', visitor);
}