Very simple find-and-replace remark plugin enters a recursive loop #1201
-
Hi, I'm writing a plugin to convert all instances of hex color codes in markdown: `#FEF65B` into <span class="color" style="--color: #FEF65B">`#FEF65B`</span> I wrote a very simple plugin to do this: const { className, cssVariable } = options
visit(ast, "inlineCode", (node: InlineCode, i, parent) => {
const match = node.value.match(colorRegex)?.[0]
if (match && typeof i !== "undefined") {
parent?.children.splice(i, 1,
{
type: "html",
value: `<span class="${className}" style="--${cssVariable}: ${match}">`,
},
node,
{ type: "html", value: "</span>" },
)
}
}) problem is, once i try running any tests to verify the plugin works, it enters into an infinite loop and doesn't do anything. How would I fix this? I tried using the |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
You are trying to modify the HTML output, not markdown. This can be done better as a rehype plugin. It looks something like below. The main difference is that this adds the style to the generated import { visit } from 'unist-util-visit'
export default function rehypeColorCode({ cssVariable }) {
function transformer(ast) {
visit(ast, 'element', (node) => {
if (node.tagName !== 'code') {
return
}
if (node.children.length !== 1) {
return
}
const child = node.children[0]
if (child.type !== 'text') {
return
}
const match = child.value.match(colorRegex)?.[0]
if (!match) {
return
}
const css = `--${cssVariable}: ${match[0]};`
child.properties ||= {}
child.properties.style = child.properties.style ? `${child.properties.style};${css}` : css
})
}
} |
Beta Was this translation helpful? Give feedback.
-
Problem is you replace the current node with something else, while moving the current node to the next node. But |
Beta Was this translation helpful? Give feedback.
You are trying to modify the HTML output, not markdown. This can be done better as a rehype plugin. It looks something like below. The main difference is that this adds the style to the generated
<code>
node instead of wrapping it in a<span>
.