-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecond-templ.ts
49 lines (46 loc) · 2 KB
/
second-templ.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import {CssObserve} from 'css-observe/css-observe.js';
import {TemplMount} from './templ-mount.js';
// import {getShadowContainer} from 'xtal-element/getShadowContainer.js';
const listening = Symbol();
const activatedIds: Set<string> = new Set<string>();
export class SecondTempl{
constructor(public tm: TemplMount){
const shadowContainer = tm.getRootNode();
if(shadowContainer[listening] === true) return;
shadowContainer[listening] = true;
const templateObserver = document.createElement(CssObserve.is) as CssObserve;
templateObserver.observe = true;
templateObserver.selector = "template[append-to-head]";
templateObserver.customStyles = `
template[append-to-head]{
display:block;
}
`;
templateObserver.addEventListener('latest-match-changed', e =>{
const t = (<any>e).detail.value as HTMLTemplateElement;
if(t.id){
if(activatedIds.has(t.id)) return;
activatedIds.add(t.id);
}
const clonedNode = t.content.cloneNode(true) as DocumentFragment;
this.cloneTemplate(clonedNode, 'script', ['src', 'type', 'nomodule']);
this.cloneTemplate(clonedNode, 'style', []);
});
tm.appendChild(templateObserver);
}
copyAttrs(src: HTMLScriptElement, dest: HTMLScriptElement, attrs: string[]){
attrs.forEach(attr =>{
if(!src.hasAttribute(attr)) return;
let attrVal = src.getAttribute(attr);
dest.setAttribute(attr, attrVal);
})
}
cloneTemplate(clonedNode: DocumentFragment, tagName: string, copyAttrs: string[]){
Array.from(clonedNode.querySelectorAll(tagName)).forEach(node =>{
const clone = document.createElement(tagName) as HTMLScriptElement;
this.copyAttrs(node as HTMLScriptElement, clone, copyAttrs);
clone.innerHTML = node.innerHTML;
document.head.appendChild(clone);
})
}
}