@mundorum/oid
Version:
Web components based on the Digital Content Component (DCC) model for the Mundorum space.
109 lines (108 loc) • 31.8 kB
JavaScript
(function(o,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(o=typeof globalThis<"u"?globalThis:o||self,h(o.oidlib={}))})(this,function(o){"use strict";var j=Object.defineProperty;var U=(o,h,m)=>h in o?j(o,h,{enumerable:!0,configurable:!0,writable:!0,value:m}):o[h]=m;var v=(o,h,m)=>U(o,typeof h!="symbol"?h+"":h,m);const h=(p,...e)=>String.raw({raw:p},...e),m=(p,...e)=>String.raw({raw:p},...e);class b{constructor(){this._listeners={},this._listenersRgx=[],this._providers={},this._pendingCnx={}}subscribe(e,t){if(e!=null){let s={};typeof e=="string"&&t!=null?s[e]=t:typeof e=="object"&&(s=e);const i=this._listenersRgx.slice(),n={...this._listeners};for(const l in s)s[l]!=null&&(l.includes("+")||l.includes("#")?i.push([b._convertRegExp(l),s[l],l]):(n[l]==null?n[l]=[]:n[l]=n[l].slice(),n[l].push(s[l])));this._listenersRgx=i,this._listeners=n}}unsubscribe(e){if(e!=null){let t={};typeof e=="string"&&handler!=null?t[e]=handler:typeof e=="object"&&(t=e);const s=this._listenersRgx.slice(),i={...this._listeners};for(const n in t)if(n.includes("+")||n.includes("#")){for(const l in s)if(s[l][1]===t[n]&&s[l][2]==n){s.splice(l,1);break}}else if(i[n]!=null){for(const l in i[n])if(i[n][l]===t[n]){i[n]=i[n].toSplice(l,1);break}}this._listenersRgx=s,this._listeners=i}}async publish(e,t){if(this._listeners[e]!=null)for(const i of this._listeners[e])i(e,t);const s=this._listenersRgx;for(const i of s){const n=i[0].exec(e);n!=null&&n[0]===e&&i[1](e,t)}}static _convertRegExp(e){return new RegExp(e.replace(/\//g,"\\/").replace(/\+/g,"[^/]+").replace(/#/g,".+"))}provide(e,t,s){let i=!1;if(t!=null&&e!=null&&s!=null){const n=e+"#"+t;if(this._providers[n]==null&&(i=!0,this._providers[n]=s,this._pendingCnx[n]!=null)){for(let l of this._pendingCnx[n])l.connectionReady(e,t,s);delete this._pendingCnx[n]}}return i}withhold(e,t){let s=!1;if(t!=null&&e!=null){const i=e+"#"+t;this._providers[i]&&(s=!0,delete this._providers[i])}return s}connect(e,t,s){let i=!1;if(t!=null&&e!=null&&s!=null){const n=`${e}#${t}`;this._providers[n]?s.connectionReady(e,t,this._providers[n]):this._pendingCnx[n]?this._pendingCnx[n].push(s):this._pendingCnx[n]=[s],i=!0}return i}async invoke(e,t,s,i){const n=`${e}#${t}`;return this._providers[n]!=null?await this._providers[n].handleInvoke(e,s,i):null}}b.i=new b;const k={id:"default",bus:b.i,stylesheets:"<auto>",stydefault:["stylesheets:oid.min.css"],assets:"/assets/"};class u{constructor(e,t,s,i,n){if(this._id=e||null,this._bus=t||u.i.bus,this._stydefault=i||u.i.stydefault,this._stylesheets=s||u.i.stylesheets,this._stylesheets==="<auto>"&&this._stydefault){const l=this._stydefault[0].split(/[:\/]/).pop(),r=document.querySelectorAll('link[rel="stylesheet"]');for(const d of r)if(d.href&&d.href.endsWith(l)){this._stylesheets=d.href.slice(0,-l.length);break}}this._assets=n||u.i.assets}static create(e,t,s,i,n){if(e!=null&&u._spheres[e]!=null)throw new Error(`Sphere with id ${e} already exists`);const l=new u(e,t,s,i,n);return e!=null&&(u._spheres[e]=l),l}static get(e){return e&&u._spheres[e]||null}get id(){return this._id}get bus(){return this._bus}set stylesheets(e){this._stylesheets=e}get stylesheets(){return this._stylesheets}set stydefault(e){this._stydefault=e}get stydefault(){return this._stydefault}set assets(e){this._assets=e}get assets(){return this._assets}}u._spheres={},u.i=u.create(k.id,k.bus,k.stylesheets,k.stydefault,k.assets);class y extends HTMLElement{connectedCallback(){if(this.hasAttribute("global"))this._sphere=u.i,this.hasAttribute("stylesheets")&&(u.i.stydefault=this.getAttribute("stylesheets")),this.hasAttribute("stydefault")&&(u.i.stydefault=this.getAttribute("stydefault")),this.hasAttribute("assets")&&(u.i.assets=this.getAttribute("assets"));else{const e=this.getAttribute("id");u.get(e)?this._sphere=u.get(e):this._sphere=u.create(this.getAttribute("id"),new b,this.getAttribute("stylesheets"),this.getAttribute("stydefault"),this.getAttribute("assets"))}}get id(){return this._sphere.id}get stylesheets(){return this._sphere.stylesheets}get stydefault(){return this._sphere.stydefault}get assets(){return this._sphere.assets}get sphere(){return this._sphere}}y.elementTag="oid-sphere",customElements.define(y.elementTag,y);class x extends HTMLElement{constructor(){super(),this._sphere=null}get _bus(){return this._sphere==null?null:this._sphere.bus}connectedCallback(){let e=this._findAggregator(y);e!=null?this._sphere=e.sphere:this._sphere=u.i}_findAggregator(e){let t=this.parentNode!=null?this.parentNode:this instanceof DocumentFragment?this.host:null;for(;t!=null&&!(t instanceof e);)t=t.parentNode!=null?t.parentNode:t instanceof DocumentFragment?t.host:null;return t}_subscribe(e,t){this._bus!=null&&this._bus.subscribe(e,t)}_unsubscribe(e,t){this._bus.unsubscribe(e,t)}async _publish(e,t){await this._bus.publish(e,t)}_provide(e,t,s){this._bus.provide(e,t,s)}_withhold(e,t){this._bus.withhold(e,t)}_connect(e,t,s){this._bus.connect(e,t,s)}async _invoke(e,t,s,i){return await this._bus.invoke(e,t,s,i)}}class S extends x{constructor(){super(),this._mapTopicNotice={},this._rgxTopicNotice=[],this._mapNoticeTopic={},this._receiveHandler={},this._provideHandler={},this._connected={},this._convertNotice=this._convertNotice.bind(this),this.handleNotice=this.handleNotice.bind(this)}async connectedCallback(){super.connectedCallback(),await this._initialize()}disconnectedCallback(){this._finalize()}async _initialize(){const e=this.constructor.spec;if(e&&(this._buildHandlers(this._receiveHandler,e.receive),this._buildProviders(),this._buildProvidersHandlers(),this._buildEventDispatchers(e.dispatcher)),e&&e.properties)for(const[t,s]of Object.entries(e.properties))s.default!=null&&!this.hasAttribute(t)&&(this[t]=s.default);this.hasAttribute("custom")&&(this._custom=await c.getCustom(e.id,this.getAttribute("custom"))),this.hasAttribute("publish")&&this._publishNoticeTopic(this.getAttribute("publish")),this.hasAttribute("subscribe")&&this._subscribeTopicNotice(this.getAttribute("subscribe")),this.hasAttribute("connect")&&this._connectInterface(this.getAttribute("connect"))}_buildProviders(){const e=this.constructor.spec;if(e.provide!=null&&this.id)for(const t in e.provide)this._provide(t,this.id,this)}_buildProvidersHandlers(){const e=this.constructor.spec;if(e.provide!=null)for(const t in e.provide)this._buildHandlers(this._provideHandler,e.provide[t].operations,t)}_removeProviders(){const e=this.constructor.spec;if(e.provide!=null&&this.id)for(const t in e.provide)this._withhold(t,this.id)}_buildHandlers(e,t,s){if(t!=null){const i=s==null?"":s+".";if(Array.isArray(t))for(const n of t)e[i+n]==null&&(e[i+n]=this["handle"+n[0].toUpperCase()+n.slice(1)].bind(this));else for(const[n,l]of Object.entries(t))if(e[i+n]==null){const r=typeof l=="string"?l:l.handler!=null?l.handler:"handle"+n[0].toUpperCase()+n.slice(1);e[i+n]=this[r].bind(this)}}}_buildEventDispatchers(e){if(e){this._dispatcher=[];for(const[t,s,i]of e)this._dispatcher.push([t,s,i.bind(this)])}}_finalize(){this._removeProviders();for(const e in this._mapTopicNotice)this._mapTopicNotice[e]!=e?this._unsubscribe(e,this._convertNotice):this._unsubscribe(e,this.handleNotice)}attributeChangedCallback(e,t,s){const i=e.replace(/-([a-z])/g,(n,l)=>l.toUpperCase());this[i]=s}static get observedAttributes(){return["id"]}get id(){return this._id}set id(e){this._id!=null&&this._bus!=null&&this._removeProviders(),this._id=e,this._bus!=null&&this._buildProviders()}get publish(){return this.getAttribute("publish")}get subscribe(){return this.getAttribute("subscribe")}get connect(){return this.getAttribute("connect")}handleGet(e,t){return t.property!=null?this[t.property]:null}handleSet(e,t){t.property!=null&&t.value!=null&&(this[t.property]=t.value)}_subscribeTopicNotice(e){const t=e.split(";");for(const s of t){const i=s.split("~");if(i.length>1){const n=i[0].trim();n.includes("+")||n.includes("#")?this._rgxTopicNotice.push([b._convertRegExp(n),i[1].trim(),n]):this._mapTopicNotice[n]=i[1].trim(),this._subscribe(n,this._convertNotice)}else{const n=s.trim();this._mapTopicNotice[n]=n,this._subscribe(n,this.handleNotice)}}}_publishNoticeTopic(e){const t=e.split(";");for(const s of t){const i=s.split("~");i.length>1?this._mapNoticeTopic[i[0].trim()]=i[1].trim():this._mapNoticeTopic[s.trim()]=s.trim()}}_connectInterface(e){let t=!0;const s=e.split(";");for(const i of s){const n=i.split("#");n.length>1?this._connect(n[0].trim(),n[1].trim(),this):t=!1}return t}_notify(e,t){this._mapNoticeTopic[e]!=null&&this._publish(this._mapNoticeTopic[e],t)}_convertNotice(e,t){if(this._mapTopicNotice[e]!=null)this.handleNotice(this._mapTopicNotice[e],t);else for(const[s,i]of this._rgxTopicNotice){const n=s.exec(e);if(n!=null&&n[0]===e){this.handleNotice(i,t);break}}}connectTo(e,t){t.id&&this._connect(e,t.id,this)}connectionReady(e,t,s){this._connected[e]==null&&(this._connected[e]=[]),this._connected[e].push(t)}async _invoke(e,t,s){const i=c.getInterface(e);if(this._connected[e]!=null)if(i.response!=null&&i.response===!0){const n=[];for(const l of this._connected[e])n.push(await this._bus.invoke(e,l,t,s));return n}else for(const n of this._connected[e])return await this._bus.invoke(e,n,t,s)}handleNotice(e,t){this._receiveHandler[e]!=null&&this._receiveHandler[e](e,t)}async handleInvoke(e,t,s){let i=null;return this._provideHandler[`${e}.${t}`]!=null&&(i=await this._provideHandler[`${e}.${t}`](t,s)),i}_customExists(e){return this._custom!=null&&this._custom.hasOwnProperty(e)}_getCustomField(e){return this._custom==null||this._custom[e]==null?null:this._custom[e]}_callCustom(e,t){if(this._custom!=null&&this._custom[e]!=null)return this._custom[e](this,t)}}class g extends S{}class f extends g{async connectedCallback(){await super.connectedCallback(),this._stylesheets=this.constructor.spec.stylesheets.replace('href="default"','href="'+this._sphere.stydefault+'"').replace('href="stylesheets:','href="'+this._sphere.stylesheets),this.render()}render(){const e=this.constructor.spec;let t=e!=null?e.template:null;if(this.template){const s=this.template();if(s!=this._template){this._template=s;const i=c.prepareDispatchers(s,this.constructor);this._templatePre=i.template,this._buildEventDispatchers(i.dispatcher,this)}t=this._templatePre}if(this._presentation=null,e!=null&&t!=null){let s=this._getCustomField("style");s=s?`<style>${s}</style>`:"";const i=(this._stylesheets+e.styles+s+t).replace(/{{[ \t]*(url:)?[ \t]*this\.([^}]*)}}/g,(n,l,r)=>{r=r?r.trim():"";let d=this[r]?this[r]:"";return l==="url:"&&(d=d.replace("assets:",this._sphere.assets)),d});if(e.shadow===!1?(this.innerHTML=i,this._presentation=this.querySelector("#oid-prs")||this):this._presentation=this._shadowHTML(i),this._dispatcher){const n=e.shadow===!1?this:this.shadowRoot;for(const[l,r,d]of this._dispatcher)n.querySelector("["+l+"]").addEventListener(r,d)}}}_shadowHTML(e){const t=f.prepareShadow(this,e);return this.shadowRoot.querySelector("#oid-prs")||t}static prepareShadow(e,t){const s=document.createElement("template");s.innerHTML=t;const i=document.importNode(s.content,!0);return e.shadowRoot?e.shadowRoot.innerHTML="":e.attachShadow({mode:"open"}),e.shadowRoot.appendChild(i),i}}const a=class a{static cInterface(e){e!=null&&(a._interfaceReg[e.id]=e)}static getInterface(e){return a._interfaceReg[e]}static component(e){e=Object.assign({},a._defaultSpec,e);let t=e.implementation;if(t==null){const n=e.ui===!1||e.template==null?e.element==null?S:g:f,l=e.element[0].toUpperCase()+e.element.slice(1).replace(/-([a-z])/g,(r,d)=>d.toUpperCase());t=class extends n{},Object.defineProperty(t,"name",{value:l})}const s=t.observedAttributes.slice();if(e.properties){Object.defineProperty(t,"observedAttributes",{get:function(){return this.observed}});for(const n in e.properties){const l=e.properties[n],r=n.replace(/-([a-z])/g,(d,w)=>w.toUpperCase());Object.defineProperty(t.prototype,r,l.readonly?{get:function(){return this["_"+r]}}:t.prototype.render==null?{get:function(){return this["_"+r]},set:function(d){this["_"+r]=d}}:{get:function(){return this["_"+r]},set:function(d){const w=this["_"+r];this["_"+r]=d,w!=d&&this._sphere&&this.render()}}),(l.attribute==null||l.attribute!==!1)&&s.push(n)}}if(e.provide=e.provide==null?a.defaultInterface:e.provide.concat(a.defaultInterface),e.provide){const n={};for(const l of e.provide){const r=a._interfaceReg[l];if(r==null)throw new Error("Unknown interface id: "+l);n[l]=r}e.provide=n}a.stylePreprocess(e);const i=a.prepareDispatchers(e.template,t);e.template=i.template,i.dispatcher&&(e.dispatcher=i.dispatcher),Object.assign(t,{spec:e,observed:s}),e.element==null&&(e.element="internal-"+e.id.replace(":","-")),customElements.define(e.element,t),a._oidReg[e.id]=t}static componentSet(e,t){if(e!=null&&a._oidReg[e]!=null){const s=a._oidReg[e].spec;for(const i in t)s[i]=t[i];a.stylePreprocess(s)}}static stylePreprocess(e){let t="";if(e.stylesheets){let s=e.stylesheets;Array.isArray(s)||(s=[s]);for(const i of s)t+=`<link href="${i}" rel="stylesheet">`}e.stylesheets=t,e.styles=e.styles?`<style>${e.styles}</style>`:""}static prepareDispatchers(e,t){let s=null;if(e){let i=1;const n=e.split(/@([^= >]*)[ \t]*(?:=[ \t]*{{[ \t]*this\.([^}]*)[ \t]*}})?/);if(n.length>1){s=[];let l="";for(let r=0;r+2<n.length;r+=3){l+=n[r]+a.eventAttribute+i+" ";const d=n[r+1].trim(),w=n[r+2]!=null?n[r+2].trim():"_on"+d[0].toUpperCase()+d.substring(1);s.push([a.eventAttribute+i,d,t.prototype[w]]),i++}e=l+n[n.length-1]}}return{template:e,dispatcher:s}}static create(e,t){const s=a._oidReg[e];if(s==null)throw new Error("Unknown component id: "+e);const i=document.createElement(s.spec.element);if(t!=null)for(const n in t)i.setAttribute(n,t[n]);return i}static customize(e,t){e!=null&&a._oidReg[e]!=null&&t!=null&&t.cid!=null&&(a._oidCustom[e+"."+t.cid]=t,a._customQueue[e+"."+t.cid]!=null&&(a._customQueue[e+"."+t.cid](),delete a._customQueue[e+"."+t.cid]))}static async getCustom(e,t){return e==null||t==null?null:(a._oidCustom[e+"."+t]==null&&await new Promise((i,n)=>{const l=function(){i()};a._customQueue[e+"."+t]=l}),a._oidCustom[e+"."+t])}static setDefault(e){this._defaultSpec=e}static addDefault(e){for(const t in e)this._defaultSpec[t]==null?this._defaultSpec[t]=e[t]:Array.isArray(this._defaultSpec[t])?this._defaultSpec[t]=this._defaultSpec[t].concat(e[t]):typeof this._defaultSpec[t]=="object"?Object.assign(this._defaultSpec[t],e[t]):this._defaultSpec[t]=e[t]}};v(a,"eventAttribute","oidevent_"),v(a,"defaultInterface",["itf:oid"]),v(a,"_interfaceReg",{}),v(a,"_oidReg",{}),v(a,"_oidCustom",{}),v(a,"_customQueue",{}),v(a,"_defaultSpec",{});let c=a;c.cInterface({id:"itf:oid",operations:{get:{response:!0},set:{response:!1}},flow:"pull"}),c.cInterface({id:"itf:transfer",operations:["send"],flow:"push"}),c.cInterface({id:"itf:storage",operations:["store","load"],flow:"pull"}),c.cInterface({id:"itf:iterate",operations:{first:{response:!0},next:{response:!0}},flow:"pull",connections:"1"});class _ extends y{connectedCallback(){super.connectedCallback();const e=this._prepareHTML(),t=_.template.replace("{stylesheet}",this.stylesheet).replace("{code}",_.code.replace("{html}",e).replace("{rows}",this._rows(e))).replace("{console}",this.messages?_.console.replace("{rows}",this.rows?this.rows:_.rows):"");f.prepareShadow(this,t),this._scriptPanel=this.shadowRoot.querySelector("#script"),this._unlockScript=this._unlockScript.bind(this),this._scriptPanel.addEventListener("click",this._unlockScript),this._buttonRender=this.shadowRoot.querySelector("#btn-render"),this._buttonRender.addEventListener("click",this._computeRender.bind(this)),this._observer=new MutationObserver(this._scriptUpdated.bind(this)),this._observer.observe(this,{attributes:!0,childList:!0,subtree:!0}),this.sphere.bus.subscribe("#",this._busMonitor.bind(this))}static get observedAttributes(){return y.observedAttributes.concat(["messages","rows"])}get messages(){return this.hasAttribute("messages")}set messages(e){this.setAttribute("messages",e)}get rows(){return this.getAttribute("rows")}set rows(e){this.setAttribute("rows",e)}_scriptUpdated(e,t){const s=this._prepareHTML();this._scriptPanel.value=s,this._scriptPanel.rows=this._rows(s)}_rows(e){const t=e.split(/\r\n|\r|\n/);let s=0;return t.forEach(i=>{s+=Math.floor(i.length/45)+1}),s}_prepareHTML(){let e=this.innerHTML.replace('=""',"").replace(/^[\r\n]+/,"").replace(/[\r\n]+$/,"");if(e.startsWith(" ")||e.startsWith(" ")){const t=e.match(/^[ \t]+/);e=e.replace(new RegExp("^"+t,"gm"),"")}return e}_unlockScript(){this._scriptPanel.removeEventListener("click",this._unlockScript),this._scriptPanel.readOnly=!1,this._buttonRender.style.display="initial"}_computeRender(){this.shadowRoot.querySelector("#render").innerHTML=this._scriptPanel.value}_busMonitor(e,t){e!="bus/monitor"&&this.sphere.bus.publish("bus/monitor",{value:`[${e}] ${JSON.stringify(t)}`})}}_.rows=5,_.code=h`<div style="width:100%;display:flex">
<textarea id="script" class="code" style="width:100%;cursor:pointer" rows="{rows}" readonly>{html}</textarea>
<button id="btn-render" class="btn btn-secondary" style="width:auto;display:none">Render</button>
</div>`,_.template=h`<link rel="stylesheet" href="{stylesheet}">
{code}
<div id="render"><slot></slot></div>
{console}`,_.console=h`<div id="msg-pnl" style="width:100%">
<b>Messages on the Bus</b><br>
<console-oid rows="{rows}" class="code" prompt="" subscribe="bus/monitor~display"></console-oid>
</div>`,_.elementTag="oid-play",customElements.define(_.elementTag,_);class C extends g{async handleSubmit(e,t){const s={},i=this._getCustomField("schema");let n=null;if(i!=null)for(const l of Object.keys(i)){const r=document.querySelector(`#${l}`);r!=null&&(s[l]=r.value)}else{for(n=this.parentNode;n!=null&&n.nodeName.toLowerCase()!=="form";)n=n.parentNode;if(n!=null)for(const l of n)l.type==="radio"||l.type==="checkbox"?l.checked&&(l.type==="checkbox"||!l.hasAttribute("name")?s[l.id]=l.value:s[l.name]=l.value):s[l.id]=l.value}(!this._customExists("pre")||this._callCustom("pre",s)===!0)&&(this._notify("submit",s),this._notify("dispatch",{value:s}),this._invoke("itf:transfer","send",{value:s}))}handleUpdate(e,t){if(t.value){let s=this.parentNode;for(;s!=null&&s.nodeName.toLowerCase()!=="form";)s=s.parentNode;if(s!=null)for(const i of s)i.type==="radio"||i.type==="checkbox"?i.checked&&(i.type==="checkbox"||!i.hasAttribute("name")?i.value=t.value[i.id]:i.value=t.value[i.name]):i.value=t.value[i.id]}}}c.component({id:"oid:submit",element:"submit-oid",receive:["submit","update"],implementation:C});class A extends f{template(){let e=this.selection==="both"?h`<div class="group">`:"";return(this.selection==="drop"||this.selection==="both")&&(e+=h`<div class="drop" @dragover @drop>{{this.dropLabel}}</div>`),(this.selection==="dialog"||this.selection==="both")&&(e+=h`<input type="file" class="selector" @change></input>`),this.selection==="both"&&(e+="</div>"),e}_onDragover(e){this.pre&&(this._presentation.innerHTML=this.dropPre),e.preventDefault()}async _onDrop(e){e.preventDefault(),this.post&&(this._presentation.innerHTML=this.dropPost);let t=null;if(e.dataTransfer.items)for(const i of e.dataTransfer.items)i.kind==="file"&&(t=i.getAsFile());else t=e.dataTransfer.files[0];let s=await t.text();this.filetype==="json"&&(s=JSON.parse(s)),this._notify("dispatch",{value:s}),this._invoke("itf:transfer","send",{value:s})}_onChange(e){const t={},s=e.target.files[0];if(!s)t.error="No file selected";else{const i=new FileReader;i.onload=n=>{t.value=n.target.result,this.filetype==="json"&&(t.value=JSON.parse(t.value))},i.onerror=n=>{t.error=`Error reading file: ${n.target.error}`},i.readAsText(s)}this._notify("dispatch",t),this._invoke("itf:transfer","send",t)}handleRetrieve(e,t){}handleStore(e,t){let s=t.value||"";this.filetype==="json"&&(s=JSON.stringify(s));const i=document.createElement("a");i.style.display="none",document.body.appendChild(i),i.href=window.URL.createObjectURL(new Blob([s],{type:"text/plain"})),i.setAttribute("download",t.filename||this.filename),i.click(),window.URL.revokeObjectURL(i.href),document.body.removeChild(i)}}c.component({id:"oid:file",element:"file-oid",properties:{selection:{default:"both"},dropLabel:{default:"Drop Zone"},dropPre:{default:"Drop your file here"},dropPost:{default:"File loaded"},filename:{default:"file.txt"},filetype:{default:"plain"}},receive:["retrieve","store"],implementation:A,styles:m`
.group {
display: flex;
width: 100%;
height: 100%;
}
.drop {
width: 50%;
border: 5px solid;
}
.selector {
flex: 1;
}`});class N extends g{async handleLoad(e,t){const s=`${this.dataset}:${t.collection||this.collection}:${t.key||this.key}`,i=JSON.parse(localStorage.getItem(s));return this._notify("dispatch",{value:i}),this._invoke("itf:transfer","send",{value:i}),{value:i}}async handleStore(e,t){let s=!1;if(t.value){const i=`${this.dataset}:${t.collection||this.collection}:${t.key||this.key}`;localStorage.setItem(i,JSON.stringify(t.value)),s=!0}return s}}c.component({id:"oid:local-storage",element:"local-storage-oid",receive:["load","store"],provide:["itf:storage"],properties:{dataset:{default:"default-mundorum-oid"},collection:{default:"default"},key:{default:"default"}},implementation:N});class R extends g{async handleLoad(e,t){const s={};if(t.filename==null&&this.filename==null)s.error="No file name provided";else{const i=t.filename||this.filename,n=await fetch(`${i}`);n.ok?s.value=await n.json():s.error="Failed to load JSON"}return this._notify("dispatch",s),this._invoke("itf:transfer","send",s),s}}c.component({id:"oid:json-file",element:"json-file-oid",receive:["load"],properties:{filename:{}},implementation:R});class O extends f{_onClick(){this._notify("click",{value:this.label||this.source})}_onMouseenter(){this._notify("mouseenter",{value:this.label||this.source})}_onMouseleave(){this._notify("mouseleave",{value:this.label||this.source})}}c.component({id:"oid:image",element:"image-oid",properties:{source:{default:"assets:images/image.svg"},label:{}},implementation:O,stylesheets:"default",template:h`
<image id="oid-prs" src="{{url:this.source}}" alt="{{this.label}}"
@click @mouseenter @mouseleave>`});class T extends f{_onClick(){this._callCustom("click"),this._notify("click",{value:this.value||this.label}),this._invoke("itf:transfer","send",{value:this.value||this.label})}_onMouseenter(){this._notify("mouseenter",{value:this.value||this.label})}_onMouseleave(){this._notify("mouseleave",{value:this.value||this.label})}}c.component({id:"oid:button",element:"button-oid",properties:{label:{},value:{}},implementation:T,stylesheets:"default",template:h`
<button id="oid-prs" class="btn btn-primary"
@click @mouseenter @mouseleave>
{{this.label}}
</button>`});class L extends f{handleSend(e,t){this._presentation&&t&&t.value&&typeof t.value=="object"&&(t.value=JSON.stringify(t.value)),this._presentation.value+=(this.prompt.length>0?`${this.prompt} `:"")+`${t.value}
`}}c.component({id:"oid:console",element:"console-oid",properties:{prompt:{default:">"},rows:{default:10}},receive:{display:"handleSend"},provide:["itf:transfer"],implementation:L,styles:m`
.console {
width: 100%;
font-family: "Courier New", monospace;
font-size: 1em;
background-color: lightgray
}`,template:h`
<textarea class="console" rows="{{this.rows}}" id="oid-prs" readonly></textarea>`});class P extends f{connectedCallback(){this._value=this.getAttribute("value")||!1,super.connectedCallback()}static get observedAttributes(){return f.observedAttributes.concat(["variable","value"])}get variable(){return this._variable}set variable(e){this._variable=e}get value(){return this._value}set value(e){this._value=e}}class E extends P{connectedCallback(){super.connectedCallback(),this.hasAttribute("value")&&(this.value=this.getAttribute("value")!=="off",this.render()),this._notify("initial",{value:this.value?this.on:this.off})}render(){super.render(),this._input=this._presentation.querySelector("#oid-input"),this._input.checked=this.value}handleInvert(e,t){this.value=!this.value,this.value?this._input.checked=!0:this._input.checked=!1,this._notifyState()}handleOn(){this.value=!0,this._input.checked=!0,this._notifyState()}handleOff(){this.value=!1,this._input.checked=!1,this._notifyState()}handleRepublish(e,t){this.value&&this._notify("republish",t)}_onInput(){this._value=this._input.checked,this._notifyState()}_notifyState(){const e=this._value?this.on:this.off;this._notify("change",{value:e}),this._notify(e,{value:e})}}c.component({id:"oid:switch",element:"switch-oid",properties:{on:{default:"on"},off:{default:"off"}},receive:["invert","on","off","republish"],implementation:E,styles:m`
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}`,template:h`
<label id="oid-prs" class="switch">
<input id="oid-input" type="checkbox" @input>
<span class="slider round"></span>
</label>`});class z extends P{connectedCallback(){super.connectedCallback(),this.hasAttribute("value")||(this.value=Math.round((parseInt(""+this.min)+parseInt(""+this.max))/2),this.render()),this._notify("initial",{value:this.value})}render(){super.render(),this._input=this._presentation.querySelector("#oid-input"),this.hasAttribute("index")&&(this._index=this._presentation.querySelector("#index"),this._index.innerHTML=this.value)}_onInput(){this._value=this._input.value,this.hasAttribute("index")&&(this._index.innerHTML=this.value),this._notify("change",{value:this.value})}}c.component({id:"oid:slider",element:"slider-oid",properties:{min:{default:0},max:{default:100},index:{default:!1}},implementation:z,stylesheets:"default",template:h`
<div id="oid-prs" style="width:100%; display:flex; flex-direction:row">
<span id="index" style="flex:initial"></span>
<input type="range" id="oid-input" min="{{this.min}}" max="{{this.max}}"
value="{{this.value}}" style="flex:auto" @input>
</div>`});class M extends f{constructor(){super(),this._x=0,this._y=0,this._sideASize=0,this._onMousemove=this._onMousemove.bind(this),this._onMouseup=this._onMouseup.bind(this)}async connectedCallback(){await super.connectedCallback(),this._horz=this.split!=="vertical",this._resizer=this.shadowRoot.getElementById("resizer"),this._sidea=this.shadowRoot.getElementById("sidea"),this._sideb=this.shadowRoot.getElementById("sideb"),this._horz?(this._resizer.style.cursor="ew-resize",this._resizer.style.height="100%",this._resizer.classList.add("divide-x"),this._sidea.style.width=this.proportion):(this._resizer.style.cursor="ns-resize",this._presentation.style.flexDirection="column",this._resizer.style.width="100%",this._resizer.classList.add("divide-y"),this._sidea.style.height=this.proportion)}_onMousedown(e){this._x=e.clientX,this._y=e.clientY,this._sideASize=this._horz?this._sidea.getBoundingClientRect().width:this._sidea.getBoundingClientRect().height,this.shadowRoot.addEventListener("mousemove",this._onMousemove),this.shadowRoot.addEventListener("mouseup",this._onMouseup)}_onMousemove(e){const t=e.clientX-this._x,s=e.clientY-this._y;if(this._horz){const i=(this._sideASize+t)*100/this._presentation.getBoundingClientRect().width;this._sidea.style.width=i+"%",this._resizer.style.cursor="col-resize",document.body.style.cursor="col-resize"}else{const i=(this._sideASize+s)*100/this._presentation.getBoundingClientRect().height;this._sidea.style.height=i+"%",this._resizer.style.cursor="row-resize",document.body.style.cursor="row-resize"}this._sidea.style.userSelect="none",this._sidea.style.pointerEvents="none",this._sideb.style.userSelect="none",this._sideb.style.pointerEvents="none"}_onMouseup(e){this.shadowRoot.removeEventListener("mousemove",this._onMousemove),this.shadowRoot.removeEventListener("mouseup",this._onMouseup),this._resizer.style.cursor=this._horz?"ew-resize":"ns-resize",document.body.style.removeProperty("cursor"),this._sidea.style.removeProperty("user-select"),this._sidea.style.removeProperty("pointer-events"),this._sideb.style.removeProperty("user-select"),this._sideb.style.removeProperty("pointer-events"),this._notify("resize",{awidth:this._sidea.style.width,aheight:this._sidea.style.height,bwidth:this._sideb.style.width,bheight:this._sideb.style.height})}}c.component({id:"oid:split-pane",element:"split-pane-oid",properties:{split:{default:"horizontal"},proportion:{default:"50%"}},implementation:M,stylesheets:"default",styles:m`
.group {
display: flex;
width: 100%;
height: 100%;
}
.pane-b {
flex: 1;
}`,template:h`
<div id="oid-prs" class="group">
<div class="bg-base" id="sidea"><slot name="side-a"></slot></div>
<div class="divide" id="resizer" @mousedown></div>
<div class="pane-b bg-base" id="sideb"><slot name="side-b"></slot></div>
</div>`});class H extends f{async connectedCallback(){super.connectedCallback(),this._toInitial=this.initial,this._updateVisualState(),this._observer=new MutationObserver(this._updateVisualState.bind(this)),this._observer.observe(this,{childList:!0,subtree:!0})}_updateVisualState(){this._toInitial!=null&&(this._state=this.querySelector(`#${this._toInitial}`),this._state!=null&&(this._toInitial=null));const e=this.querySelectorAll("*");for(let t=0;t<e.length;t++){const s=e[t];this._state==null&&(this._state=s),s===this._state&&s.style.display!=null?s.style.removeProperty("display"):(s.style.display==null||s.style.display!=="none")&&(s.style.display="none")}}handleFirst(){this._state=this.firstElementChild,this._updateVisualState()}handleNext(){if(this._state!=null){let e=this._state.nextElementSibling;e==null&&(e=this.firstElementChild),this._state=e,this._updateVisualState()}}handlePrev(){if(this._state!=null){let e=this._state.previousElementSibling;e==null&&(e=this.lastElementChild),this._state=e,this._updateVisualState()}}handleLast(){this._state=this.lastElementChild,this._updateVisualState()}handleState(e,t){this._state=this.querySelector(`#${t.value}`),this._updateVisualState()}}c.component({id:"oid:state-pane",element:"state-pane-oid",properties:{initial:{}},receive:["first","next","prev","last","state"],implementation:H,stylesheets:"default"});class $ extends g{connectedCallback(){super.connectedCallback(),this._space=document.querySelector(`#${this.space}`)}handleUpdate(e,t){var s;this.space!=null&&((s=t.value)!=null&&s[this.source])&&(this.space.innerHTML=t.value[this.source])}}c.component({id:"oid:platform",element:"platform-oid",properties:{space:{default:"platform-oid-space"},source:{default:"source"}},receive:["update"],implementation:$}),o.Bus=b,o.ButtonOid=T,o.ConsoleOid=L,o.FileOid=A,o.ImageOid=O,o.JSONFileOid=R,o.LocalStorageOid=N,o.Oid=c,o.OidBase=S,o.OidPlay=_,o.OidSphere=y,o.OidUI=f,o.OidWeb=g,o.PlatformOid=$,o.Primitive=x,o.SliderOid=z,o.Sphere=u,o.SplitPaneOid=M,o.StatePaneOid=H,o.SubmitOid=C,o.SwitchOid=E,o.css=m,o.html=h,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})});