1 line
9.9 KiB
JavaScript
1 line
9.9 KiB
JavaScript
const t=[7,0,0],e=`bitty-${t[0]}-${t[1]}`;function n(t,e){null!==t&&(e.isTarget=t.target.dataset.bittyid===e.dataset.bittyid,e.isSender=e.sender.dataset.bittyid===e.dataset.bittyid),e.bittyParent=s(e),e.bittyParentBittyId=e.bittyParent.dataset.bittyid,e.bittyId=e.dataset.bittyid,e.ds=t=>c.call(null,e,t),e.dsInt=t=>parseInt(c.call(null,e,t)),e.dsFloat=t=>parseFloat(c.call(null,e,t)),null!==t&&(e.targetBittyId=t.target.dataset.bittyid),e.targetDs=e=>c.call(null,t.target,e),e.targetDsInt=e=>parseInt(c.call(null,t.target,e)),e.targetDsFloat=e=>parseFloat(c.call(null,t.target,e)),null!==t&&(e.senderBittyId=e.sender.dataset.bittyid),e.senderDs=t=>c.call(null,e.sender,t),e.senderDsInt=t=>parseInt(c.call(null,e.sender,t)),e.senderDsFloat=t=>parseFloat(c.call(null,e.sender,t)),e.value&&(e.val=e.value,e.valInt=parseInt(e.value,10),e.valFloat=parseFloat(e.value)),null!==t&&t.target.value&&(e.targetVal=t.target.value,e.targetValInt=parseInt(t.target.value,10),e.targetValFloat=parseFloat(t.target.value)),null!==t&&e.sender.value&&(e.senderVal=e.sender.value,e.senderValInt=parseInt(e.sender.value,10),e.senderValFloat=parseFloat(e.sender.value)),e.matchTargetDs=n=>{const a=c.call(null,t.target,n),s=c.call(null,e,n);return void 0!==a&&void 0!==s&&a===s},e.matchSenderDs=t=>{const n=c.call(null,e.sender,t),a=c.call(null,e,t);return void 0!==n&&void 0!==a&&n===a}}function a(t){return t.dataset&&t.dataset.send||t.dataset&&t.dataset.use?t:t.parentNode?a(t.parentNode):void 0}function s(t){return t.localName.toLowerCase()===e?t:t.parentNode?s(t.parentNode):null}class i extends Error{constructor(t){super(),Error.captureStackTrace&&Error.captureStackTrace(this,i),this.name="BittyError";for(let[e,n]of Object.entries(t))this[e]=n}}class r extends Event{constructor(t,e){super("bittyforward",{bubbles:!0}),this.forwardedEvent=t,this.forwardedSignal=e}}class o extends Event{constructor(t){super("bittylocaltrigger",{bubbles:!0}),this.signal=t}}class l extends Event{constructor(t){super("bittytrigger",{bubbles:!0}),this.signal=t}}function c(t,e){if(void 0!==t.dataset)return void 0!==t.dataset[e]?t.dataset[e]:t.parentNode?c(t.parentNode,e):void 0}class d extends HTMLElement{constructor(){super(),this.config={listeners:["click","input"],license:"CC0",version:t}}async connectedCallback(){this.dataset.bittyid=self.crypto.randomUUID(),await this.makeConnection(),this.conn&&(this.conn.api=this,this.handleEventBridge=this.handleEvent.bind(this),this.setIds(this),this.addEventListeners(),await this.runBittyInit(),await this.runDataInits(),await this.runBittyReady())}addEventListeners(){const t=["bittyforward","bittylocaltrigger","bittytrigger"];this.dataset.listeners?this.trimInput(this.dataset.listeners).forEach(e=>{t.push(e)}):(t.push("click"),t.push("input")),t.forEach(t=>{window.addEventListener(t,t=>{this.handleEventBridge.call(this,t)})})}connectedMoveCallback(){}doSubs(t,e){return e.forEach(e=>{const n=typeof e[1],a=Object.prototype.toString.call(e[1]);if("object"===n&&"[object Array]"===a){const n=e[1].map(t=>{const e=typeof t,n=Object.prototype.toString.call(t);return"object"===e&&"[object DocumentFragment]"===n?[...t.childNodes].map(t=>"[object Text]"===Object.prototype.toString.call(t)?t.wholeText:t.outerHTML).join(""):"object"===e?t.outerHTML:t}).join("");t=t.replaceAll(e[0],n)}else if("object"===n&&"[object DocumentFragment]"===a){const n=[];[...e[1].childNodes].forEach(t=>{"[object Text]"===Object.prototype.toString.call(t)?n.push(t.wholeText):n.push(t.outerHTML)}),t=t.replaceAll(e[0],n.join(""))}else t="object"==typeof e[1]?t.replaceAll(e[0],e[1].outerHTML):t.replaceAll(e[0],e[1])}),t}forward(t,e){const n=new r(t,e);this.dispatchEvent(n)}getBittyParent(t){return t.localName.toLowerCase()===e?t:t.parentNode?this.getBittyParent(t.parentNode):null}async getElement(t,e=[],n={}){const a=await this.getHTML(t,e,n,"getElement");if(a.value){return{value:a.value.firstChild}}return a}async getHTML(t,e=[],n={}){const a=await this.getTXT(t,e,n,"getHTML");return a.error?a:{value:this.makeHTML(a.value,e)}}async getJSON(t,e=[],n={}){const a=await this.getTXT(t,e,n,"getJSON");if(a.error)return a;try{const t=JSON.parse(a.value);return{value:t}}catch(t){return{error:new i({type:"parsing"})}}}async getSVG(t,e=[],n={}){const a=await this.getTXT(t,e,n,"getSVG");if(a.error)return a;{const t=document.createElement("template");t.innerHTML=a.value;return{value:t.content.cloneNode(!0).querySelector("svg")}}}async getTXT(t,e=[],n={},a="getTXT"){let s=await fetch(t,n);try{if(s.ok){return{value:this.doSubs(await s.text(),e)}}throw new i({type:"fetching",message:`${a}() returned ${s.status} [${s.statusText}] in:\n${a}(${s.url}, ${JSON.stringify(e)}, ${JSON.stringify(n)})`,statusText:s.statusText,status:s.status,url:s.url,incomingMethod:a,subs:e,options:n})}catch(t){return console.error(`BittyError: ${t.message}`),{error:t}}}async handleEvent(t){if(function(t){void 0!==t.target.value&&(t.val=t.target.value,t.valInt=parseInt(t.target.value,10),t.valFloat=parseFloat(event.target.value)),t.ds=e=>c.call(null,t.target,e),t.dsInt=e=>parseInt(c.call(null,t.target,e)),t.dsFloat=e=>parseFloat(c.call(null,t.target,e))}(t),"bittylocaltrigger"===t.type){const e=this.trimInput(t.signal),a=this.querySelectorAll("[data-receive]");for(let i of e){let e=!1;const r=i.split(":");if(2===r.length&&"await"===r[0]&&(e=!0,i=r[1]),this.conn[i]){const r=s(t.target);let o=!1;for(let l of a){l.sender=t.target;const a=s(l);if(r.dataset.bittyid===a.dataset.bittyid){const a=this.trimInput(l.dataset.receive);for(let s of a){const a=s.split(":");2===a.length&&"await"===a[0]&&(e=!0,s=a[1]),s===i&&(o=!0,n(t,l),e?await this.conn[i](t,l):this.conn[i](t,l))}}}!1===o&&r.dataset.bittyid===this.dataset.bittyid&&(e?await this.conn[i](t,null):this.conn[i](t,null))}}}else if("bittytrigger"===t.type){const e=this.trimInput(t.signal),a=this.querySelectorAll("[data-receive]");for(let s of e){let e=!1;const i=s.split(":");if(2===i.length&&"await"===i[0]&&(e=!0,s=i[1]),this.conn[s]){let i=!1;for(let r of a){r.sender=t.target;const a=this.trimInput(r.dataset.receive);for(let o of a){const a=o.split(":");2===a.length&&"await"===a[0]&&(e=!0,o=a[1]),o===s&&(i=!0,n(t,r),e?await this.conn[s](t,r):this.conn[s](t,r))}}!1===i&&(e?await this.conn[s](t,null):this.conn[s](t,null))}}}else if("bittyforward"===t.type){const e=this.trimInput(t.forwardedSignal);t=t.forwardedEvent;const a=this.querySelectorAll("[data-receive]");for(let s of a){s.sender=t.target,n(t,s);const a=this.trimInput(s.dataset.receive);for(let n of a)e.includes(n)&&this.conn[n]&&this.conn[n](t,s)}}else{const e=a(t.target);if(e){const a=this.querySelectorAll("[data-use]");if(e.dataset.use){const s=this.trimInput(e.dataset.use);if(a.length>0)for(let i of s){let s=!1;const r=i.split(":");if(2===r.length&&"await"===r[0]&&(s=!0,i=r[1]),this.conn[i])for(let r of a)r.sender=e,n(t,r),r.bittyId===r.senderBittyId&&(s?await this.conn[i](t,r):this.conn[i](t,r))}}if(e.dataset.send){const a=this.trimInput(e.dataset.send),s=this.querySelectorAll("[data-receive]");for(let i of a){let a=!1;const r=i.split(":");if(2===r.length&&"await"===r[0]&&(a=!0,i=r[1]),this.conn[i]){let r=!1;for(let o of s){o.sender=e;const s=this.trimInput(o.dataset.receive);for(const e of s){const s=e.split(":");2===s.length&&"await"===s[0]&&(e=s[1]),e===i&&(r=!0,n(t,o),a?await this.conn[i](t,o):this.conn[i](t,o))}}!1===r&&(a?await this.conn[i](t,null):this.conn[i](t,null))}}}}}}localTrigger(t){const e=new o(t);this.dispatchEvent(e)}async loadCSS(t,e,n){const a=await this.getTXT(t,e,n,"loadCSS");if(a.error)return a;{const t=new CSSStyleSheet;return t.replaceSync(a.value),document.adoptedStyleSheets.push(t),{value:a.value}}}async makeConnection(){try{if(this.dataset.connect){let t=this.trimInput(this.dataset.connect);if(void 0!==window[t[0]])this.conn=new window[t[0]];else{if("/"===t[0].substring(0,1)){const e=new URL(window.location.href);t[0]=new URL(t[0],e.origin).toString()}if("http"===t[0].substring(0,4)){const e=await import(t[0]);void 0===t[1]?this.conn=new e.default:this.conn=new e[t[1]]}else console.error(`Tried to use 'data-connect="${this.dataset.connect}" which did not match a class on the page which means an attempt to use it as a URL was made. It failed becasue the URL version of 'data-connect' must start with 'http' or '/'. Other URLs are not currently supported`)}}else window.BittyClass?this.conn=new window.BittyClass:console.error(`${e} error: No class to connect to.`)}catch(t){console.error(`${e} error: ${t} - ${this.dataset.connect}`)}}makeElement(t,e=[]){return this.makeHTML(t,e).firstChild}makeHTML(t,e=[]){const n=document.createElement("template");n.innerHTML=this.makeTXT(t,e).trim();const a=n.content.cloneNode(!0);return this.setIds(a),a}makeSVG(t,e=[]){const n=document.createElement("template");n.innerHTML=this.makeTXT(t,e).trim();return n.content.cloneNode(!0).querySelector("svg")}makeTXT(t,e=[]){return this.doSubs(t,e)}async runBittyInit(){"function"==typeof this.conn.bittyInit&&("AsyncFunction"===this.conn.bittyInit[Symbol.toStringTag]?await this.conn.bittyInit():this.conn.bittyInit())}async runBittyReady(){"function"==typeof this.conn.bittyReady&&("AsyncFunction"===this.conn.bittyReady[Symbol.toStringTag]?await this.conn.bittyReady():this.conn.bittyReady())}async runDataInits(){if(this.dataset.init){const t=this.trimInput(this.dataset.init);for(let e of t)"function"==typeof this.conn[e]&&("AsyncFunction"===this.conn[e][Symbol.toStringTag]?await this.conn[e](null,this):this.conn[e](null,this))}for(let t of this.querySelectorAll("[data-init]"))if(t.dataset.init){n(null,t);const e=this.trimInput(t.dataset.init);for(let n of e)"function"==typeof this.conn[n]&&("AsyncFunction"===this.conn[n][Symbol.toStringTag]?await this.conn[n](null,t):this.conn[n](null,t))}}setProp(t,e){document.documentElement.style.setProperty(t,e)}setIds(t){t.querySelectorAll("*").forEach(t=>{t.dataset.bittyid||(t.dataset.bittyid=self.crypto.randomUUID())})}trigger(t){const e=new l(t);this.dispatchEvent(e)}trimInput(t){return t.trim().split(/\s+/m).map(t=>t.trim())}}customElements.define(e,d); |