diff --git a/examples/scoped-styles/index.html b/examples/constructed-styles/index.html similarity index 100% rename from examples/scoped-styles/index.html rename to examples/constructed-styles/index.html diff --git a/examples/constructed-styles/index.js b/examples/constructed-styles/index.js new file mode 100644 index 0000000..6a73d43 --- /dev/null +++ b/examples/constructed-styles/index.js @@ -0,0 +1,35 @@ +// @ts-check +import { WebComponent, html } from '../../src/index.js' + +class StyledElements extends WebComponent { + static props = { + condition: false, + type: 'info', + } + + static shadowRootInit = { + mode: 'open', + } + + static styles = ` + div { + background-color: yellow; + border: 1px solid black; + padding: 1em; + + p { + text-decoration: underline; + } + } + ` + + get template() { + return html` +
+

Wow!?

+
+ ` + } +} + +customElements.define('styled-elements', StyledElements) diff --git a/examples/style-objects/index.html b/examples/style-objects/index.html new file mode 100644 index 0000000..4ef7b41 --- /dev/null +++ b/examples/style-objects/index.html @@ -0,0 +1,12 @@ + + + + + + WC demo + + + + + + diff --git a/examples/scoped-styles/index.js b/examples/style-objects/index.js similarity index 100% rename from examples/scoped-styles/index.js rename to examples/style-objects/index.js diff --git a/src/WebComponent.js b/src/WebComponent.js index 6efba52..aba6780 100644 --- a/src/WebComponent.js +++ b/src/WebComponent.js @@ -28,6 +28,8 @@ export class WebComponent extends HTMLElement { */ static props + static styles + /** * Read-only string property that represents how the component will be rendered * @returns {string | any} @@ -182,7 +184,15 @@ export class WebComponent extends HTMLElement { // TODO: smart diffing if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) { + this.#applyStyles() + + /** + * create element + * - resolve prop values + * - attach event listeners + */ const el = createElement(tree) + if (el) { if (Array.isArray(el)) this.#host.replaceChildren(...el) else this.#host.replaceChildren(el) @@ -191,4 +201,11 @@ export class WebComponent extends HTMLElement { } } } + + #applyStyles() { + const styleObj = new CSSStyleSheet() + styleObj.replaceSync(this.constructor.styles) + console.log(this.constructor.styles, this.constructor.props) + this.#host.adoptedStyleSheets = [...this.#host.adoptedStyleSheets, styleObj] + } }