2 lines
15 KiB
JavaScript
2 lines
15 KiB
JavaScript
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ApigoState={})}(this,function(e){"use strict";var t;let n=null,a=null;const s=e=>n=e,r=e=>a=e,o=new Set;function i(e={},t=null,s=null){const r={},i=new Map,l=new Map,d=(e,t)=>(l.has(e)||l.set(e,new Set),t?l.get(e).add(t):l.get(e).clear(),()=>l.get(e).delete(t)),c=(e,t)=>{l.has(e)&&l.set(e,new Set),l.get(e).delete(t)},h=t||(e=>r[e]),u=s||((e,t)=>r[e]=t);return Object.assign(r,e),new Proxy(r,{get:(e,t)=>"__watch"===t?d:"__unwatch"===t?c:"__isProxy"===t||(n&&(i.has(t)||i.set(t,new Set),i.get(t).add(n),n.node._states||(n.node._states=new Set),n.node._states.add(i)),h(t)),set(e,t,n){if(h(t)!==n&&u(t,n),l.has(t)&&l.get(t).forEach(a=>{const s=a(n);void 0!==s&&(n=s,e[t]=n)}),l.has(null)&&l.get(null).forEach(e=>e(n)),i.has(t)){const e=i.get(t);for(const t of e)t.node.isConnected?a!==t.node&&o.forEach(e=>e(t)):e.delete(t)}return!0}})}const l=(e,t)=>t?e.querySelector(t):document.querySelector(e),d=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e),c=new Map,h=[],u={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...a)=>{console.log("Component.register:",e.toUpperCase()),c.set(e.toUpperCase(),t),"loading"!==document.readyState?u._addTemplate(e,n,a):h.push([e,n,a])},exists:e=>c.has(e.toUpperCase()),getSetupFunction:e=>c.get(e.toUpperCase()),_addTemplate:(e,t,n)=>{if(t){const n=document.createElement("TEMPLATE");n.setAttribute("component",e.toUpperCase()),n.content.appendChild(t),document.body.appendChild(n)}n&&n.forEach(e=>document.body.appendChild(e))},_initPending:()=>{h.forEach(([e,t,n])=>u._addTemplate(e,t,n)),h.length=0}};function f(e,t,n,a={}){e.attributes&&Array.from(e.attributes).forEach(e=>{"class"!==e.name&&("style"===e.name?t.hasAttribute("style")?t.setAttribute("style",`${e.value}; ${t.getAttribute("style")}`):t.setAttribute("style",e.value):t.hasAttribute(e.name)||t.setAttribute(e.name,e.value))}),t.classList.add(...e.classList);const s="TEMPLATE"===t.tagName?t.content:t,r="TEMPLATE"===e.tagName?e.content.childNodes:e.childNodes;Array.from(r).forEach(e=>s.appendChild(e)),e.tagName&&u.exists(e.tagName)&&b(e.tagName,t,n,a)}function b(e,t,n,a={}){if(a[e])return;a[e]=!0,n.thisObj&&Array.from(t.attributes).forEach(e=>{(e.name.startsWith("$")||e.name.startsWith("st-"))&&e.value.includes("this.")&&(e.value=e.value.replace(/\bthis\./g,"this.parent."))});const s=u.getSetupFunction(e),r={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(r[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=i(t.state||{});const o=u.getTemplate(e);if(o){const e=o.content.cloneNode(!0);if(e.childNodes.length){const s=e.children[0];s&&f(s,t,n,a),d(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");r[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",f(r[t],e,n,a))})}}s&&s(t)}let m=!1;function p(e){m=e}const g=new Map;function _(e,t,n,a){const s={...a||{},...t||{}},r=Object.keys(s),o=Object.values(s),i=e+r.join(",");try{let t=g.get(i);return t||(t=new Function("Hash","LocalStorage","State",...r,e),g.set(i,t)),t.apply(n,[globalThis.Hash,globalThis.LocalStorage,globalThis.State,...o])}catch(s){return m||console.error(s,a,[e,a,t,n]),null}}function y(e,t,n,a){return e.includes("${")?_("return `"+e+"`",t,n,a):_("return "+e,t,n,a)}let A=(e,t)=>e&&"string"==typeof e?e.replace(/\{(.+?)\}/g,(e,n)=>t.hasOwnProperty(n)?t[n]:e):e;const v=e=>A=e,E=e=>e&&"string"==typeof e&&e.includes("{#")?e.replace(/\{#(.+?)#\}/g,(e,t)=>{const n=t.split("||").map(e=>e.trim()),a={};if(n.length>1){const e=n[0].match(/\{(.+?)\}/g);e&&e.forEach((e,t)=>a[e.substring(1,e.length-1)]=n[t+1]||"")}return A(n[0],a)}):e;if("undefined"!=typeof document)try{document.createElement("div").setAttribute("$t","1")}catch(e){const t=Element.prototype.setAttribute;Element.prototype.setAttribute=function(e,n){return e.startsWith("$")?t.call(this,"st-"+e.substring(1),n):t.call(this,e,n)}}var N;function T(e){e._renderedNodes&&e._renderedNodes.forEach(e=>e.forEach(e=>{e.remove(),e._renderedNodes&&T(e)}))}function O(e){const t=e.node;if(!t.isConnected&&"TEMPLATE"!==t.tagName)return;s(e);let n=e.exp?e.tpl?y(e.tpl,{thisNode:t},t._thisObj||t,t._ref||null):null:e.tpl;if(2===e.exp&&"string"==typeof n)try{n=y(n,{thisNode:t},t._thisObj||t,t._ref||null)}catch(e){}if(s(null),e.prop){const a=e.prop;let s=t;for(let e=0;e<a.length-1&&(!a[e]||(null==s[a[e]]&&(s[a[e]]={}),s=s[a[e]],"object"==typeof s));e++);if("object"==typeof s&&null!==s){const e=a[a.length-1];if(e){"object"!=typeof n||null==n||Array.isArray(n)||null!=s[e]||(s[e]={});const t=s[e];"object"==typeof t&&null!=t&&t.__watch?Object.assign(t,n):s[e]!==n&&(s[e]=n)}else"object"!=typeof n||null==n||Array.isArray(n)||Object.assign(s,n)}}else if(e.attr){const a=e.attr;if("if"===a)n?t._renderedNodes&&0!==t._renderedNodes.length||(t._children.forEach(e=>{t.parentNode.insertBefore(e,t),e._ref={...t._ref},e._thisObj=t._thisObj}),t._renderedNodes=[t._children]):(T(t),t._renderedNodes=[]);else if("each"===a)if(n&&"object"==typeof n){const e=t.getAttribute("as")||"item",a=t.getAttribute("index")||"index",s=t.getAttribute("key");let r,o;if(n instanceof Map)r=Array.from(n.keys()),o=e=>n.get(e);else if("function"==typeof n[Symbol.iterator]){const e=Array.isArray(n)?n:Array.from(n);r=new Array(e.length);for(let t=0;t<e.length;t++)r[t]=t;o=t=>e[t]}else r=Object.keys(n),o=e=>n[e];t._keyedNodes||(t._keyedNodes=new Map);const i=new Map,l=[];r.forEach((n,r)=>{const d=o(n),c=s?d&&"object"==typeof d?d[s]:d:n,h=null==c||i.has(c)?`st_key_${r}`:c;let u=t._keyedNodes.get(h);u?(t._keyedNodes.delete(h),u.forEach(t=>{t._ref[a]=n,t._ref[e]=d,w(t)})):(u=[],t._children.forEach(s=>{const r=s.cloneNode(!0);r._ref={...t._ref,[a]:n,[e]:d},r._thisObj=t._thisObj,t.parentNode.insertBefore(r,t),u.push(r)})),i.set(h,u),l.push(u)}),t._keyedNodes.forEach(e=>e.forEach(e=>{T(e),e.remove()})),t._keyedNodes=i,t._renderedNodes=l}else T(t),t._renderedNodes=[];else if("bind"===a){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&!t.hasAttribute("autocomplete")&&t.setAttribute("autocomplete","off"),"checkbox"===t.type){"on"===t.value||n||(_(`${e.tpl} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),n=[]),t._checkboxMultiMode=n instanceof Array;const a=n instanceof Array?n.includes(t.value):!!n;t.checked!==a&&(t.checked=a)}else"radio"===t.type?t.checked!==(t.value===String(n??""))&&(t.checked=t.value===String(n??"")):"value"in t&&"file"!==t.type?Promise.resolve().then(()=>{t.value!==String(n??"")&&(t.value=n)}):t.isContentEditable&&t.innerHTML!==String(n??"")&&(t.innerHTML=n);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:n}))}else["checked","disabled","readonly"].includes(a)&&(n=!!n),"boolean"==typeof n?n?t.setAttribute(a,""):t.removeAttribute(a):void 0!==n&&("string"!=typeof n&&(n=JSON.stringify(n)),"text"===a?t.textContent=n??"":"html"===a?t.innerHTML=n??"":"IMG"===t.tagName&&"src"===a&&n.includes(".svg")?t.setAttribute("_src",n??""):t.setAttribute(a,n??""))}}N=e=>O(e),o.add(N);const S=e=>{e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),O(e)},w=(e,t={})=>{if(3===e.nodeType){if(e._stTranslated)return;const t=E(e.textContent);return t!==e.textContent&&(e.textContent=t),void(e._stTranslated=!0)}if(1!==e.nodeType)return;if(e._stTranslated||(Array.from(e.attributes).forEach(e=>{if(!e.name.startsWith("$")&&!e.name.startsWith("st-")&&!e.name.startsWith(".")){const t=E(e.value);t!==e.value&&(e.value=t)}}),e._stTranslated=!0),"TEMPLATE"!==e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("$each")||e.hasAttribute("st-if")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE");return Array.from(e.attributes).filter(t=>["$if","$each","st-if","st-each"].includes(t.name)||(e.hasAttribute("$each")||e.hasAttribute("st-each"))&&["as","index"].includes(t.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),e.parentNode.insertBefore(t,e),t.content.appendChild(e),void(t._ref=e._ref)}if("TEMPLATE"===e.tagName&&(e.hasAttribute("$if")||e.hasAttribute("st-if"))&&(e.hasAttribute("$each")||e.hasAttribute("st-each"))){const t=document.createElement("TEMPLATE"),n=Array.from(e.attributes).filter(e=>["$if","$each","st-if","st-each"].includes(e.name)),a=n[n.length-1];t.setAttribute(a.name,a.value),e.removeAttribute(a.name),"$each"!==a.name&&"st-each"!==a.name||Array.from(e.attributes).filter(e=>["as","index"].includes(e.name)).forEach(n=>{t.setAttribute(n.name,n.value),e.removeAttribute(n.name)}),Array.from(e.content.childNodes).forEach(e=>t.content.appendChild(e)),e.content.appendChild(t),t._ref=e._ref}if("IMG"===e.tagName&&(e.hasAttribute("src")||e.hasAttribute("_src")||e.hasAttribute("$src"))){const t=e;Promise.resolve().then(()=>{const e=t.getAttribute("_src")||t.getAttribute("src");e&&fetch(e,{cache:"force-cache"}).then(e=>e.text()).then(e=>{const n=(new DOMParser).parseFromString(e,"image/svg+xml").querySelector("svg");n&&(Array.from(t.attributes).forEach(e=>n.setAttribute(e.name,e.value)),t.replaceWith(n))})})}if(void 0!==e._thisObj)t.thisObj=e._thisObj||null;else{let n=e;for(;n&&void 0===n._thisObj;)n=n.parentNode;t.thisObj=n?n._thisObj:null}if(void 0===e._ref){let t=e;for(;t&&void 0===t._ref;)t=t.parentNode;e._ref=t?{...t._ref}:{}}t.extendVars&&Object.assign(e._ref,t.extendVars),((e,t)=>{if(e._bindings)return e._states=new Set,e._bindings.forEach(t=>O({node:e,...t})),void(e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})));u.exists(e.tagName)&&!e._componentInitialized&&(Array.from(e.attributes).forEach(n=>{var a;if(n.name.startsWith("$.")){const s=n.name.slice(2);let r=E(n.value);r.includes("this.")&&(r=r.replace(/\bthis\./g,"this.parent."));const o=y(r,{thisNode:e},{parent:t.thisObj||e},e._ref||{});let i=e;const l=s.split(".");for(let e=0;e<l.length-1;e++)l[e]&&(i=i[a=l[e]]??(i[a]={}));i[l[l.length-1]]=o,e.removeAttribute(n.name)}}),b(e.tagName,e,t),d(e,"[slot-id]").forEach(e=>e.removeAttribute("slot-id")),e._componentInitialized=!0,e._thisObj||(e._thisObj=e)),"TEMPLATE"===e.tagName&&(e._children=[...e.content.childNodes],e._renderedNodes||(e._renderedNodes=[]));let n=[];"TEMPLATE"===e.tagName?["$if","$each","st-if","st-each"].forEach(t=>e.hasAttribute(t)&&n.push(e.getAttributeNode(t))):n=Array.from(e.attributes).filter(e=>(e.name.startsWith("$")||e.name.startsWith("st-"))&&!["$if","$each","st-if","st-each"].includes(e.name)||e.name.includes(".")),e._thisObj&&t.thisObj&&(e._thisObj.parent=t.thisObj),e._thisObj||(e._thisObj=t.thisObj||null),e._ref||(e._ref=t.extendVars||{}),e._states=new Set,n.forEach(n=>{let a=0;n.name.startsWith("$$")||n.name.startsWith("st-st-")?a=2:(n.name.startsWith("$")||n.name.startsWith("st-"))&&(a=1);const s=2===a?n.name.startsWith("$$")?n.name.slice(2):n.name.slice(6):1===a?n.name.startsWith("$")?n.name.slice(1):n.name.slice(3):n.name;let o=n.value;if(e.removeAttribute(n.name),s.startsWith("."))S({node:e,prop:s.split("."),tpl:o,exp:a});else if(s.startsWith("on")){const n=s.slice(2);"update"===n&&(e._hasOnUpdate=!0),"load"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnLoad=!0),"unload"!==n||["BODY","IMG","IFRAME"].includes(e.tagName)||(e._hasOnUnload=!0),e.addEventListener(n,n=>_(o,{event:n,thisNode:e,...n.detail||{}},t.thisObj||e,e._ref||{}))}else"bind"===s?e.addEventListener(["textarea","text","password"].includes(e.type||"text")||e.isContentEditable?"input":"change",n=>{let a=e.isContentEditable?n.target.innerHTML:"checkbox"===e.type?n.target.checked:n.target.files||n.target.value||n.detail;r(e),p(!0),"checkbox"===e.type&&e._checkboxMultiMode?_(`!!checked ? (!${o}.includes(val) && ${o}.push(val)) : (index = ${o}.indexOf(val), index > -1 && ${o}.splice(index, 1))`,{val:e.value,checked:a,thisNode:e},t.thisObj||e,e._ref||{}):_(`${o} = val`,{val:a,thisNode:e},t.thisObj||e,e._ref||{}),p(!1),r(null)}):"text"!==s||o||(o=e.textContent,e.textContent=""),o&&(o=E(o),S({node:e,attr:s,tpl:o,exp:a}))}),(e._hasOnLoad||e._componentInitialized)&&Promise.resolve().then(()=>e.dispatchEvent(new Event("load",{bubbles:!1}))),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),e._thisObj&&(t.thisObj=e._thisObj)})(e,{...t});[...e.childNodes||[]].forEach(n=>w(n,{thisObj:t.thisObj,extendVars:{...e._ref}}))},j=e=>{1===e.nodeType&&(e._hasOnUnload&&e.dispatchEvent(new Event("unload",{bubbles:!1})),e._states&&e._states.forEach(t=>{for(const[n,a]of t)for(const t of a)t.node===e&&a.delete(t)}),e.childNodes&&e.childNodes.forEach(e=>j(e)))},x=w,$={clone:window.structuredClone||(e=>JSON.parse(JSON.stringify(e))),base64:e=>btoa(String.fromCharCode(...(new TextEncoder).encode(e))),unbase64:e=>(new TextDecoder).decode(Uint8Array.from(atob(e),e=>e.charCodeAt(0))),urlbase64:e=>$.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>$.unbase64(e.replace(/[-_.]/g,e=>({"-":"+",_:"/",".":"="}[e])).padEnd(4*Math.ceil(e.length/4),"=")),safeJson:e=>{try{return JSON.parse(e)}catch{return null}},updateDefaults:(e,t)=>{for(const n in t)void 0===e[n]&&(e[n]=t[n])},copyFunction:(e,t,...n)=>{n.forEach(n=>e[n]=t[n].bind(t))},getFunctionBody:e=>{const t=e.toString();return t.slice(t.indexOf("{")+1,t.lastIndexOf("}")).trim()},makeDom:e=>{e.includes(">\n")&&(e=e.replace(/>\s+</g,"><").trim());const t=document.createElement("div");return t.innerHTML=e,t.children[0]},newAvg:()=>{let e=0,t=0,n=0;return{add:a=>(e+=a,t++,n=e/t),get:()=>n,clear:()=>{e=0,t=0,n=0}}},newTimeCount:()=>{let e=0,t=0,n=0;return{start:()=>e=(new Date).getTime(),end:()=>{const a=(new Date).getTime(),s=a-e;return e=a,t+=s,n++,s},avg:()=>t/n}}};globalThis.Util=$;let M=new URLSearchParams((null==(t=window.location.hash)?void 0:t.substring(1))||"");const L=i({},e=>$.safeJson(M.get(e)),(e,t)=>{const n=M.get(e),a=void 0===t?void 0:JSON.stringify(t);n===a||null===n&&void 0===a||(void 0===t?M.delete(e):M.set(e,a),window.location.hash="#"+M.toString())});"undefined"!=typeof window&&window.addEventListener("hashchange",()=>{var e;const t=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||""),n=new Set([...M.keys(),...t.keys()]);M=t,n.forEach(e=>L[e]=L[e])});const C=i({},e=>$.safeJson(localStorage.getItem(e)),(e,t)=>{const n=localStorage.getItem(e),a=void 0===t?void 0:JSON.stringify(t);n===a||null===n&&void 0===a||(void 0===t?localStorage.removeItem(e):localStorage.setItem(e,a))}),k=i({exitBlocks:0});globalThis.Hash=L,globalThis.LocalStorage=C,globalThis.State=k;const P={NewState:i,Component:u,$:l,$$:d,RefreshState:x,SetTranslator:v,_scanTree:w,_unbindTree:j,Util:$,Hash:L,LocalStorage:C,State:k};if(globalThis.$=l,globalThis.$$=d,"undefined"!=typeof window&&(window.ApigoState=P),"undefined"!=typeof document){const e=()=>{u._initPending();const e=document.documentElement;e.hasAttribute("$data-bs-theme")||e.hasAttribute("data-bs-theme")||e.setAttribute("$data-bs-theme","LocalStorage.darkMode?'dark':'light'"),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.isConnected&&w(e)}),e.removedNodes.forEach(e=>j(e))})}).observe(document.documentElement,{childList:!0,subtree:!0}),w(document.documentElement)};"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e,!0)}e.$=l,e.$$=d,e.Component=u,e.Hash=L,e.LocalStorage=C,e.NewState=i,e.RefreshState=x,e.SetTranslator=v,e.State=k,e.Util=$,e._scanTree=w,e._unbindTree=j,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
|