2021-05-21 15:52:20 -05:00
|
|
|
import { visit } from 'unist-util-visit';
|
|
|
|
|
|
|
|
/** */
|
|
|
|
export function remarkCodeBlock() {
|
|
|
|
const visitor = (node: any) => {
|
2021-05-24 16:00:34 -04:00
|
|
|
const { data, meta } = node;
|
|
|
|
let lang = node.lang || 'html'; // default to html matches GFM behavior.
|
|
|
|
|
2021-05-21 15:52:20 -05:00
|
|
|
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 };
|
2021-05-21 15:52:20 -05:00
|
|
|
|
|
|
|
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') {
|
2021-08-12 12:51:37 -04:00
|
|
|
return { ...child, value: child.value.replace(/\{/g, 'ASTRO_ESCAPED_LEFT_CURLY_BRACKET\0') };
|
2021-05-21 15:52:20 -05:00
|
|
|
}
|
|
|
|
return child;
|
2021-05-21 20:53:47 +00:00
|
|
|
});
|
|
|
|
};
|
2021-05-21 15:52:20 -05: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);
|
|
|
|
}
|