UNPKG

@web-widget/container

Version:
3 lines (2 loc) 12 kB
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).WebWidgetExports={})}(this,(function(t){"use strict";const e="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";var f=Object.freeze({__proto__:null,INITIAL:e,LOADING:n,LOADED:i,BOOTSTRAPPING:s,BOOTSTRAPPED:o,MOUNTING:r,MOUNTED:a,UPDATING:c,UNMOUNTING:d,UNLOADING:l,LOAD_ERROR:u,BOOTSTRAP_ERROR:h,MOUNT_ERROR:b,UPDATE_ERROR:m,UNMOUNT_ERROR:p,UNLOAD_ERROR:g});const w={load:{creator:!0,timeout:12e3,status:[e,n,i,u]},bootstrap:{pre:"load",timeout:4e3,status:[i,s,o,h]},mount:{pre:"bootstrap",timeout:3e3,status:[o,r,a,b]},update:{verify:!0,timeout:3e3,status:[a,c,a,m]},unmount:{timeout:3e3,status:[a,d,o,p]},unload:{pre:"unmount",timeout:3e3,status:[o,l,e,g]}},y=Symbol("setState");class ApplicationService{constructor(t,n,i){this.timeouts=i,this.state=e,this.lifecycles=Object.create(null),this.loader=t.bind(this.lifecycles),this.getDependencies=()=>("function"==typeof n&&(n=n()),n)}getState(){return this.state}[y](t){t!==this.state&&(this.state=t,this.stateChangeCallback())}stateChangeCallback(){}async trigger(t){const e=this.timeouts[t],n="number"==typeof e,i=w[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[y](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:w[t].timeout,n,1e3).then((()=>{this[y](r),delete this.pending})).catch((t=>{throw this[y](a),delete this.pending,t})),this.pending;this[y](r)}else if(i.verify)throw new Error(`Cannot ${t}: Application state: ${this.state}`)}}function E(){const t=new Map;return{[Symbol("data")]:t,get:e=>t.get(e),define(e,n){t.set(e,n)}}}const x=HTMLScriptElement.supports&&HTMLScriptElement.supports("importmap");function W(t){return t.default||t}function A(t){return x||"function"!=typeof importShim?import(/* @vite-ignore */ /* webpackIgnore: true */t):importShim(t)}let S;const R="function"==typeof window.queueMicrotask?window.queueMicrotask.bind(window):t=>(S||(S=Promise.resolve())).then(t).catch((t=>setTimeout((()=>{throw t}),0)));var T=(t,e="")=>console.warn(`Web Widget: "${t}" API is about to be deprecated. ${e}`);const O=Symbol("context"),v=Symbol("createPortal");function L(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 T("context",'Please use "container" instead'),this[O]||(this[O]=L(this.ownerElement)),this[O]}get createPortal(){return T("createPortal"),this[v]||(this[v]=(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),L(o)}),this[v]}get data(){const t=this.ownerElement.data;return Array.isArray(t)?[...t]:{...t}}set data(t){this.ownerElement.data=t}get name(){return T("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(){T("sandboxed");const{sandboxed:t}=this.ownerElement;return t}}window.WebWidgetDependencies=WebWidgetDependencies;class WebWidgetSandbox{constructor(t){Reflect.defineProperty(this,"ownerElement",{get:()=>t})}unload(){}get window(){return null}}window.WebWidgetSandbox=WebWidgetSandbox;const C=Symbol("application"),N=Symbol("data"),D=Symbol("firstConnect"),M=Symbol("applicationService"),P=Symbol("moveing"),U=Symbol("parentWidget"),k=Symbol("statechangeCallback"),I=Symbol("throwGlobalError"),j=Symbol("timeouts"),$=Symbol("trigger"),_=Symbol("tryAutoLoad"),H=Symbol("tryAutoLoadTimer"),G=Symbol("tryAutoUnload"),B=Symbol("tryAutoUnloadTimer"),z=E(),q=E();let F=Object.create(null);const J=t=>!t.inactive,K=t=>t.isConnected&&(t.import||t.src||t.application||t.text),Q=t=>J(t)&&K(t),V=J,X=new IntersectionObserver((t=>{t.forEach((({isIntersecting:t,target:e})=>{t&&Q(e)&&(e[_](),X.unobserve(e))}))}),{rootMargin:"80%"});function Y(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(!K(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[k](),this.dispatchEvent(new Event("statechange"))},this[M]=e}get application(){return this[C]||null}set application(t){"function"==typeof t&&(this[C]=t,this[_]())}get csp(){return T("csp"),this.getAttribute("csp")||""}set csp(t){T("csp"),this.setAttribute("csp",t)}get data(){if(!this[N]){const t=this.getAttribute("data");if(t)try{this[N]=JSON.parse(t)}catch(t){this[I](t),this[N]={}}else this[N]={...this.dataset}}return this[N]}set data(t){"object"==typeof t&&(this[N]=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[M].getState()}get sandboxed(){return T("sandboxed"),this.hasAttribute("sandboxed")}set sandboxed(t){T("sandboxed"),t?this.setAttribute("sandboxed",""):this.removeAttribute("sandboxed")}get name(){return T("name"),this.getAttribute("name")||""}set name(t){T("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 T("text"),this.getAttribute("text")||""}set text(t){T("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 T("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"})),Y(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[D]?this[P]:(this.firstConnectedCallback(),this[D]=!0)}firstConnectedCallback(){if(this[U]()){const{sandboxed:t,csp:e}=this[U]();t&&(this.sandboxed=t),e&&(this.csp=e)}var t;"lazy"===this.loading?(t=this,X.observe(t)):this[_]()}disconnectedCallback(){this[P]=!0,R((()=>{this.isConnected||(this[P]=!1,this.destroyedCallback())}))}attributeChangedCallback(t){"data"===t?delete this[N]:"lazy"!==this.loading&&this[_]()}destroyedCallback(){var t;"lazy"===this.loading&&(t=this,X.unobserve(t)),this[G]()}[_](){this[H]=setTimeout((()=>{Q(this)&&this.mount().catch(this[I].bind(this)),clearTimeout(this[H])}))}[G](){this[B]=setTimeout((()=>{V(this)&&(this.unload().catch(this[I].bind(this)),this.sandboxed&&this.sandbox.unload()),clearTimeout(this[B])}))}[$](t){return this[M].trigger(t,[this.dependencies])}[k](){const t=this.state;if(this.setAttribute("state",t),[a,u,h,b].includes(t)){let e,n;const i=t!==a;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)}}[U](){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}[I](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}),R((()=>{throw t}))}static get observedAttributes(){return["data","import","src","text","inactive"]}static get portalDestinations(){return T("portalDestinations"),z}static get loaders(){return q}static get timeouts(){return F}static set timeouts(t){F=t}}function Z(){customElements.define("web-widget",HTMLWebWidgetElement),Y(document)}Object.assign(HTMLWebWidgetElement,f),q.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 A(s).then(W);const o=new Blob([n],{type:"application/javascript"}),r=URL.createObjectURL(o);return A(r).then((t=>(URL.revokeObjectURL(r),W(t))),(t=>{throw URL.revokeObjectURL(r),t}))})),window.HTMLWebWidgetElement=HTMLWebWidgetElement,!1!==window.WEB_WIDGET_BOOTSTRAP&&Z(),t.HTMLWebWidgetElement=HTMLWebWidgetElement,t.WebWidgetDependencies=WebWidgetDependencies,t.WebWidgetSandbox=WebWidgetSandbox,t.bootstrap=Z,Object.defineProperty(t,"__esModule",{value:!0})})); //# sourceMappingURL=main.js.map