Does this do what I think it does? #237
-
Hi 👋 import type { Transformer } from "unified"
import type { Root } from "hast"
import { visit, SKIP } from "unist-util-visit"
export default (): Transformer<Root> => {
return (tree) => {
visit(tree, "element", (node, index, parent) => {
if (!parent || index === undefined) return
if (node.tagName === "style" || node.tagName === "script") return
delete node.position
parent.children.splice(
index,
1,
{
type: "raw",
value: `{#if "${node.tagName}" in MarkdownElements}`,
},
{
...node,
tagName: "svelte:component",
properties: {
...node.properties,
this: `{MarkdownElements.${node.tagName}}`,
},
},
{
type: "raw",
value: "{:else}",
},
{
...node,
tagName: "svelte:element",
properties: {
...node.properties,
this: node.tagName,
},
},
{
type: "raw",
value: "{/if}",
}
)
if (node.tagName === "code" || node.tagName === "pre")
return [SKIP, index + 5]
return index + 5
})
}
} I do |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Hey @babakfp! 👋
It's unclear your full goal here, so it's hard to say.
The best way to verify this is to create a test case. 🙂 import { visit, SKIP } from 'unist-util-visit';
export default () => {
return (tree) => {
visit(tree, 'element', (node, index, parent) => {
if (!parent || index === undefined) return;
if (node.tagName === 'style' || node.tagName === 'script') return;
// Assert that the node does not have a warning attribute
if (node.data && node.data.warning) {
throw new Error(
`Node with tag ${node.tagName} already has a warning attribute`
);
}
delete node.position;
parent.children.splice(
index,
1,
{
type: 'raw',
value: `{#if "${node.tagName}" in MarkdownElements}`,
data: { warning: true },
},
{
...node,
tagName: 'svelte:component',
properties: {
...node.properties,
this: `{MarkdownElements.${node.tagName}}`,
},
data: { warning: true },
},
{
type: 'raw',
value: '{:else}',
data: { warning: true },
},
{
...node,
tagName: 'svelte:element',
properties: {
...node.properties,
this: node.tagName,
},
data: { warning: true },
},
{
type: 'raw',
value: '{/if}',
data: { warning: true },
}
);
if (node.tagName === 'code' || node.tagName === 'pre')
return [SKIP, index + 5];
return index + 5;
});
};
}; I suspect you intended to skip 4 indices ahead (since the first node replaces the current one). Here is a sandbox where you could do some testing https://stackblitz.com/edit/stackblitz-starters-ftcjzf?file=transformer.js |
Beta Was this translation helpful? Give feedback.
Hey @babakfp! 👋
It's unclear your full goal here, so it's hard to say.
The best way to verify this is to create a test case. 🙂
One way to do this would be to add a warning attribute, and assert none of the visited nodes have that attribute