@ts-kit/lit-framework
Version:
Framework arouhd Lit-Html
80 lines • 3.7 kB
JavaScript
import { Injector } from '@ts-kit/di';
import { render, html } from 'lit-html';
import { ComponentState } from './state';
import { ELEMENT_REF } from './el-ref';
export const ElementInstance = (element) => element;
export const createComponent = (componentDef) => {
return ElementInstance(document.createElement(componentDef.tag));
};
export const Component = (config) => (componentDef) => {
var _a;
componentDef.tag = config.tag;
customElements.define(config.tag, (_a = class extends HTMLElement {
constructor() {
super();
this.componentInjector = new Injector({
providers: [
{ provide: ELEMENT_REF, useFactory: () => this },
{
provide: ComponentState,
useFactory: () => {
return new ComponentState(state => {
const template = html `
${config.style} ${config.template(state, this.run)}
`;
render(template, this.shadow);
}, config.defaultState);
}
}
]
}, window.ROOT__INJECTOR__ // The root injector is global
);
this.shadow = this.attachShadow({ mode: 'open' });
this.run = (eventName, payload) => (e) => {
if (eventName in this.componentInstance.handlers) {
this.componentInstance.handlers[eventName].call(this.componentInstance, e, payload);
}
};
const template = html `
${config.style} ${config.template(config.defaultState, this.run)}
`;
render(template, this.shadow);
this.componentInstance = this.componentInjector.create(componentDef);
this.componentInstance.props = this.componentInstance.props || [];
this.componentState = this.componentInjector.get(ComponentState);
for (let i = 0; i < this.componentInstance.props.length; i++) {
const prop = this.componentInstance.props[i];
Object.defineProperty(this, prop, {
set: value => {
this.componentInstance[prop] = value;
if (this.componentInstance.onPropChanges) {
this.componentInstance.onPropChanges(prop, value);
}
},
get: () => this.componentInstance[prop]
});
}
if (this.componentInstance.onInit) {
this.componentInstance.onInit();
}
}
connectedCallback() {
if (this.componentInstance.connectedCallback) {
this.componentInstance.connectedCallback();
}
}
disconnectedCallback() {
if (this.componentInstance.disconnectedCallback) {
this.componentInstance.disconnectedCallback();
}
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (this.componentInstance.attributeChangedCallback) {
this.componentInstance.attributeChangedCallback(attrName, oldVal, newVal);
}
}
},
_a.observedAttributes = config.observedAttributes,
_a));
};
//# sourceMappingURL=component.js.map