feat: support constructable stylesheets

This commit is contained in:
Ayo Ayco 2025-03-30 12:00:45 +02:00
parent fdc3b428e5
commit 822c4d3984
5 changed files with 64 additions and 0 deletions

View file

@ -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`
<div>
<p>Wow!?</p>
</div>
`
}
}
customElements.define('styled-elements', StyledElements)

View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>WC demo</title>
<script type="module" src="./index.js"></script>
</head>
<body>
<styled-elements type="warn" condition></styled-elements>
</body>
</html>

View file

@ -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]
}
}