rich-component
Version:
library providing means to work conveniently with HTML based Web Components
1 lines • 1.75 kB
JavaScript
import{fetchTemplate as t}from"./template-fetch.js";const e="template",n="htmlUrl",o=Symbol("attach.light.dom"),i={};class r extends HTMLElement{constructor(){super();const t=this.getTemplate(),e="light"===this.constructor.domType;t?t.content?l(this,t,e):t.then(t=>{l(this,t,e),this.dispatchEvent(new Event("templated"))}):console.error(`failed to get template for '${this.localName}'`)}connectedCallback(){o in this&&(this.appendChild(this[o]),delete this[o])}getTemplate(){let e=null;const n=i[this.localName];if("function"==typeof n){const o=n.call(this,this);o&&"TEMPLATE"===o.nodeName?e=o:"string"==typeof o&&(e=t(o))}else e=n;return e}}export{r as ComponentBase,a as initComponent,t as fetchTemplate};async function a(o,a){let l;if(function(t){if(!t||"string"!=typeof t||!/^[a-z0-9]+(-[a-z0-9]+)*-[a-z0-9]+$/.test(t))throw new Error(`invalid element's tag/name: ${t}`);if(customElements.get(t))throw new Error(`'${t}' element already defined`)}(o),function(t,o){if(!(o&&o.prototype instanceof r))throw new Error(`invalid class for '${t}'; MUST NOT be null and MUST be an instance of ComponentBase`);if(!(e in o)&&!(n in o)||e in o&&n in o)throw new Error(`'${t}' MUST implement either static getter of '${n}' property returning component's HTML path, or static getter of '${e}' property returning a template`)}(o,a),e in a){if((!(l=a[e])||"TEMPLATE"!==l.nodeName)&&"function"!=typeof l)throw new Error(`'${o}' provided invalid template: ${l}`)}else{if((!(l=a[n])||"string"!=typeof l)&&"function"!=typeof l)throw new Error(`'${o}' provided invalid template URL: ${l}`);"string"==typeof l&&(l=await t(l))}i[o]=l,customElements.define(o,a)}function l(t,e,n=!1){const i=e.content.cloneNode(!0);n?t[o]=i:t.attachShadow({mode:"open"}).appendChild(i)}