-
Hi 👋 In terms of unist/mdast/ast, how can I improve this code? I don't know, it doesn't look great. import { visit } from "unist-util-visit"
import { Transformer } from "unified"
import type { Root } from "mdast"
// Only opening tags because closing tags are parsed correctly by mdast as type of "text"
const SVELTE_SPECIAL_ELEMENTS_NAME = /^svelte:[a-z]+$/i
const SVELTE_SPECIAL_ELEMENTS_OPEN = /<svelte:[a-z]+(?:\s+[^>]*)?>/i
const SVELTE_SPECIAL_ELEMENTS_CLOSE = /<\/svelte:[a-z]+(?:\s+[^>]*)?>/i
export default (): Transformer<Root> => {
return (tree) => {
// Tags like `<svelte:something>` gets parsed as type of "link"! This fixes that by setting it to "text" (and later to "html").
visit(
tree,
"paragraph",
(nodeParagraph, indexParagraph, parentParagraph) => {
if (typeof indexParagraph === "number" && parentParagraph) {
visit(
nodeParagraph,
"link",
(nodeLink, indexLink, parentLink) => {
if (typeof indexLink === "number" && parentLink) {
if (
SVELTE_SPECIAL_ELEMENTS_NAME.test(
nodeLink.url
)
) {
visit(
nodeLink,
"text",
(nodeText, indexText, parentText) => {
if (
SVELTE_SPECIAL_ELEMENTS_NAME.test(
nodeText.value
)
) {
parentLink.children.splice(
indexLink,
1,
{
// NOTE: Using "text" because closing Svelte special tags are set to the same type. We will change both opening and closing tags to `html` later in the code.
type: "text",
value: `<${nodeText.value}>`,
}
)
}
}
)
}
}
}
)
// This will leave some p tags with no children. Will be fixed later in the code.
visit(
nodeParagraph,
"text",
(nodeText, indexText, parentText) => {
if (
SVELTE_SPECIAL_ELEMENTS_OPEN.test(
nodeText.value
) ||
SVELTE_SPECIAL_ELEMENTS_CLOSE.test(
nodeText.value
)
) {
// @ts-expect-error
nodeText.type = "html"
parentParagraph.children.splice(
indexParagraph,
0 + Number(indexText),
nodeText
)
if (
parentText &&
typeof indexText === "number"
) {
parentText.children.splice(indexText, 1)
}
}
}
)
}
}
)
// Removing empty paragraphs
visit(tree, "paragraph", (node, index, parent) => {
if (!node.children.length && parent && typeof index === "number") {
parent.children.splice(index, 1)
}
})
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
My first recommendation if I see such nested code, is to flatten its structures using early returns. This applies to all code, not just when working with unified or ASTs. Your variable names are in reverse order from what I usually see. For example, the parent of the paragraph is called I see a line Since indices are of type from a visitor function, you can return You call |
Beta Was this translation helpful? Give feedback.
-
Hey again @babakfp! 👋 |
Beta Was this translation helpful? Give feedback.
Thanks.
I did this, and I think it's good enough 👍