joicomponents
Version:
Design patterns to build native web components
82 lines (73 loc) • 2.43 kB
HTML
<script>
class PassePartout extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: "open"}); //[1]
this.shadowRoot.innerHTML =
`<style>
div {
border: 20px solid grey;
}
</style>
<div>
<slot id="inner">Hello grey world</slot>
</div>`;
}
}
class GreenFrame extends HTMLElement {
constructor(){
super();
this.attachShadow({mode: "open"}); //[1]
this.shadowRoot.innerHTML =
`<style>
div {
border: 10px solid green;
}
</style>
<div>
<passe-partout>
<slot id="outer">Hello green world</slot>
</passe-partout>
</div>`;
}
}
customElements.define("passe-partout", PassePartout);
customElements.define("green-frame", GreenFrame);
</script>
<green-frame id="one"><slot id="strange">hello world</slot></green-frame>
<br>
<slot id="two"><h1>hello sunshine</h1></slot>
<script>
function flatDomChildNodes(slot){
const transposed= slot.assignedNodes();
if (transposed.length === 0)
return slot.childNodes;
return transposed;
}
function simplifiedFlatDomChildNodes(slot){
const flattenedChildren = slot.assignedNodes({flatten: true});
if (flattenedChildren.length === 0)
return slot.childNodes;
const flatFlat = [];
for (let node of flattenedChildren) {
if (node.tagName === "SLOT"){
for (let child of node.childNodes)
flatFlat.push(child);
} else {
flatFlat.push(node);
}
}
return flatFlat;
}
const onePassePartout = document.querySelector("#one").shadowRoot.children[1].children[0];
const one = onePassePartout.shadowRoot.children[1].children[0];
const two = document.querySelector("#two");
console.log("--------one--------------");
console.log("assignedNodes({flatten: true}): ", one.assignedNodes({flatten: true}));
console.log("flatDomChildNodes(slot): ", flatDomChildNodes(one));
console.log("simplifiedFlatDomChildNodes(slot): ", simplifiedFlatDomChildNodes(one));
console.log("--------two--------------");
console.log("assignedNodes({flatten: true}): ", two.assignedNodes({flatten: true}));
console.log("flatDomChildNodes(slot): ", flatDomChildNodes(two));
console.log("simplifiedFlatDomChildNodes(slot): ", simplifiedFlatDomChildNodes(two));
</script>