UNPKG

@web-widget/container

Version:
3 lines (2 loc) 11.8 kB
System.register([],(function(t,e){"use strict";return{execute:function(){t("bootstrap",tt);const n="initial",i="loading",s="loaded",o="bootstrapping",r="bootstrapped",a="mounting",c="mounted",d="updating",l="unmounting",u="unloading",h="load-error",b="bootstrap-error",m="mount-error",p="update-error",g="unmount-error",f="unload-error";var w=Object.freeze({__proto__:null,INITIAL:n,LOADING:i,LOADED:s,BOOTSTRAPPING:o,BOOTSTRAPPED:r,MOUNTING:a,MOUNTED:c,UPDATING:d,UNMOUNTING:l,UNLOADING:u,LOAD_ERROR:h,BOOTSTRAP_ERROR:b,MOUNT_ERROR:m,UPDATE_ERROR:p,UNMOUNT_ERROR:g,UNLOAD_ERROR:f});const y={load:{creator:!0,timeout:12e3,status:[n,i,s,h]},bootstrap:{pre:"load",timeout:4e3,status:[s,o,r,b]},mount:{pre:"bootstrap",timeout:3e3,status:[r,a,c,m]},update:{verify:!0,timeout:3e3,status:[c,d,c,p]},unmount:{timeout:3e3,status:[c,l,r,g]},unload:{pre:"unmount",timeout:3e3,status:[r,u,n,f]}},E=Symbol("setState");class ApplicationService{constructor(t,e,i){this.timeouts=i,this.state=n,this.lifecycles=Object.create(null),this.loader=t.bind(this.lifecycles),this.getDependencies=()=>("function"==typeof e&&(e=e()),e)}getState(){return this.state}[E](t){t!==this.state&&(this.state=t,this.stateChangeCallback())}stateChangeCallback(){}async trigger(t){const e=this.timeouts[t],n="number"==typeof e,i=y[t],[s,o,r,a]=i.status;if(!i)throw new Error(`Cannot ${t}`);if(this.pending&&await this.pending,i.creator&&!this.lifecycles[t]&&(this.lifecycles[t]=async t=>{let e=await this.loader(t);"function"==typeof e&&(e=e(t)),e||(e={}),Object.assign(this.lifecycles,e)}),s!==this.state&&i.pre&&await this.trigger(i.pre),[s,a].includes(this.state)){if(this[E](o),this.lifecycles[t])return this.pending=function(t,e,n,i=!1,s=1e3){return new Promise(((o,r)=>{const a=`Lifecycle function did not complete within ${n} ms: ${t}`;let c=!1,d=!1;function l(t){if(!c)if(!0===t)d=!0,i?r(new Error(a)):console.error(new Error(a));else if(!d){const e=t,i=e*s;console.warn(new Error(a)),i+s<n&&setTimeout((()=>l(e+1)),s)}}e().then((t=>{c=!0,o(t)})).catch((t=>{c=!0,r(t)})),i||setTimeout((()=>l(1)),s),setTimeout((()=>l(!0)),n)}))}(t,(async()=>this.lifecycles[t](this.getDependencies())),n?e:y[t].timeout,n,1e3).then((()=>{this[E](r),delete this.pending})).catch((t=>{throw this[E](a),delete this.pending,t})),this.pending;this[E](r)}else if(i.verify)throw new Error(`Cannot ${t}: Application state: ${this.state}`)}}function x(){const t=new Map;return{[Symbol("data")]:t,get:e=>t.get(e),define(e,n){t.set(e,n)}}}const A=HTMLScriptElement.supports&&HTMLScriptElement.supports("importmap");function W(t){return t.default||t}function S(t){return A||"function"!=typeof importShim?e.import(/* @vite-ignore */ /* webpackIgnore: true */t):importShim(t)}let R;const T="function"==typeof window.queueMicrotask?window.queueMicrotask.bind(window):t=>(R||(R=Promise.resolve())).then(t).catch((t=>setTimeout((()=>{throw t}),0)));var O=(t,e="")=>console.warn(`Web Widget: "${t}" API is about to be deprecated. ${e}`);const v=Symbol("context"),L=Symbol("createPortal");function C(t){return{mount:()=>t.mount(),update:e=>t.update(e),unmount:()=>t.unmount()}}class WebWidgetDependencies{constructor(t){Reflect.defineProperty(this,"ownerElement",{get:()=>t})}get container(){const t=this.ownerElement;return t.renderRoot||(t.renderRoot=t.createRenderRoot(),["mount","update","unmount"].forEach((e=>{t.renderRoot[e]||(t.renderRoot[e]=n=>t[e](n))}))),t.renderRoot}get context(){return O("context",'Please use "container" instead'),this[v]||(this[v]=C(this.ownerElement)),this[v]}get createPortal(){return O("createPortal"),this[L]||(this[L]=(t,e)=>{const n=this.ownerElement,i=n.constructor,s=i.portalDestinations.get(e),o=s?s():null;if(!o)throw new Error(`The portal cannot be found: ${e}`);if(!(o instanceof i))throw new Error(`Portal must be an instance of "HTMLWebWidgetElement": ${e}`);this.sandboxed&&!t.isConnected&&this.container.appendChild(t),t.slot||(t.slot="");const r=o.querySelector(`[slot="${t.slot}"]`);return r&&o.removeChild(r),o.appendChild(t),o.mount(),n.portals.push(o),C(o)}),this[L]}get data(){const t=this.ownerElement.data;return Array.isArray(t)?[...t]:{...t}}set data(t){this.ownerElement.data=t}get name(){return O("name"),this.ownerElement.name}get parameters(){return this.env}get env(){return[...this.ownerElement.attributes].reduce(((t,{name:e,value:n})=>(t[e]=n,t)),{})}get sandboxed(){O("sandboxed");const{sandboxed:t}=this.ownerElement;return t}}t("WebWidgetDependencies",WebWidgetDependencies),window.WebWidgetDependencies=WebWidgetDependencies;class WebWidgetSandbox{constructor(t){Reflect.defineProperty(this,"ownerElement",{get:()=>t})}unload(){}get window(){return null}}t("WebWidgetSandbox",WebWidgetSandbox),window.WebWidgetSandbox=WebWidgetSandbox;const N=Symbol("application"),D=Symbol("data"),M=Symbol("firstConnect"),P=Symbol("applicationService"),U=Symbol("moveing"),k=Symbol("parentWidget"),I=Symbol("statechangeCallback"),$=Symbol("throwGlobalError"),j=Symbol("timeouts"),_=Symbol("trigger"),H=Symbol("tryAutoLoad"),G=Symbol("tryAutoLoadTimer"),B=Symbol("tryAutoUnload"),z=Symbol("tryAutoUnloadTimer"),q=x(),F=x();let J=Object.create(null);const K=t=>!t.inactive,Q=t=>t.isConnected&&(t.import||t.src||t.application||t.text),V=t=>K(t)&&Q(t),X=K,Y=new IntersectionObserver((t=>{t.forEach((({isIntersecting:t,target:e})=>{t&&V(e)&&(e[H](),Y.unobserve(e))}))}),{rootMargin:"80%"});function Z(t){!function(t,e){const n="web-widget";e([...t.querySelectorAll(`[is=${n}]`)].filter((t=>t.localName.includes("-")))),new MutationObserver((t=>{e(t.reduce(((t,{type:e,target:n,addedNodes:i})=>("attributes"===e?t.push(n):t.push(...i),t)),[]).filter((t=>t.nodeType===Node.ELEMENT_NODE&&t.localName.includes("-")&&t.getAttribute("is")===n)))})).observe(t,{attributeFilter:["is"],attributes:!0,childList:!0,subtree:!0})}(t,(t=>{t.forEach((t=>{const e=t.localName;if(!customElements.get(e)){customElements["define"](e,class extends HTMLWebWidgetElement{})}}))}))}class HTMLWebWidgetElement extends HTMLElement{constructor(){super();const t=this,e=new ApplicationService((function(e){if(!Q(t))throw new Error("Cannot load: Not initialized");const{application:n}=t;if(t.sandbox=t.sandbox||t.sandboxed?t.createSandbox():null,t.renderRoot=null,t.loader=n||t.createLoader(),t.portals=[],t.sandboxed&&!t.sandbox.window)throw new Error("Sandbox mode is not implemented");return t.loader.call(this,e)}),(()=>{const t=this.createDependencies();return this.dependencies=t,t}),this.timeouts);e.stateChangeCallback=()=>{this[I](),this.dispatchEvent(new Event("statechange"))},this[P]=e}get application(){return this[N]||null}set application(t){"function"==typeof t&&(this[N]=t,this[H]())}get csp(){return O("csp"),this.getAttribute("csp")||""}set csp(t){O("csp"),this.setAttribute("csp",t)}get data(){if(!this[D]){const t=this.getAttribute("data");if(t)try{this[D]=JSON.parse(t)}catch(t){this[$](t),this[D]={}}else this[D]={...this.dataset}}return this[D]}set data(t){"object"==typeof t&&(this[D]=t)}get inactive(){return this.hasAttribute("inactive")}set inactive(t){t?this.setAttribute("inactive",""):this.removeAttribute("inactive")}get loading(){return this.getAttribute("loading")||"auto"}set loading(t){this.setAttribute("loading",t)}get type(){return this.getAttribute("type")||"module"}set type(t){this.setAttribute("type",t)}get state(){return this[P].getState()}get sandboxed(){return O("sandboxed"),this.hasAttribute("sandboxed")}set sandboxed(t){O("sandboxed"),t?this.setAttribute("sandboxed",""):this.removeAttribute("sandboxed")}get name(){return O("name"),this.getAttribute("name")||""}set name(t){O("name"),this.setAttribute("name",t)}get src(){const t=this.getAttribute("src");return null===t?"":new URL(t,this.baseURI).href}set src(t){this.setAttribute("src",t)}get import(){const t=this.getAttribute("import");return null===t?"":t}set import(t){this.setAttribute("import",t)}get rendertarget(){return this.getAttribute("rendertarget")||"shadow"}set rendertarget(t){this.setAttribute("rendertarget",t)}get text(){return O("text"),this.getAttribute("text")||""}set text(t){O("text"),this.setAttribute("text",t)}get timeouts(){return this[j]||(this[j]={...this.constructor.timeouts}),this[j]}set timeouts(t){this[j]=t}createDependencies(){return new WebWidgetDependencies(this)}createSandbox(){return O("createSandbox"),new WebWidgetSandbox(this)}createRenderRoot(){let t=null;const{sandboxed:e,sandbox:n}=this;if(e){const e=n.window.document,i=e.createElement("style");i.textContent="body{margin:0}",e.head.appendChild(i),t=e.body}else if("shadow"===this.rendertarget){if(this.hasAttribute("hydrateonly")&&this.attachInternals){t=this.attachInternals().shadowRoot}t||(t=this.attachShadow({mode:"open"})),Z(t)}else"light"===this.rendertarget&&(t=this);return t}createLoader(){const{type:t}=this,e=this.constructor.loaders.get(t);if(!e)throw Error(`Loader is not defined: ${t}`);return()=>e(this)}async load(){await this[_]("load")}async bootstrap(){await this[_]("bootstrap")}async mount(){await this[_]("mount")}async update(t={}){const e=this.dependencies||{};Object.assign(e,t),await this[_]("update")}async unmount(){const t=this.portals||[];await this[_]("unmount"),await Promise.all(t.map((t=>t.unmount())))}async unload(){const t=this.portals||[],e=this.dependencies||{};await this[_]("unload"),await Promise.all(t.map((t=>t.unload()))),Object.getOwnPropertyNames(e).forEach((t=>{Reflect.deleteProperty(e,t)}))}connectedCallback(){this[M]?this[U]:(this.firstConnectedCallback(),this[M]=!0)}firstConnectedCallback(){if(this[k]()){const{sandboxed:t,csp:e}=this[k]();t&&(this.sandboxed=t),e&&(this.csp=e)}var t;"lazy"===this.loading?(t=this,Y.observe(t)):this[H]()}disconnectedCallback(){this[U]=!0,T((()=>{this.isConnected||(this[U]=!1,this.destroyedCallback())}))}attributeChangedCallback(t){"data"===t?delete this[D]:"lazy"!==this.loading&&this[H]()}destroyedCallback(){var t;"lazy"===this.loading&&(t=this,Y.unobserve(t)),this[B]()}[H](){this[G]=setTimeout((()=>{V(this)&&this.mount().catch(this[$].bind(this)),clearTimeout(this[G])}))}[B](){this[z]=setTimeout((()=>{X(this)&&(this.unload().catch(this[$].bind(this)),this.sandboxed&&this.sandbox.unload()),clearTimeout(this[z])}))}[_](t){return this[P].trigger(t,[this.dependencies])}[I](){const t=this.state;if(this.setAttribute("state",t),[c,h,b,m].includes(t)){let e,n;const i=t!==c;for(const t of this.children){const i=t.localName;"placeholder"===i?e=t:"fallback"===i&&(n=t)}e&&n?(e.hidden=i,n.hidden=!i):e?i||(e.hidden=!0):n&&(n.hidden=!i)}}[k](){const t=function(t,e){let n=t;do{if(n=n.getRootNode().host,n&&n instanceof e)return n}while(n);return null}(this,this.constructor);return t||null}[$](t){const e=`Web Widget application (${this.name||this.import||this.src||this.localName})`;"object"!=typeof t&&(t=new Error(t)),t.message.includes(e)||Reflect.defineProperty(t,"message",{value:`${e}: ${t.message}`,writable:!0,configurable:!0}),T((()=>{throw t}))}static get observedAttributes(){return["data","import","src","text","inactive"]}static get portalDestinations(){return O("portalDestinations"),q}static get loaders(){return F}static get timeouts(){return J}static set timeouts(t){J=t}}function tt(){customElements.define("web-widget",HTMLWebWidgetElement),Z(document)}t("HTMLWebWidgetElement",HTMLWebWidgetElement),Object.assign(HTMLWebWidgetElement,w),F.define("module",(async function(t){const{src:e,text:n,sandboxed:i}=t,s=t.import||e;if(i)throw new Error("The sandbox does not support ES module");if(s)return S(s).then(W);const o=new Blob([n],{type:"application/javascript"}),r=URL.createObjectURL(o);return S(r).then((t=>(URL.revokeObjectURL(r),W(t))),(t=>{throw URL.revokeObjectURL(r),t}))})),window.HTMLWebWidgetElement=HTMLWebWidgetElement,!1!==window.WEB_WIDGET_BOOTSTRAP&&tt()}}})); //# sourceMappingURL=main.js.map