svem
Version:
Svelte in Markdown preprocessor
50 lines (49 loc) • 1.38 kB
JavaScript
const remarkHeadingSection = (options) => {
const { attributes = {} } = options ?? {};
return (tree) => {
if (typeof attributes.class === "string") {
attributes.class = attributes.class.split(" ");
}
if (!attributes.class) {
attributes.class = [];
}
if (Array.isArray(tree.children)) {
for (const node of [...tree.children]) {
if (node.type === "heading") {
const index = tree.children.indexOf(node);
const section = {
type: "html-node",
depth: node.depth,
tagName: "section",
attributes: {
...attributes,
class: ["section-block", ...attributes.class],
"data-depth": node.depth
},
children: [node]
};
const children = wrap(tree.children.slice(index + 1), (n) => n.type === "heading");
section.children?.push(...children);
tree.children.splice(index, 0, section);
for (const child of section.children ?? []) {
tree.children.splice(tree.children.indexOf(child), 1);
}
}
}
}
};
};
const wrap = (children, isStop) => {
const output = [];
for (const child of children) {
if (isStop(child)) {
break;
}
output.push(child);
}
return output;
};
export {
remarkHeadingSection,
wrap
};