feat: use shadow dom host (#41)

This commit is contained in:
Ayo Ayco 2023-12-27 00:13:21 +01:00 committed by GitHub
parent 29fa864ca2
commit e78030ab13
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 18 additions and 18 deletions

View file

@ -1,6 +1,6 @@
{
"name": "web-component-base",
"version": "2.1.0-beta.2",
"version": "2.1.0-beta.3",
"description": "A zero-dependency & tiny JS base class for creating reactive custom elements easily",
"type": "module",
"exports": {

View file

@ -16,6 +16,12 @@ import {
* @see https://WebComponent.io
*/
export class WebComponent extends HTMLElement {
#host;
#prevDOM;
#props;
#typeMap = {};
#effectsMap = {};
/**
* Array of strings that tells the browsers which attributes will cause a render
* @type {Array<string>}
@ -54,11 +60,6 @@ export class WebComponent extends HTMLElement {
return this.#props;
}
/**
* @type {PropStringMap}
*/
#props;
/**
* Triggered after view is initialized
*/
@ -89,6 +90,7 @@ export class WebComponent extends HTMLElement {
constructor() {
super();
this.#initializeProps();
this.#initializeHost();
}
static get observedAttributes() {
@ -128,9 +130,6 @@ export class WebComponent extends HTMLElement {
if (restored !== this.props[key]) this.props[key] = restored;
}
#typeMap = {};
#effectsMap = {};
#handler(setter, meta) {
const effectsMap = meta.#effectsMap;
const typeMap = meta.#typeMap;
@ -188,24 +187,25 @@ export class WebComponent extends HTMLElement {
);
}
}
#initializeHost() {
this.#host = this;
if (this.constructor.shadowRootInit) {
this.#host = this.attachShadow(this.constructor.shadowRootInit);
}
}
#prevDOM;
render() {
if (typeof this.template === "string") {
this.innerHTML = this.template;
} else if (typeof this.template === "object") {
let host = this;
if (this.constructor.shadowRootInit) {
host = this.attachShadow(this.constructor.shadowRootInit);
}
const tree = this.template;
// TODO: smart diffing
if (JSON.stringify(this.#prevDOM) !== JSON.stringify(tree)) {
const el = createElement(tree);
if (el) {
if (Array.isArray(el)) host.replaceChildren(...el);
else host.replaceChildren(el);
if (Array.isArray(el)) this.#host.replaceChildren(...el);
else this.#host.replaceChildren(el);
}
this.#prevDOM = tree;
}