feat: fragment slots

This commit is contained in:
Ayo 2023-10-19 23:52:28 +02:00
parent 287f2e3c17
commit b48bd9a282
2 changed files with 20 additions and 19 deletions

View file

@ -3,14 +3,15 @@
*/ */
import { import {
Node as UltraNode,
ELEMENT_NODE, ELEMENT_NODE,
parse, parse,
render, render,
renderSync, renderSync,
walkSync, walkSync,
transform,
html as ultraHtml,
} from "ultrahtml"; } from "ultrahtml";
import { querySelectorAll } from "ultrahtml/selector"; import swap from "ultrahtml/transformers/swap";
import { parseScript } from "esprima"; import { parseScript } from "esprima";
import config from "../mcfly.config"; import config from "../mcfly.config";
@ -240,28 +241,28 @@ async function useFragments(html: string) {
if (node.type === ELEMENT_NODE && !!selector) { if (node.type === ELEMENT_NODE && !!selector) {
const index = node.parent.children.indexOf(node); const index = node.parent.children.indexOf(node);
node.parent.children[index] = parse(availableFragments[selector]); const fragmentNode = parse(availableFragments[selector]);
replaceSlots(fragmentNode, node);
node.parent.children[index] = fragmentNode;
} }
}); });
return render(ast); return render(ast);
} }
function replaceSlots(text: string, sourceNode: UltraNode) { function replaceSlots(fragmentNode, node) {
const regex = /<slot \/>/g; // fragmentNode.children = fragmentNode.children.concat(node.children);
var match;
while ((match = regex.exec(text))) { // walkSync find slot
let [key, _value] = match; walkSync(fragmentNode, (n) => {
const slotName = sourceNode.attributes.slot; if (n.type === ELEMENT_NODE && n.name === "slot") {
const h = sourceNode.children.find((node) => node.name === slotName); console.log(n);
if (h) { const index = n.parent.children.indexOf(n);
text = text?.replace(key, h.value); n.parent.children.splice(index, 1, ...node.children);
sourceNode.children.splice(sourceNode.children.indexOf(h), 1);
} }
} });
return text;
} }
async function getFiles(type: string) { async function getFiles(type: string) {

View file

@ -18,7 +18,7 @@
</script> </script>
</my-head> </my-head>
<body> <body>
<awesome-header></awesome-header> <awesome-header><span>heyyy</span></awesome-header>
<main> <main>
<a href="/demo/about">{{ count }}</a> <a href="/demo/about">{{ count }}</a>
<div> <div>
@ -30,8 +30,8 @@
<code-block language="js" line-numbers="true"> <code-block language="js" line-numbers="true">
<pre> <pre>
const hey = "AYO"; const hey = "AYO";
console.log(hey) console.log(hey)</pre
</pre> >
</code-block> </code-block>
</main> </main>
<my-footer></my-footer> <my-footer></my-footer>