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