-
I've been stuck with this problem. I want to add some div tags around a pre tag to introduce some heading elements to support code copy buttons and headers I've tried the following approach. But somehow the result is not showing up in the browser when I use inspect: const rehypeCodeHeaders = () => {
return (tree) => {
visit(tree, 'element', (node, index, parent) => {
if (node.tagName == "pre") {
node = wrapper("lang", node);
console.log(node); // shows node was replaced with wrapper successfully.
}
});
};
}
// my custom node
function wrapper(lang, content) {
const wrapperObj = {
type: 'element',
tagName: 'div',
properties: { className: ['code-block'] },
children: [
{
type: 'element',
tagName: 'div',
properties: { className: ['code-block-title'] },
children: [
{
type: 'element',
tagName: 'p',
properties: { className: ['code-bloc-title-lang'] },
children: [
{
type: 'text',
value: lang
}
]
},
{
type: 'element',
tagName: 'button',
properties: {
className: ['code-bloc-title-btn'],
onclick: "const parent = this.closest('.code-block'); const codeBlock = parent.querySelector('code'); navigator.clipboard.writeText(codeBlock.textContent);"
},
children: [
]
}
]
},
{
type: 'element',
tagName: 'div',
properties: { className: ['code-block-body'] },
children: [content]
}
]
};
return wrapperObj;
}
// Using it..
export async function markdownToHtml2(markdown) {
const result = await unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype, { allowDangerousHtml: true})
.use(rehypeCodeHeaders) //
.use(rehypeRaw)
.use(rehypeHighlight)
.use(rehypeStringify)
.process(markdown)
return result.toString(); Result in the browser: Where did my div go? |
Beta Was this translation helpful? Give feedback.
Answered by
wooorm
Aug 15, 2024
Replies: 1 comment 2 replies
-
There's no code here that replaces? |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
zenovak
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's no code here that replaces?
There is code that creates a new node.
But no code that insert that new node?
https://unifiedjs.com/learn/recipe/remove-node/