diff --git a/dist/state.js b/dist/state.js index 11175fd..6f1d8ae 100644 --- a/dist/state.js +++ b/dist/state.js @@ -285,11 +285,23 @@ function _updateBinding(binding) { if (existingNodes) { node._keyedNodes.delete(keyVal); existingNodes.forEach((child) => { - child._ref[indexName] = k; - if (child._ref[asName] !== item) { + if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.reuseCount++; + let scopeChanged = false; + for (let key in node._ref) { + if (key === asName || key === indexName) continue; + if (child._ref[key] !== node._ref[key]) { + child._ref[key] = node._ref[key]; + scopeChanged = true; + } + } + const indexChanged = child._ref[indexName] !== k; + if (indexChanged) child._ref[indexName] = k; + if (child._ref[asName] !== item || scopeChanged) { child._ref[asName] = item; + if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.scanCount++; _scanTree(child, { thisObj: node._thisObj, extendVars: child._ref }); } else if (node.parentNode.lastChild !== child) { + if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.moveCount++; node.parentNode.insertBefore(child, node); } }); @@ -510,6 +522,9 @@ const _scanTree = (node, scanObj = {}) => { while (curr && curr._ref === void 0) curr = curr.parentNode; node._ref = curr ? { ...curr._ref } : {}; } + if (node._refExt !== void 0) { + Object.assign(node._ref, node._refExt); + } if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars); _parseNode(node, scanObj); const nodes = [...node.childNodes || []]; diff --git a/dist/state.min.js b/dist/state.min.js index f240414..d8a8e23 100644 --- a/dist/state.min.js +++ b/dist/state.min.js @@ -1 +1 @@ -var e;let t=null,n=null;const a=e=>t=e,r=e=>n=e,s=new Set;function o(e={},a=null,r=null){const o={},i=new Map,d=new Map,c=(e,t)=>(d.has(e)||d.set(e,new Set),t?d.get(e).add(t):d.get(e).clear(),()=>d.get(e).delete(t)),l=(e,t)=>{d.has(e)&&d.get(e).delete(t)},h=a||(e=>o[e]),u=r||((e,t)=>o[e]=t);return Object.assign(o,e),new Proxy(o,{get:(e,n)=>"__watch"===n?c:"__unwatch"===n?l:"__isProxy"===n||(t&&(i.has(n)||i.set(n,new Set),i.get(n).add(t),t.node._states||(t.node._states=new Set),t.node._states.add(i)),h(n)),set(e,t,a){if(h(t)!==a&&u(t,a),d.has(t)&&d.get(t).forEach(n=>{const r=n(a);void 0!==r&&(a=r,e[t]=a)}),d.has(null)&&d.get(null).forEach(e=>e(a)),i.has(t)){const e=i.get(t);for(const t of e)t.node.isConnected?n!==t.node&&s.forEach(e=>e(t)):e.delete(t)}return!0}})}const i=(e,t)=>t?e.querySelector(t):document.querySelector(e),d=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e),c=new Map,l=[],h={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...a)=>{c.set(e.toUpperCase(),t),"loading"!==document.readyState?h._addTemplate(e,n,a):l.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:()=>{l.forEach(([e,t,n])=>h._addTemplate(e,t,n)),l.length=0}};function u(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 r="TEMPLATE"===e.tagName?e.content:e,s="TEMPLATE"===t.tagName?t.content:t;Array.from(r.childNodes).forEach(e=>s.appendChild(e)),e.tagName&&h.exists(e.tagName)&&f(e.tagName,t,n,a)}function f(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 r=h.getSetupFunction(e),s={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(s[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=o(t.state||{});const i=h.getTemplate(e);if(i){const e=i.content.cloneNode(!0);if(e.childNodes.length){const r=Array.from(e.childNodes).find(e=>e.nodeType===Node.ELEMENT_NODE);r&&u(r,t,n,a),d(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");s[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",u(s[t],e,n,a))})}}r&&r(t)}let b=!1;function p(e){b=e}const m=new Map;function g(e,t,n,a){const r={...a||{},...t||{}},s=Object.keys(r),o=Object.values(r),i=e+s.join(",");try{let t=m.get(i);return t||(t=new Function("Hash","LocalStorage","State",...s,e),m.set(i,t)),t.apply(n,[globalThis.Hash,globalThis.LocalStorage,globalThis.State,...o])}catch(r){return b||console.error(r,a,[e,a,t,n]),null}}function _(e,t,n,a){return e.includes("${")?g("return `"+e+"`",t,n,a):g("return "+e,t,n,a)}let E=(e,t)=>e&&"string"==typeof e?e.replace(/\{(.+?)\}/g,(e,n)=>t.hasOwnProperty(n)?t[n]:e):e;const v=e=>E=e,y=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 E(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 A;function N(e){e._renderedNodes&&e._renderedNodes.forEach(e=>e.forEach(e=>{e.remove(),e._renderedNodes&&N(e)}))}function T(e){const t=e.node;if(!t.isConnected&&"TEMPLATE"!==t.tagName)return;a(e),window.__perfTrace&&window.__perfTrace.evalCount++;const n=window.__perfTrace?performance.now():0;let r=e.exp?e.tpl?_(e.tpl,{thisNode:t},t._thisObj||t,t._ref||null):null:e.tpl;if(window.__perfTrace&&(window.__perfTrace.evalTotal+=performance.now()-n),a(null),e.prop){const n=e.prop;let a=t;for(let e=0;ew(e,{thisObj:t._thisObj,extendVars:e._ref})):(t._children.forEach(e=>{e._stManaged=!0,t.parentNode.insertBefore(e,t),e._ref={...t._ref}}),t._renderedNodes=[t._children]):(N(t),t._renderedNodes=[]);else if("each"===n)if(r&&"object"==typeof r){const e=t.getAttribute("as")||"item",n=t.getAttribute("index")||"index",a=t.getAttribute("key");let s,o;if(r instanceof Map)s=Array.from(r.keys()),o=e=>r.get(e);else if("function"==typeof r[Symbol.iterator]){const e=Array.isArray(r)?r:Array.from(r);s=new Array(e.length);for(let t=0;te[t]}else s=Object.keys(r),o=e=>r[e];t._keyedNodes||(t._keyedNodes=new Map);const i=new Map,d=[];s.forEach((r,s)=>{const c=o(r),l=a?c&&"object"==typeof c?c[a]:c:r,h=null==l||i.has(l)?`st_key_fallback_${s}_${Math.random()}`:l;let u=t._keyedNodes.get(h);u?(t._keyedNodes.delete(h),u.forEach(a=>{a._ref[n]=r,a._ref[e]!==c?(a._ref[e]=c,w(a,{thisObj:t._thisObj,extendVars:a._ref})):t.parentNode.lastChild!==a&&t.parentNode.insertBefore(a,t)})):(u=[],t._children.forEach(a=>{const s=a.cloneNode(!0);s._stManaged=!0,s._ref={...t._ref,[n]:r,[e]:c},s._thisObj=t._thisObj,t.parentNode.insertBefore(s,t),u.push(s)})),i.set(h,u),d.push(u),u.forEach(e=>t.parentNode.insertBefore(e,t))}),t._keyedNodes.forEach(e=>e.forEach(e=>{N(e),e.remove()})),t._keyedNodes=i,t._renderedNodes=d}else N(t),t._keyedNodes&&t._keyedNodes.forEach(e=>e.forEach(e=>e.remove())),t._keyedNodes=new Map,t._renderedNodes=[];else if("bind"===n){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&!t.hasAttribute("autocomplete")&&t.setAttribute("autocomplete","off"),"checkbox"===t.type){"on"===t.value||r||(g(`${e.tpl} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),r=[]),t._checkboxMultiMode=r instanceof Array;const n=r instanceof Array?r.includes(t.value):!!r;t.checked!==n&&(t.checked=n)}else"radio"===t.type?t.checked!==(t.value===String(r??""))&&(t.checked=t.value===String(r??"")):"value"in t&&"file"!==t.type?setTimeout(()=>{t.value!==String(r??"")&&(t.value=r)}):t.isContentEditable&&t.innerHTML!==String(r??"")&&(t.innerHTML=r);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:r}))}else["checked","disabled","readonly"].includes(n)&&(r=!!r),"boolean"==typeof r?r?t.setAttribute(n,""):t.removeAttribute(n):void 0!==r&&("string"!=typeof r&&(r=JSON.stringify(r)),"text"===n?t.textContent=r??"":"html"===n?t.innerHTML=r??"":"IMG"===t.tagName&&"src"===n&&r.includes(".svg")?t.setAttribute("_src",r??""):t.setAttribute(n,r??""))}}A=e=>T(e),s.add(A);const O=e=>{e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),T(e)},w=(e,t={})=>{if(3===e.nodeType){if(e._stTranslated)return;const t=y(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=y(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)=>{let n=!1;if(e._bindings&&(e._states=new Set,e._bindings.forEach(t=>T({node:e,...t})),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),n=!0),h.exists(e.tagName)&&!e._componentInitialized&&(Array.from(e.attributes).forEach(n=>{var a;if(n.name.startsWith("$.")){const r=n.name.slice(2);let s=y(n.value);s.includes("this.")&&(s=s.replace(/\bthis\./g,"this.parent."));const o=_(s,{thisNode:e},{parent:t.thisObj||e},e._ref||{});let i=e;const d=r.split(".");for(let e=0;ee.removeAttribute("slot-id")),e._componentInitialized=!0,e._thisObj||(e._thisObj=e)),"TEMPLATE"===e.tagName&&(e._children=[...e.content.childNodes],e._renderedNodes||(e._renderedNodes=[])),n)return;let a=[];"TEMPLATE"===e.tagName?["$if","$each","st-if","st-each"].forEach(t=>e.hasAttribute(t)&&a.push(e.getAttributeNode(t))):a=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,a.forEach(n=>{const a=n.name.startsWith("$")||n.name.startsWith("st-"),s=a?n.name.slice(n.name.startsWith("$")?1:3):n.name;let o=n.value;if(e.removeAttribute(n.name),s.startsWith("."))O({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=>g(o,{event:n,thisNode:e,...n.detail||{}},t.thisObj||e,e._ref||{}))}else"bind"===s?e.addEventListener("TEXTAREA"===e.tagName||e.isContentEditable||"text"===e.type||"password"===e.type?"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?g(`!!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||{}):g(`${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=y(o),O({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);const n=[...e.childNodes||[]],a={thisObj:t.thisObj,extendVars:{...e._ref}};n.forEach(e=>{e._stManaged||w(e,a)})},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,M={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=>M.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>M.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+<").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(),r=a-e;return e=a,t+=r,n++,r},avg:()=>t/n}}};globalThis.Util=M;let S=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||"");const L=o({},e=>M.safeJson(S.get(e)),(e,t)=>{const n=S.get(e),a=void 0===t?void 0:JSON.stringify(t);n===a||null===n&&void 0===a||(void 0===t?S.delete(e):S.set(e,a),window.location.hash="#"+S.toString())});"undefined"!=typeof window&&window.addEventListener("hashchange",()=>{var e;const t=S;S=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||""),S.forEach((e,n)=>{t.get(n)!==e&&(L[n]=M.safeJson(e))}),t.forEach((e,t)=>{void 0===S.get(t)&&(L[t]=void 0)})});const $=o({},e=>M.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))});if(globalThis.Hash=L,globalThis.LocalStorage=$,"undefined"!=typeof document){const e=()=>{h._initPending(),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)}export{i as $,d as $$,h as Component,L as Hash,$ as LocalStorage,o as NewState,x as RefreshState,v as SetTranslator,M as Util,w as _scanTree,j as _unbindTree}; +var e;let t=null,n=null;const r=e=>t=e,a=e=>n=e,s=new Set;function o(e={},r=null,a=null){const o={},i=new Map,d=new Map,c=(e,t)=>(d.has(e)||d.set(e,new Set),t?d.get(e).add(t):d.get(e).clear(),()=>d.get(e).delete(t)),l=(e,t)=>{d.has(e)&&d.get(e).delete(t)},h=r||(e=>o[e]),u=a||((e,t)=>o[e]=t);return Object.assign(o,e),new Proxy(o,{get:(e,n)=>"__watch"===n?c:"__unwatch"===n?l:"__isProxy"===n||(t&&(i.has(n)||i.set(n,new Set),i.get(n).add(t),t.node._states||(t.node._states=new Set),t.node._states.add(i)),h(n)),set(e,t,r){if(h(t)!==r&&u(t,r),d.has(t)&&d.get(t).forEach(n=>{const a=n(r);void 0!==a&&(r=a,e[t]=r)}),d.has(null)&&d.get(null).forEach(e=>e(r)),i.has(t)){const e=i.get(t);for(const t of e)t.node.isConnected?n!==t.node&&s.forEach(e=>e(t)):e.delete(t)}return!0}})}const i=(e,t)=>t?e.querySelector(t):document.querySelector(e),d=(e,t)=>t?e.querySelectorAll(t):document.querySelectorAll(e),c=new Map,l=[],h={getTemplate:e=>document.querySelector(`template[component="${e.toUpperCase()}"]`),register:(e,t,n=null,...r)=>{c.set(e.toUpperCase(),t),"loading"!==document.readyState?h._addTemplate(e,n,r):l.push([e,n,r])},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:()=>{l.forEach(([e,t,n])=>h._addTemplate(e,t,n)),l.length=0}};function u(e,t,n,r={}){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 a="TEMPLATE"===e.tagName?e.content:e,s="TEMPLATE"===t.tagName?t.content:t;Array.from(a.childNodes).forEach(e=>s.appendChild(e)),e.tagName&&h.exists(e.tagName)&&f(e.tagName,t,n,r)}function f(e,t,n,r={}){if(r[e])return;r[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 a=h.getSetupFunction(e),s={};Array.from(t.childNodes).forEach(e=>{e.nodeType===Node.ELEMENT_NODE&&e.hasAttribute("slot")&&(s[e.getAttribute("slot")]=e,e.removeAttribute("slot"))}),t.innerHTML="",t.state=o(t.state||{});const i=h.getTemplate(e);if(i){const e=i.content.cloneNode(!0);if(e.childNodes.length){const a=Array.from(e.childNodes).find(e=>e.nodeType===Node.ELEMENT_NODE);a&&u(a,t,n,r),d(t,"[slot-id]").forEach(e=>{const t=e.getAttribute("slot-id");s[t]&&(e.removeAttribute("slot-id"),e.innerHTML="",u(s[t],e,n,r))})}}a&&a(t)}let b=!1;function m(e){b=e}const p=new Map;function _(e,t,n,r){const a={...r||{},...t||{}},s=Object.keys(a),o=Object.values(a),i=e+s.join(",");try{let t=p.get(i);return t||(t=new Function("Hash","LocalStorage","State",...s,e),p.set(i,t)),t.apply(n,[globalThis.Hash,globalThis.LocalStorage,globalThis.State,...o])}catch(a){return b||console.error(a,r,[e,r,t,n]),null}}function g(e,t,n,r){return e.includes("${")?_("return `"+e+"`",t,n,r):_("return "+e,t,n,r)}let E=(e,t)=>e&&"string"==typeof e?e.replace(/\{(.+?)\}/g,(e,n)=>t.hasOwnProperty(n)?t[n]:e):e;const y=e=>E=e,v=e=>e&&"string"==typeof e&&e.includes("{#")?e.replace(/\{#(.+?)#\}/g,(e,t)=>{const n=t.split("||").map(e=>e.trim()),r={};if(n.length>1){const e=n[0].match(/\{(.+?)\}/g);e&&e.forEach((e,t)=>r[e.substring(1,e.length-1)]=n[t+1]||"")}return E(n[0],r)}):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 A;function N(e){e._renderedNodes&&e._renderedNodes.forEach(e=>e.forEach(e=>{e.remove(),e._renderedNodes&&N(e)}))}function T(e){const t=e.node;if(!t.isConnected&&"TEMPLATE"!==t.tagName)return;r(e),window.__perfTrace&&window.__perfTrace.evalCount++;const n=window.__perfTrace?performance.now():0;let a=e.exp?e.tpl?g(e.tpl,{thisNode:t},t._thisObj||t,t._ref||null):null:e.tpl;if(window.__perfTrace&&(window.__perfTrace.evalTotal+=performance.now()-n),r(null),e.prop){const n=e.prop;let r=t;for(let e=0;eO(e,{thisObj:t._thisObj,extendVars:e._ref})):(t._children.forEach(e=>{e._stManaged=!0,t.parentNode.insertBefore(e,t),e._ref={...t._ref}}),t._renderedNodes=[t._children]):(N(t),t._renderedNodes=[]);else if("each"===n)if(a&&"object"==typeof a){const e=t.getAttribute("as")||"item",n=t.getAttribute("index")||"index",r=t.getAttribute("key");let s,o;if(a instanceof Map)s=Array.from(a.keys()),o=e=>a.get(e);else if("function"==typeof a[Symbol.iterator]){const e=Array.isArray(a)?a:Array.from(a);s=new Array(e.length);for(let t=0;te[t]}else s=Object.keys(a),o=e=>a[e];t._keyedNodes||(t._keyedNodes=new Map);const i=new Map,d=[];s.forEach((a,s)=>{const c=o(a),l=r?c&&"object"==typeof c?c[r]:c:a,h=null==l||i.has(l)?`st_key_fallback_${s}_${Math.random()}`:l;let u=t._keyedNodes.get(h);u?(t._keyedNodes.delete(h),u.forEach(r=>{window.__statePerformanceTelemetry&&window.__statePerformanceTelemetry.reuseCount++;let s=!1;for(let a in t._ref)a!==e&&a!==n&&r._ref[a]!==t._ref[a]&&(r._ref[a]=t._ref[a],s=!0);r._ref[n]!==a&&(r._ref[n]=a),r._ref[e]!==c||s?(r._ref[e]=c,window.__statePerformanceTelemetry&&window.__statePerformanceTelemetry.scanCount++,O(r,{thisObj:t._thisObj,extendVars:r._ref})):t.parentNode.lastChild!==r&&(window.__statePerformanceTelemetry&&window.__statePerformanceTelemetry.moveCount++,t.parentNode.insertBefore(r,t))})):(u=[],t._children.forEach(r=>{const s=r.cloneNode(!0);s._stManaged=!0,s._ref={...t._ref,[n]:a,[e]:c},s._thisObj=t._thisObj,t.parentNode.insertBefore(s,t),u.push(s)})),i.set(h,u),d.push(u),u.forEach(e=>t.parentNode.insertBefore(e,t))}),t._keyedNodes.forEach(e=>e.forEach(e=>{N(e),e.remove()})),t._keyedNodes=i,t._renderedNodes=d}else N(t),t._keyedNodes&&t._keyedNodes.forEach(e=>e.forEach(e=>e.remove())),t._keyedNodes=new Map,t._renderedNodes=[];else if("bind"===n){if(["INPUT","SELECT","TEXTAREA"].includes(t.tagName)&&!t.hasAttribute("autocomplete")&&t.setAttribute("autocomplete","off"),"checkbox"===t.type){"on"===t.value||a||(_(`${e.tpl} = []`,{thisNode:t},t._thisObj||t,t._ref||{}),a=[]),t._checkboxMultiMode=a instanceof Array;const n=a instanceof Array?a.includes(t.value):!!a;t.checked!==n&&(t.checked=n)}else"radio"===t.type?t.checked!==(t.value===String(a??""))&&(t.checked=t.value===String(a??"")):"value"in t&&"file"!==t.type?setTimeout(()=>{t.value!==String(a??"")&&(t.value=a)}):t.isContentEditable&&t.innerHTML!==String(a??"")&&(t.innerHTML=a);t.dispatchEvent(new CustomEvent("bind",{bubbles:!1,detail:a}))}else["checked","disabled","readonly"].includes(n)&&(a=!!a),"boolean"==typeof a?a?t.setAttribute(n,""):t.removeAttribute(n):void 0!==a&&("string"!=typeof a&&(a=JSON.stringify(a)),"text"===n?t.textContent=a??"":"html"===n?t.innerHTML=a??"":"IMG"===t.tagName&&"src"===n&&a.includes(".svg")?t.setAttribute("_src",a??""):t.setAttribute(n,a??""))}}A=e=>T(e),s.add(A);const w=e=>{e.node._bindings||(e.node._bindings=[]),e.node._bindings.push({attr:e.attr,prop:e.prop,tpl:e.tpl,exp:e.exp}),T(e)},O=(e,t={})=>{if(3===e.nodeType){if(e._stTranslated)return;const t=v(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=v(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)),r=n[n.length-1];t.setAttribute(r.name,r.value),e.removeAttribute(r.name),"$each"!==r.name&&"st-each"!==r.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}:{}}void 0!==e._refExt&&Object.assign(e._ref,e._refExt),t.extendVars&&Object.assign(e._ref,t.extendVars),((e,t)=>{let n=!1;if(e._bindings&&(e._states=new Set,e._bindings.forEach(t=>T({node:e,...t})),e._hasOnUpdate&&e.dispatchEvent(new Event("update",{bubbles:!1})),n=!0),h.exists(e.tagName)&&!e._componentInitialized&&(Array.from(e.attributes).forEach(n=>{var r;if(n.name.startsWith("$.")){const a=n.name.slice(2);let s=v(n.value);s.includes("this.")&&(s=s.replace(/\bthis\./g,"this.parent."));const o=g(s,{thisNode:e},{parent:t.thisObj||e},e._ref||{});let i=e;const d=a.split(".");for(let e=0;ee.removeAttribute("slot-id")),e._componentInitialized=!0,e._thisObj||(e._thisObj=e)),"TEMPLATE"===e.tagName&&(e._children=[...e.content.childNodes],e._renderedNodes||(e._renderedNodes=[])),n)return;let r=[];"TEMPLATE"===e.tagName?["$if","$each","st-if","st-each"].forEach(t=>e.hasAttribute(t)&&r.push(e.getAttributeNode(t))):r=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,r.forEach(n=>{const r=n.name.startsWith("$")||n.name.startsWith("st-"),s=r?n.name.slice(n.name.startsWith("$")?1:3):n.name;let o=n.value;if(e.removeAttribute(n.name),s.startsWith("."))w({node:e,prop:s.split("."),tpl:o,exp:r});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"===e.tagName||e.isContentEditable||"text"===e.type||"password"===e.type?"input":"change",n=>{let r=e.isContentEditable?n.target.innerHTML:"checkbox"===e.type?n.target.checked:n.target.files||n.target.value||n.detail;a(e),m(!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:r,thisNode:e},t.thisObj||e,e._ref||{}):_(`${o} = val`,{val:r,thisNode:e},t.thisObj||e,e._ref||{}),m(!1),a(null)}):"text"!==s||o||(o=e.textContent,e.textContent=""),o&&(o=v(o),w({node:e,attr:s,tpl:o,exp:r}))}),(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);const n=[...e.childNodes||[]],r={thisObj:t.thisObj,extendVars:{...e._ref}};n.forEach(e=>{e._stManaged||O(e,r)})},j=e=>{1===e.nodeType&&(e._hasOnUnload&&e.dispatchEvent(new Event("unload",{bubbles:!1})),e._states&&e._states.forEach(t=>{for(const[n,r]of t)for(const t of r)t.node===e&&r.delete(t)}),e.childNodes&&e.childNodes.forEach(e=>j(e)))},x=O,M={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=>M.base64(e).replace(/[+/=]/g,e=>({"+":"-","/":"","=":""}[e])),unurlbase64:e=>M.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+<").trim());const t=document.createElement("div");return t.innerHTML=e,t.children[0]},newAvg:()=>{let e=0,t=0,n=0;return{add:r=>(e+=r,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 r=(new Date).getTime(),a=r-e;return e=r,t+=a,n++,a},avg:()=>t/n}}};globalThis.Util=M;let S=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||"");const C=o({},e=>M.safeJson(S.get(e)),(e,t)=>{const n=S.get(e),r=void 0===t?void 0:JSON.stringify(t);n===r||null===n&&void 0===r||(void 0===t?S.delete(e):S.set(e,r),window.location.hash="#"+S.toString())});"undefined"!=typeof window&&window.addEventListener("hashchange",()=>{var e;const t=S;S=new URLSearchParams((null==(e=window.location.hash)?void 0:e.substring(1))||""),S.forEach((e,n)=>{t.get(n)!==e&&(C[n]=M.safeJson(e))}),t.forEach((e,t)=>{void 0===S.get(t)&&(C[t]=void 0)})});const L=o({},e=>M.safeJson(localStorage.getItem(e)),(e,t)=>{const n=localStorage.getItem(e),r=void 0===t?void 0:JSON.stringify(t);n===r||null===n&&void 0===r||(void 0===t?localStorage.removeItem(e):localStorage.setItem(e,r))});if(globalThis.Hash=C,globalThis.LocalStorage=L,"undefined"!=typeof document){const e=()=>{h._initPending(),new MutationObserver(e=>{e.forEach(e=>{e.addedNodes.forEach(e=>{e.isConnected&&O(e)}),e.removedNodes.forEach(e=>j(e))})}).observe(document.documentElement,{childList:!0,subtree:!0}),O(document.documentElement)};"loading"!==document.readyState?e():document.addEventListener("DOMContentLoaded",e,!0)}export{i as $,d as $$,h as Component,C as Hash,L as LocalStorage,o as NewState,x as RefreshState,y as SetTranslator,M as Util,O as _scanTree,j as _unbindTree}; diff --git a/src/dom.js b/src/dom.js index 6f260e5..6b2c303 100644 --- a/src/dom.js +++ b/src/dom.js @@ -137,7 +137,7 @@ export function _updateBinding(binding) { } const indexChanged = child._ref[indexName] !== k; if (indexChanged) child._ref[indexName] = k; - + if (child._ref[asName] !== item || scopeChanged) { child._ref[asName] = item; if (window.__statePerformanceTelemetry) window.__statePerformanceTelemetry.scanCount++; @@ -357,6 +357,9 @@ export const _scanTree = (node, scanObj = {}) => { while (curr && curr._ref === undefined) curr = curr.parentNode; node._ref = curr ? { ...curr._ref } : {}; } + if (node._refExt !== undefined) { + Object.assign(node._ref, node._refExt); + } if (scanObj.extendVars) Object.assign(node._ref, scanObj.extendVars); _parseNode(node, scanObj);