Skip to content

Commit

Permalink
feat: add appendStyle method
Browse files Browse the repository at this point in the history
  • Loading branch information
infodusha committed Jul 30, 2024
1 parent ca9b396 commit 8a02f5b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 17 deletions.
2 changes: 1 addition & 1 deletion example/app-footer.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<template data-shadow>
<template>
<footer>Built by infodusha. Inspired by Vika.</footer>
</template>

Expand Down
38 changes: 22 additions & 16 deletions src/create-component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function createComponent(
"<template> is required"
);

const styles = definedElement.querySelectorAll("style");
const styles = [...definedElement.querySelectorAll("style"), ...globalStyles];
const scripts = definedElement.querySelectorAll("script");

const usedAttributes = getUsedAttributes(template, ["data-attr", "data-if"]);
Expand All @@ -38,6 +38,12 @@ export function createComponent(

readonly #cleanupFns = new Set<CleanupFn>();

readonly #styleGroup = document.createElement("style");

get shadowRoot(): ShadowRoot {
return returnIfDefined(super.shadowRoot);
}

constructor() {
super();
const content = cloneNode(template.content);
Expand Down Expand Up @@ -78,9 +84,12 @@ export function createComponent(
}

#attach(content: DocumentFragment): void {
const shadowRoot = this.attachShadow({ mode: "open" });
shadowRoot.appendChild(content);
this.#setShadowStyles(shadowRoot);
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(content);

for (const style of styles) {
this.appendStyle(style);
}
}

#applyAttr(name: string, value: string | null): void {
Expand All @@ -107,16 +116,6 @@ export function createComponent(
}
}

#setShadowStyles(shadowRoot: ShadowRoot) {
const group = document.createElement("style");
group.setAttribute("data-define-html", "");
for (const style of styles) {
group.append(cloneNode(style));
}
group.append(...globalStyles.map((el) => cloneNode(el)));
shadowRoot.append(group);
}

#execScripts(): void {
for (const script of scripts) {
executeScript(script, href, this)
Expand Down Expand Up @@ -153,12 +152,19 @@ export function createComponent(
}
}

appendStyle(style: HTMLLinkElement | HTMLStyleElement) {
if (this.#styleGroup.childElementCount === 0) {
this.shadowRoot.append(this.#styleGroup);
}
this.#styleGroup.append(cloneNode(style));
}

querySelector(selector: string): Element | null {
return returnIfDefined(this.shadowRoot).querySelector(selector);
return this.shadowRoot.querySelector(selector);
}

querySelectorAll(selector: string): NodeListOf<Element> {
return returnIfDefined(this.shadowRoot).querySelectorAll(selector);
return this.shadowRoot.querySelectorAll(selector);
}
}

Expand Down

0 comments on commit 8a02f5b

Please sign in to comment.