native-document 1.0.32 → 1.0.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var NativeDocument=function(t){"use strict";let n={};n={log(){},warn(){},error(){},disable(){}};var r=n;const o=function(){let e=0;const t=new Map;return{register(n){const r=++e;return t.set(r,new WeakRef(n)),r},unregister(e){t.delete(e)},getObservableById:e=>t.get(e)?.deref(),cleanup(){for(const[e,n]of t){const e=n.deref();e&&e.cleanup()}t.clear()},cleanObservables(e){if(t.size<e)return;let n=0;for(const[e,r]of t)r.deref()||(t.delete(e),n++);n>0&&r.log("Memory Auto Clean",`🧹 Cleaned ${n} orphaned observables`)}}}();class s extends Error{constructor(e,t={}){super(e),this.name="NativeDocumentError",this.context=t,this.timestamp=(new Date).toISOString()}}function i(e,t){this.observable=e,this.checker=t,this.unSubscriptions=[]}i.prototype.__$isObservableChecker=!0,i.prototype.subscribe=function(e){const t=this.observable.subscribe(t=>{e&&e(this.checker(t))});return this.unSubscriptions.push(t),t},i.prototype.check=function(e){return this.observable.check(()=>e(this.val()))},i.prototype.val=function(){return this.checker&&this.checker(this.observable.val())},i.prototype.set=function(e){return this.observable.set(e)},i.prototype.trigger=function(){return this.observable.trigger()},i.prototype.cleanup=function(){return this.observable.cleanup()};const a=function(){const e=new Map,t=new Map;return{list:()=>t,add(n,r){if(!r||"object"!=typeof r)throw new Error(`Plugin ${n} must be an object`);if(!e.has(n)){r.$name=n,e.set(n,r),"function"==typeof r?.init&&r.init();for(const e in r)/^on[A-Z]/.test(e)&&(t.has(e)||t.set(e,new Set),t.get(e).add(r))}},remove(n){if(!e.has(n))return;const r=e.get(n);"function"==typeof r.cleanup&&r.cleanup();for(const[e,n]of t.entries())n.has(r)&&n.delete(r),0===n.size&&t.delete(e);e.delete(n)},emit(e,...n){const o="on"+e;if(!t.has(o))return;const s=t.get(o);for(const e of s){const t=e[o];if("function"==typeof t)try{t.call(e,...n)}catch(t){r.error("Plugin Manager",`Error in plugin ${e.$name} for event ${o}`,t)}}}}}();function u(e){this.$previousValue=e,this.$currentValue=e,this.$isCleanedUp=!1,this.$listeners=null,this.$watchers=null,this.$memoryId=null,a.emit("CreateObservable",this)}Object.defineProperty(u.prototype,"$value",{get(){return this.$currentValue},set(e){this.set(e)},configurable:!0}),u.prototype.__$isObservable=!0;const l=function(){};u.prototype.triggerListeners=function(e){const t=this.$listeners,n=this.$previousValue,r=this.$currentValue;if(e=e||{},t?.length)for(let o=0,s=t.length;o<s;o++)t[o](r,n,e)},u.prototype.triggerWatchers=function(){if(!this.$watchers)return;const e=this.$watchers,t=this.$previousValue,n=this.$currentValue;e.has(n)&&e.get(n).forEach(e=>{e.set?e.set(!0):e(!0)}),e.has(t)&&e.get(t).forEach(e=>{e.set?e.set(!1):e(!1)})},u.prototype.triggerAll=function(e){this.triggerListeners(e),this.triggerWatchers()},u.prototype.assocTrigger=function(){this.$watchers?.size&&this.$listeners?.length?this.trigger=this.triggerAll:this.$listeners?.length?this.trigger=this.triggerListeners:this.$watchers?.size?this.trigger=this.triggerWatchers:this.trigger=l},u.prototype.trigger=l,u.prototype.set=function(e){const t="function"==typeof e?e(this.$currentValue):e;this.$currentValue!==t&&(this.$previousValue=this.$currentValue,this.$currentValue=t,a.emit("ObservableBeforeChange",this),this.trigger(),this.$previousValue=null,a.emit("ObservableAfterChange",this))},u.prototype.val=function(){return this.$currentValue},u.prototype.disconnectAll=function(){if(this.$listeners?.splice(0),this.$previousValue=null,this.$currentValue=null,this.$watchers)for(const[e,t]of this.$watchers)t.splice(0);this.$watchers?.clear(),this.$listeners=null,this.$watchers=null,this.trigger=l},u.prototype.cleanup=function(){o.unregister(this.$memoryId),this.disconnectAll(),this.$isCleanedUp=!0,delete this.$value},u.prototype.subscribe=function(e,t=null){if(this.$listeners=this.$listeners??[],this.$isCleanedUp)return r.warn("Observable subscription","⚠️ Attempted to subscribe to a cleaned up observable."),()=>{};if("function"!=typeof e)throw new s("Callback must be a function");return this.$listeners.push(e),this.assocTrigger(),a.emit("ObservableSubscribe",this,t),()=>{this.unsubscribe(e),this.assocTrigger(),a.emit("ObservableUnsubscribe",this)}},u.prototype.on=function(e,t){this.$watchers=this.$watchers??new Map;let n=this.$watchers.get(e);return n||(n=[],this.$watchers.set(e,n)),n.push(t),this.assocTrigger(),()=>{const r=n.indexOf(t);n?.splice(r,1),0===n.size&&(this.$watchers?.delete(e),n=null),this.assocTrigger()}},u.prototype.unsubscribe=function(e){const t=this.$listeners.indexOf(e);t>-1&&this.$listeners.splice(t,1),this.assocTrigger()},u.prototype.check=function(e){return new i(this,e)},u.prototype.get=u.prototype.check,u.prototype.when=function(e){return{$target:e,$observer:this}},u.prototype.toString=function(){return this.$memoryId||o.register(this),"{{#ObItem::("+this.$memoryId+")}}"};const c=(e,t,n)=>{if(m.isFunction(n))return n(e,t);if(m.isObservable(e)){const r=e.val();return r&&n?r[n]:t}return m.isObject(e)?e[n]??t:e},h=function(e,t){return e.replace(new RegExp(`^[${t}]+|[${t}]+$`,"g"),"")},d={mounted:new WeakMap,mountedSupposedSize:0,unmounted:new WeakMap,unmountedSupposedSize:0,observer:null,checkMutation:function(e){for(const t of e){if(d.mountedSupposedSize>0)for(const e of t.addedNodes){const t=d.mounted.get(e);t&&(t.inDom=!0,t.mounted&&t.mounted(e))}if(d.unmountedSupposedSize>0)for(const e of t.removedNodes){const t=d.unmounted.get(e);t&&(t.inDom=!1,t.unmounted&&!0===t.unmounted(e)&&(t.disconnect(),e.nd?.remove()))}}},watch:function(e,t=!1){let n={inDom:t,mounted:null,unmounted:null,disconnect:()=>{d.mounted.delete(e),d.unmounted.delete(e),d.mountedSupposedSize--,d.unmountedSupposedSize--,n=null}};return{disconnect:n.disconnect,mounted:t=>{n.mounted=t,d.mounted.set(e,n),d.mountedSupposedSize++},unmounted:t=>{n.unmounted=t,d.unmounted.set(e,n),d.unmountedSupposedSize++}}}};d.observer=new MutationObserver(d.checkMutation),d.observer.observe(document.body,{childList:!0,subtree:!0});const p=["Click","DblClick","MouseDown","MouseEnter","MouseLeave","MouseMove","MouseOut","MouseOver","MouseUp","Wheel","KeyDown","KeyPress","KeyUp","Blur","Change","Focus","Input","Invalid","Reset","Search","Select","Submit","Drag","DragEnd","DragEnter","DragLeave","DragOver","DragStart","Drop","AfterPrint","BeforePrint","BeforeUnload","Error","HashChange","Load","Offline","Online","PageHide","PageShow","Resize","Scroll","Unload","Abort","CanPlay","CanPlayThrough","DurationChange","Emptied","Ended","LoadedData","LoadedMetadata","LoadStart","Pause","Play","Playing","Progress","RateChange","Seeked","Seeking","Stalled","Suspend","TimeUpdate","VolumeChange","Waiting","TouchCancel","TouchEnd","TouchMove","TouchStart","AnimationEnd","AnimationIteration","AnimationStart","TransitionEnd","Copy","Cut","Paste","FocusIn","FocusOut","ContextMenu"];function f(e){this.$element=e,this.$observer=null,a.emit("NDElementCreated",e,this)}f.prototype.__$isNDElement=!0;for(const e of p){const t=e.toLowerCase();f.prototype["on"+e]=function(e){return this.$element.addEventListener(t,e),this},f.prototype["onPrevent"+e]=function(e){return this.$element.addEventListener(t,function(t){t.preventDefault(),e&&e(t)}),this},f.prototype["onStop"+e]=function(e){return this.$element.addEventListener(t,function(t){t.stopPropagation(),e&&e(t)}),this},f.prototype["onPreventStop"+e]=function(e){return this.$element.addEventListener(t,function(t){t.stopPropagation(),t.preventDefault(),e&&e(t)}),this}}f.prototype.valueOf=function(){return this.$element},f.prototype.ref=function(e,t){return e[t]=this.$element,this},f.prototype.unmountChildren=function(){let e=this.$element;for(let t=0,n=e.children.length;t<n;t++){let n=e.children[t];n.$ndProx||n.nd?.remove(),n=null}return e=null,this},f.prototype.remove=function(){let e=this.$element;return e.nd.unmountChildren(),e.$ndProx=null,delete e.nd?.on?.prevent,delete e.nd?.on,delete e.nd,e=null,this},f.prototype.lifecycle=function(e){return this.$observer=this.$observer||d.watch(this.$element),e.mounted&&this.$observer.mounted(e.mounted),e.unmounted&&this.$observer.unmounted(e.unmounted),this},f.prototype.mounted=function(e){return this.lifecycle({mounted:e})},f.prototype.unmounted=function(e){return this.lifecycle({unmounted:e})},f.prototype.htmlElement=function(){return this.$element},f.prototype.node=f.prototype.htmlElement;const m={isObservable:e=>e instanceof u||e instanceof i||e?.__$isObservable,isProxy:e=>e?.__isProxy__,isObservableChecker:e=>e instanceof i||e?.__$isObservableChecker,isArray:e=>Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e,isBoolean:e=>"boolean"==typeof e,isFunction:e=>"function"==typeof e,isAsyncFunction:e=>"function"==typeof e&&"AsyncFunction"===e.constructor.name,isObject:e=>"object"==typeof e,isJson:e=>"object"==typeof e&&null!==e&&"Object"===e.constructor.name&&!Array.isArray(e),isElement:e=>e instanceof HTMLElement||e instanceof DocumentFragment||e instanceof Text,isFragment:e=>e instanceof DocumentFragment,isStringOrObservable(e){return this.isString(e)||this.isObservable(e)},isValidChild(e){return null===e||this.isElement(e)||this.isObservable(e)||this.isNDElement(e)||["string","number","boolean"].includes(typeof e)},isNDElement:e=>e instanceof f||e?.constructor?.__$isNDElement,isValidChildren(e){Array.isArray(e)||(e=[e]);return 0===e.filter(e=>!this.isValidChild(e)).length},validateChildren(e){Array.isArray(e)||(e=[e]);const t=e.filter(e=>!this.isValidChild(e));if(t.length>0)throw new s(`Invalid children detected: ${t.map(e=>typeof e).join(", ")}`);return e},containsObservables:e=>!!e&&(m.isObject(e)&&Object.values(e).some(e=>m.isObservable(e))),containsObservableReference:e=>!(!e||"string"!=typeof e)&&/\{\{#ObItem::\([0-9]+\)\}\}/.test(e),validateAttributes(e){if(!e||"object"!=typeof e)return e;const t=[],n=Object.keys(e).filter(e=>t.includes(e));return n.length>0&&r.warn("Validator",`Reserved attributes found: ${n.join(", ")}`),e},validateEventCallback(e){if("function"!=typeof e)throw new s("Event callback must be a function")}};function b(e,t=!1){const n=document.createDocumentFragment(),o=document.createComment("Anchor Start : "+e),s=document.createComment("/ Anchor End "+e);n.appendChild(o),n.appendChild(s),n.nativeInsertBefore=n.insertBefore,n.nativeAppendChild=n.appendChild;return n.appendElement=function(e,r=null){t?r&&r!==s?s.parentNode.insertBefore(e,s):s.parentNode.append(e,s):s.parentNode!==n?s.parentNode?.insertBefore(e,r||s):s.parentNode.nativeInsertBefore(e,r||s)},n.appendChild=function(e,n=null){const o=s.parentNode;o?function(e,n,r){const o=m.isElement(n)?n:E.getChild(n);e!==o?t||r===s?e.append(o,r):e.insertBefore(o,r):e.nativeInsertBefore(o,r)}(o,e,n=n??s):r.error("Anchor","Anchor : parent not found",e)},n.removeChildren=function(){const e=s.parentNode;if(e===n)return;if(t||e.firstChild===o&&e.lastChild===s)return void e.replaceChildren(o,s);let r,i=o.nextSibling;const a=document.createDocumentFragment();for(;i&&i!==s;)r=i.nextSibling,a.append(i),i=r;a.replaceChildren()},n.remove=function(){const e=s.parentNode;if(e===n)return;if(t)return void e.replaceChildren(s,s);let r,i=o.nextSibling;for(;i!==s;)r=i.nextSibling,n.nativeAppendChild(i),i=r},n.removeWithAnchors=function(){n.removeChildren(),o.remove(),s.remove()},n.replaceContent=function(e){const r=s.parentNode;r&&(t||r.firstChild===o&&r.lastChild===s?r.replaceChildren(o,e,s):(n.removeChildren(),r.insertBefore(e,s)))},n.insertBefore=function(e,t=null){n.appendChild(e,t)},n.clear=function(){n.remove()},n.endElement=function(){return s},n.startElement=function(){return o},n}const g=["checked","selected","disabled","readonly","required","autofocus","multiple","autocomplete","hidden","contenteditable","spellcheck","translate","draggable","async","defer","autoplay","controls","loop","muted","download","reversed","open","default","formnovalidate","novalidate","scoped","itemscope","allowfullscreen","allowpaymentrequest","playsinline"];function v(e){return new u(e)}function y(e,t){for(let n in t){const r=t[n];m.isObservable(r)?(e.classList.toggle(n,r.val()),r.subscribe(t=>e.classList.toggle(n,t))):r.$observer?(e.classList.toggle(n,r.$observer.val()===r.$target),r.$observer.on(r.$target,function(t){e.classList.toggle(n,t)})):e.classList.toggle(n,r)}}function w(e,t){for(let n in t){const r=t[n];m.isObservable(r)?(e.style[n]=r.val(),r.subscribe(t=>{e.style[n]=t})):e.style[n]=r}}function C(e,t,n){const r=m.isObservable(n)?n.val():n;m.isBoolean(r)?e[t]=r:e[t]=r===e.value,m.isObservable(n)&&(["checked"].includes(t)&&e.addEventListener("input",()=>{m.isBoolean(r)?n.set(e[t]):n.set(e.value)}),n.subscribe(n=>{m.isBoolean(n)?e[t]=n:e[t]=n===e.value}))}function $(e,t,n){const r=n=>{"value"!==t?e.setAttribute(t,n):e.value=n};r(n.val()),n.subscribe(r),"value"===t&&e.addEventListener("input",()=>n.set(e.value))}v.getById=function(e){const t=o.getObservableById(parseInt(e));if(!t)throw new s("Observable.getById : No observable found with id "+e);return t},v.cleanup=function(e){e.cleanup()},v.autoCleanup=function(e=!1,t={}){if(!e)return;const{interval:n=6e4,threshold:r=100}=t;window.addEventListener("beforeunload",()=>{o.cleanup()}),setInterval(()=>o.cleanObservables(r),n)};const O=new Map;let S=null;const E={createTextNode:()=>(S||(S=document.createTextNode("")),S.cloneNode()),createObservableNode(e,t){const n=E.createTextNode();return t.subscribe(e=>n.nodeValue=e),n.nodeValue=t.val(),e&&e.appendChild(n),n},createStaticTextNode(e,t){let n=E.createTextNode();return n.nodeValue=t,e&&e.appendChild(n),n},createElement(e){if(e){if(O.has(e))return O.get(e).cloneNode();const t=document.createElement(e);return O.set(e,t),t.cloneNode()}return new b("Fragment")},processChildren(e,t){if(null===e)return;const n=Array.isArray(e)?e:[e];a.emit("BeforeProcessChildren",t);for(let e=0,r=n.length;e<r;e++){let r=this.getChild(n[e]);null!==r&&t.appendChild(r)}a.emit("AfterProcessChildren",t)},getChild(e){if(null===e)return null;if(m.isString(e)&&(e=e.resolveObservableTemplate?e.resolveObservableTemplate():e,m.isString(e)))return E.createStaticTextNode(null,e);if(m.isElement(e))return e;if(m.isObservable(e))return E.createObservableNode(null,e);if(m.isNDElement(e))return e.$element??e.$build?.()??null;if(m.isArray(e)){const t=document.createDocumentFragment();for(let n=0,r=e.length;n<r;n++)t.appendChild(this.getChild(e[n]));return t}return m.isFunction(e)?(a.emit("BeforeProcessComponent",e),this.getChild(e())):E.createStaticTextNode(null,e)},processAttributes(e,t){m.isFragment(e)||t&&function(e,t){if(m.validateAttributes(t),!m.isObject(t))throw new s("Attributes must be an object");for(let n in t){const r=n.toLowerCase();let o=t[r];if(m.isString(o)){if(o=o.resolveObservableTemplate?o.resolveObservableTemplate():o,m.isString(o)){e.setAttribute(r,o);continue}const t=o.filter(e=>m.isObservable(e));o=v.computed(()=>o.map(e=>m.isObservable(e)?e.val():e).join(" ")||" ",t)}"class"===r&&m.isJson(o)?y(e,o):"style"===r&&m.isJson(o)?w(e,o):g.includes(r)?C(e,r,o):m.isObservable(o)?$(e,r,o):e.setAttribute(r,o)}}(e,t)},setup:(e,t,n)=>(a.emit("Setup",e,t,n),e)};Object.defineProperty(HTMLElement.prototype,"nd",{configurable:!0,get(){return this.$nd||(this.$nd=new f(this),this.$nd.nd=this.$nd),this.$nd}});let A=e=>e;t.ArgTypes={},t.ArgTypes={string:()=>!0,number:()=>!0,boolean:()=>!0,observable:()=>!0,element:()=>!0,function:()=>!0,object:()=>!0,objectNotNull:()=>!0,children:()=>!0,attributes:()=>!0,optional:()=>!0,oneOf:()=>!0};const k=function(e,t=null){if(!m.isJson(e)){const n=t;t=e,e=n}return{props:e,children:t}};function I(e,t){return(n,r=null)=>function(e,t,n=null,r){const{props:o,children:s=null}=k(t,n),i=E.createElement(e),a="function"==typeof r?r(i):i;return E.processAttributes(a,o),E.processChildren(s,a),E.setup(a,o,r)}(e.toLowerCase(),n,r,t)}Function.prototype.args=function(...e){return this},Function.prototype.cached=function(...e){let t=null,n=function(){return t};return()=>(t||(t=this.apply(this,e),t.cloneNode?n=function(){return t.cloneNode(!0)}:t.$element&&(n=function(){return new f(t.$element.cloneNode(!0))})),n())},Function.prototype.errorBoundary=function(e){return(...t)=>{try{return this.apply(this,t)}catch(t){return e(t)}}},String.prototype.use=function(e){const t=this;return v.computed(()=>t.replace(/\$\{(.*?)}/g,(t,n)=>{const r=e[n];return m.isObservable(r)?r.val():r}),Object.values(e))},String.prototype.resolveObservableTemplate=function(){return m.containsObservableReference(this)?this.split(/(\{\{#ObItem::\([0-9]+\)\}\})/g).filter(Boolean).map(e=>{if(!m.containsObservableReference(e))return e;const[t,n]=e.match(/\{\{#ObItem::\(([0-9]+)\)\}\}/);return v.getById(n)}):this.valueOf()};const D=["push","pop","shift","unshift","reverse","sort","splice"];v.array=function(e){if(!Array.isArray(e))throw new s("Observable.array : target must be an array");const t=v(e);a.emit("CreateObservableArray",t),D.forEach(e=>{t[e]=function(...n){const r=t.val()[e](...n);return t.trigger({action:e,args:n,result:r}),r}}),t.clear=function(){return t.val().length=0,t.trigger({action:"clear"}),!0},t.merge=function(e){t.$value.push(...e),t.trigger({action:"merge",args:e})},t.populateAndRender=function(e,n){t.trigger({action:"populate",args:[t.val(),e,n]})},t.remove=function(e){const n=t.val().splice(e,1);return 0===n.length?[]:(t.trigger({action:"remove",args:[e],result:n[0]}),n)},t.swap=function(e,n){const r=t.val(),o=r.length;if(o<e||o<n)return!1;if(n<e){const t=e;e=n,n=t}const s=r[e],i=r[n];return r[e]=i,r[n]=s,t.trigger({action:"swap",args:[e,n],result:[s,i]}),!0},t.length=function(){return t.val().length};return["map","filter","reduce","some","every","find","findIndex","concat"].forEach(e=>{t[e]=function(...n){return t.val()[e](...n)}}),t},v.batch=function(e){const t=v(0),n=function(){if(m.isAsyncFunction(e))return e(...arguments).then(()=>{t.trigger()}).catch(e=>{throw e});e(...arguments),t.trigger()};return n.$observer=t,n},v.init=function(e){const t={};for(const n in e){const r=e[n];m.isJson(r)?t[n]=v.init(r):m.isArray(r)?t[n]=v.array(r):t[n]=v(r)}const n=function(){};return new Proxy(t,{get:(e,r)=>"__isProxy__"===r||("$value"===r?function(){const e={};for(const n in t){const r=t[n];m.isObservable(r)?e[n]=r.val():m.isProxy(r)?e[n]=r.$value:e[n]=r}return e}():"$clone"===r?n:void 0!==e[r]?e[r]:void 0),set(e,t,n){void 0!==e[t]&&e[t].set(n)}})},v.value=function(e){if(m.isObservable(e))return e.val();if(m.isProxy(e))return e.$value;if(m.isArray(e)){const t=[];for(let n=0,r=e.length;n<r;n++){const r=e[n];t.push(v.value(r))}return t}return e},v.update=function(e,t){for(const n in t){const r=e[n],o=t[n];if(m.isObservable(r)){if(m.isArray(o)){v.update(r,o);continue}r.set(o)}else m.isProxy(r)?v.update(r,o):e[n]=o}},v.object=v.init,v.json=v.init,v.computed=function(e,t=[]){const n=new u(e()),r=()=>n.set(e());if(a.emit("CreateObservableComputed",n,t),m.isFunction(t)){if(!m.isObservable(t.$observer))throw new s("Observable.computed : dependencies must be valid batch function");return t.$observer.subscribe(r),n}return t.forEach(e=>e.subscribe(r)),n};const x=function(){const e=new Map;return{use(t){const{observer:n,subscribers:r}=e.get(t),o=v(n.val()),s=n.subscribe(e=>o.set(e)),i=o.subscribe(e=>n.set(e));return o.destroy=()=>{s(),i(),o.cleanup()},r.add(o),o},follow(e){return this.use(e)},create(t,n){const r=v(n);return e.set(t,{observer:r,subscribers:new Set}),r},get(t){const n=e.get(t);return n?n.observer:null},getWithSubscribers:t=>e.get(t),delete(t){const n=e.get(t);n&&(n.observer.cleanup(),n.subscribers.forEach(e=>e.destroy()),n.observer.clear())}}}();const F=function(e,t,n=null){if(!m.isObservable(e))return r.warn("ShowIf","ShowIf : condition must be an Observable / "+n,e);const o=new b("Show if : "+(n||""));let s=null;const i=()=>s||(s=E.getChild(t),s);return e.val()&&o.appendChild(i()),e.subscribe(e=>{e?o.appendChild(i()):o.remove()}),o},T=function(e,t,n=!0){if(!m.isObservable(e))throw new s("Toggle : condition must be an Observable");const r=new b,o=new Map,i=function(e){if(n&&o.has(e))return o.get(e);let r=t[e];return r?(r=E.getChild(r),n&&o.set(e,r),r):null},a=e.val(),u=i(a);return u&&r.appendChild(u),e.subscribe(e=>{const t=i(e);r.remove(),t&&r.appendChild(t)}),r},N=function(e,t,n){if(!m.isObservable(e))throw new s("Toggle : condition must be an Observable");return T(e,{true:t,false:n})},P=I("div"),R=I("span"),L=I("label"),B=I("p"),M=B,q=I("strong"),j=I("h1"),_=I("h2"),V=I("h3"),H=I("h4"),z=I("h5"),W=I("h6"),U=I("br"),J=I("a"),K=I("pre"),Q=I("code"),Z=I("blockquote"),G=I("hr"),X=I("em"),Y=I("small"),ee=I("mark"),te=I("del"),ne=I("ins"),re=I("sub"),oe=I("sup"),se=I("abbr"),ie=I("cite"),ae=I("q"),ue=I("dl"),le=I("dt"),ce=I("dd"),he=I("form",function(e){return e.submit=function(t){return"function"==typeof t?(e.onSubmit(e=>{e.preventDefault(),t(e)}),e):(this.setAttribute("action",t),e)},e.multipartFormData=function(){return this.setAttribute("enctype","multipart/form-data"),e},e.post=function(t){return this.setAttribute("method","post"),this.setAttribute("action",t),e},e.get=function(e){this.setAttribute("method","get"),this.setAttribute("action",e)},e}),de=I("input"),pe=I("textarea"),fe=pe,me=I("select"),be=I("fieldset"),ge=I("option"),ve=I("legend"),ye=I("datalist"),we=I("output"),Ce=I("progress"),$e=I("meter"),Oe=I("button"),Se=I("main"),Ee=I("section"),Ae=I("article"),ke=I("aside"),Ie=I("nav"),De=I("figure"),xe=I("figcaption"),Fe=I("header"),Te=I("footer"),Ne=I("img"),Pe=function(e,t){return Ne({src:e,...t})},Re=I("details"),Le=I("summary"),Be=I("dialog"),Me=I("menu"),qe=I("ol"),je=I("ul"),_e=I("li"),Ve=_e,He=qe,ze=je,We=I("audio"),Ue=I("video"),Je=I("source"),Ke=I("track"),Qe=I("canvas"),Ze=I("svg"),Ge=I("time"),Xe=I("data"),Ye=I("address"),et=I("kbd"),tt=I("samp"),nt=I("var"),rt=I("wbr"),ot=I("caption"),st=I("table"),it=I("thead"),at=I("tfoot"),ut=I("tbody"),lt=I("tr"),ct=lt,ht=I("th"),dt=ht,pt=ht,ft=I("td"),mt=ft,bt=I("");var gt=Object.freeze({__proto__:null,Abbr:se,Address:Ye,Anchor:b,Article:Ae,Aside:ke,AsyncImg:function(e,t,n,r){const o=Pe(t||e,n),i=new Image;return i.onload=()=>{m.isFunction(r)&&r(null,o),o.src=e},i.onerror=()=>{m.isFunction(r)&&r(new s("Image not found"))},m.isObservable(e)&&e.subscribe(e=>{i.src=e}),i.src=e,o},Audio:We,BaseImage:Ne,Blockquote:Z,Br:U,Button:Oe,Canvas:Qe,Caption:ot,Checkbox:e=>de({type:"checkbox",...e}),Cite:ie,Code:Q,ColorInput:e=>de({type:"color",...e}),Data:Xe,Datalist:ye,DateInput:e=>de({type:"date",...e}),DateTimeInput:e=>de({type:"datetime-local",...e}),Dd:ce,Del:te,Details:Re,Dialog:Be,Div:P,Dl:ue,Dt:le,Em:X,EmailInput:e=>de({type:"email",...e}),FieldSet:be,FigCaption:xe,Figure:De,FileInput:e=>de({type:"file",...e}),Footer:Te,ForEach:function(e,t,n){const o=new b("ForEach"),s=o.endElement();o.startElement();let i=new Map,a=null;const u=new Set,l=e=>{for(const[t,n]of i.entries()){if(u.has(t))continue;const r=n.child?.deref();e&&r&&e.removeChild(r),n.indexObserver?.cleanup(),n.child=null,n.indexObserver=null,i.delete(n.keyId),a&&a.delete(n.keyId)}},h=(e,o)=>{const s=c(e,o,n);if(i.has(s)){const e=i.get(s);if(e.indexObserver?.set(o),e.isNew=!1,e.child?.deref())return s;i.delete(s)}try{const n=t.length>=2?v(o):null;let r=E.getChild(t(e,n));i.set(s,{keyId:s,isNew:!0,child:new WeakRef(r),indexObserver:n})}catch(e){throw r.error("ForEach",`Error creating element for key ${s}`,e),e}return s},d=()=>{const t=s.parentNode;if(!t)return;const n=m.isObservable(e)?e.val():e;if(u.clear(),Array.isArray(n))for(let e=0,t=n.length;e<t;e++){const t=h(n[e],e);u.add(t)}else for(const e in n){const t=h(n[e],e);u.add(t)}if(0===u.size)return o.removeChildren(),l(),void a?.clear();l(t),a&&0!==a.size?(()=>{let e=document.createDocumentFragment();const t=Array.from(u);Array.from(a);for(const n in t){const r=t[n],o=i.get(r);if(!o)continue;const s=o.child.deref();s&&e.appendChild(s)}o.replaceContent(e)})():(e=>{const t=document.createDocumentFragment();for(const e of u){const n=i.get(e);if(!n)continue;const r=n.child?.deref();r&&t.appendChild(r)}e.insertBefore(t,s)})(t),a?.clear(),a=new Set([...u])};return d(),m.isObservable(e)&&e.subscribe(d),o},ForEachArray:function(e,t,n,r={}){const o=new b("ForEach Array"),s=o.endElement(),i=o.startElement();let a=new Map,u=0;const l=t.length>=2,h=new WeakMap,d=()=>{o.removeChildren(),y(),u=0},p=(e,t)=>h.has(e)?h.get(e):c(e,t,n),f=e=>C(p(e)),g=(e,t=!0)=>{if(!e)return;const n=e.child;e.indexObserver?.deref()?.cleanup(),e.child=null,e.indexObserver=null,t&&(n?.remove(),a.delete(e.keyId))},y=()=>{for(const[e,t]of a.entries())g(t,!1);a.clear()},w=(e,n)=>{const r=p(e,n);if(a.has(r)){const e=a.get(r);e.indexObserver?.deref()?.set(n);const t=e.child;if(t)return t;a.delete(r)}const o=l?v(n):null;let s=E.getChild(t(e,o));return a.set(r,{keyId:r,child:s,indexObserver:o?new WeakRef(o):null}),h.set(e,r),s},C=function(e){const t=a.get(e);if(!t)return null;const n=t.child;return n||(g(t,!1),null)},$=function(e,t){const n=a.get(e);if(!n)return null;const r=n.child;if(!r)return null;t?t.appendChild(r):r.remove()},O={toFragment(e,t=0){const n=document.createDocumentFragment();for(let t=0,r=e.length;t<r;t++)n.append(w(e[t],u)),u++;return n},add(e,t=0){const n=O.toFragment(e);setTimeout(()=>{o.appendElement(n)},t)},replace(e){d(),O.add(e)},reOrder(e){let t=null;const n=document.createDocumentFragment();for(const r of e)t=f(r),t&&n.appendChild(t);t=null,o.appendElement(n,s)},removeOne(e,t){((e,t=!0)=>{g(a.get(e),t)})(p(e,t),!0),child=null},clear:d,merge(e){O.add(e,0)},push(e){let t=0;r.pushDelay&&(t=r.pushDelay(e)??0),O.add(e,t)},populate([e,t,n]){const r=document.createDocumentFragment();for(let o=0;o<t;o++){const t=n(o);e.push(t),r.append(w(t,o)),u++}o.appendChild(r),r.replaceChildren()},unshift(e){o.insertBefore(O.toFragment(e),i.nextSibling)},splice(e,t){const[n,r,...i]=e;let a=null;const u=document.createDocumentFragment();if(t.length>0){let e=p(t[0],n);if(1===t.length)$(e,u);else if(t.length>1){const r=C(e);a=r?.previousSibling;for(let e=0;e<t.length;e++){const r=p(t[e],n+e);$(r,u)}}}else a=s;u.replaceChildren(),i&&i.length&&a&&o.insertBefore(O.toFragment(i),a.nextSibling)},reverse(e,t){O.reOrder(t)},sort(e,t){O.reOrder(t)},remove(e,t){O.removeOne(t)},pop(e,t){O.removeOne(t)},shift(e,t){O.removeOne(t)},swap(e,t){const n=s.parentNode;let r=f(t[0]),o=f(t[1]);if(!r||!o)return;const i=o.nextSibling;n.insertBefore(o,r),n.insertBefore(r,i),r=null,o=null}},S=(e,t,n)=>{if("clear"!==n.action&&e.length){if(n?.action)O[n.action]&&O[n.action](n.args,n.result);else{if(0===u)return void O.add(e);O.replace(e)}((e,t=0)=>{if(!l)return;let n=t;for(let r=t,o=e?.length;r<o;r++){const t=a.get(p(e[r],r));t&&(t.indexObserver?.deref()?.set(n),n++)}})(e,0)}else{if(0===u)return;d()}};return S(e.val(),0,{action:null}),m.isObservable(e)&&e.subscribe(S),o},Form:he,Fragment:bt,H1:j,H2:_,H3:V,H4:H,H5:z,H6:W,Header:Fe,HiddenInput:e=>de({type:"hidden",...e}),HideIf:function(e,t,n){const r=v(!e.val());return e.subscribe(e=>r.set(!e)),F(r,t,n)},HideIfNot:function(e,t,n){return F(e,t,n)},Hr:G,Img:Pe,Input:de,Ins:ne,Kbd:et,Label:L,LazyImg:function(e,t){return Pe(e,{...t,loading:"lazy"})},Legend:ve,Li:Ve,Link:J,ListItem:_e,Main:Se,Mark:ee,Match:T,Menu:Me,Meter:$e,MonthInput:e=>de({type:"month",...e}),NativeDocumentFragment:b,Nav:Ie,NumberInput:e=>de({type:"number",...e}),Ol:He,Option:ge,OrderedList:qe,Output:we,P:B,Paragraph:M,PasswordInput:e=>de({type:"password",...e}),Pre:K,Progress:Ce,Quote:ae,Radio:e=>de({type:"radio",...e}),RangeInput:e=>de({type:"range",...e}),ReadonlyInput:e=>de({readonly:!0,...e}),Samp:tt,SearchInput:e=>de({type:"search",...e}),Section:Ee,Select:me,ShowIf:F,SimpleButton:(e,t)=>Oe(e,{type:"button",...t}),Small:Y,Source:Je,Span:R,Strong:q,Sub:re,SubmitButton:(e,t)=>Oe(e,{type:"submit",...t}),Summary:Le,Sup:oe,Svg:Ze,Switch:N,TBody:ut,TBodyCell:mt,TFoot:at,TFootCell:pt,THead:it,THeadCell:dt,TRow:ct,Table:st,Td:ft,TelInput:e=>de({type:"tel",...e}),TextArea:pe,TextInput:fe,Th:ht,Time:Ge,TimeInput:e=>de({type:"time",...e}),Tr:lt,Track:Ke,Ul:ze,UnorderedList:je,UrlInput:e=>de({type:"url",...e}),Var:nt,Video:Ue,Wbr:rt,WeekInput:e=>de({type:"week",...e}),When:function(e){if(!m.isObservable(e))throw new s("When : condition must be an Observable");let t=null,n=null;return{show(e){return t=e,this},otherwise:r=>(n=r,N(e,t,n))}}});const vt={};function yt(e,t,n={}){e="/"+h(e,"/");let r=null,o=n.name||null;const s=n.middlewares||[],i=n.shouldRebuild||!1,a=n.with||{},u={},l=[],c=e=>{if(!e)return null;const[t,n]=e.split(":");let r=a[t];return!r&&n&&(r=vt[n]),r||(r="[^/]+"),r=r.replace("(","(?:"),{name:t,pattern:`(${r})`}},d=()=>{if(r)return r;const t=e.replace(/\{(.*?)}/gi,(e,t)=>{const n=c(t);return n&&n.pattern?(u[n.name]=n.pattern,l.push(n.name),n.pattern):e});return r=new RegExp("^"+t+"$"),r};this.name=()=>o,this.component=()=>t,this.middlewares=()=>s,this.shouldRebuild=()=>i,this.path=()=>e,this.match=function(e){e="/"+h(e,"/");if(!d().exec(e))return!1;const t={};return d().exec(e).forEach((e,n)=>{if(n<1)return;const r=l[n-1];t[r]=e}),t},this.url=function(t){const n=e.replace(/\{(.*?)}/gi,(e,n)=>{const r=c(n);if(t.params&&t.params[r.name])return t.params[r.name];throw new Error(`Missing parameter '${r.name}'`)}),r="object"==typeof t.query?new URLSearchParams(t.query).toString():null;return(t.basePath?t.basePath:"")+(r?`${n}?${r}`:n)}}class wt extends Error{constructor(e,t){super(e),this.context=t}}const Ct=(e,t)=>{const n=[];return e.forEach(e=>{n.push(h(e.suffix,"/"))}),n.push(h(t,"/")),n.join("/")},$t=(e,t)=>{const n=[];return e.forEach(e=>{e.options.middlewares&&n.push(...e.options.middlewares)}),t&&n.push(...t),n},Ot=(e,t)=>{const n=[];return e.forEach(e=>{e.options?.name&&n.push(e.options.name)}),t&&n.push(t),n.join(".")};function St(){const e=[];let t=0;const n=n=>{const o=t+n;if(!e[o])return;t=o;const{route:s,params:i,query:a,path:u}=e[o];r(u)},r=e=>{window.location.replace(`${window.location.pathname}${window.location.search}#${e}`)},o=()=>window.location.hash.slice(1);this.push=function(n){const{route:s,params:i,query:a,path:u}=this.resolve(n);u!==o()&&(e.splice(t+1),e.push({route:s,params:i,query:a,path:u}),t++,r(u))},this.replace=function(n){const{route:r,params:s,query:i,path:a}=this.resolve(n);a!==o()&&(e[t]={route:r,params:s,query:i,path:a})},this.forward=function(){return t<e.length-1&&n(1)},this.back=function(){return t>0&&n(-1)},this.init=function(n){window.addEventListener("hashchange",()=>{const{route:e,params:t,query:n,path:r}=this.resolve(o());this.handleRouteChange(e,t,n,r)});const{route:r,params:s,query:i,path:a}=this.resolve(n||o());e.push({route:r,params:s,query:i,path:a}),t=0,this.handleRouteChange(r,s,i,a)}}function Et(){this.push=function(e){try{const{route:t,path:n,params:r,query:o}=this.resolve(e);if(window.history.state&&window.history.state.path===n)return;window.history.pushState({name:t.name(),params:r,path:n},t.name()||n,n),this.handleRouteChange(t,r,o,n)}catch(e){r.error("HistoryRouter","Error in pushState",e)}},this.replace=function(e){const{route:t,path:n,params:o}=this.resolve(e);try{window.history.replaceState({name:t.name(),params:o,path:n},t.name()||n,n),this.handleRouteChange(t,o,{},n)}catch(e){r.error("HistoryRouter","Error in replaceState",e)}},this.forward=function(){window.history.forward()},this.back=function(){window.history.back()},this.init=function(e){window.addEventListener("popstate",e=>{try{if(!e.state||!e.state.path)return;const t=e.state.path,{route:n,params:r,query:o,path:s}=this.resolve(t);if(!n)return;this.handleRouteChange(n,r,o,s)}catch(e){r.error("HistoryRouter","Error in popstate event",e)}});const{route:t,params:n,query:o,path:s}=this.resolve(e||window.location.pathname+window.location.search);this.handleRouteChange(t,n,o,s)}}function At(){const e=[];let t=0;const n=n=>{const r=t+n;if(!e[r])return;t=r;const{route:o,params:s,query:i,path:a}=e[r];this.handleRouteChange(o,s,i,a)};this.push=function(n){const{route:r,params:o,query:s,path:i}=this.resolve(n);e[t]&&e[t].path===i||(e.splice(t+1),e.push({route:r,params:o,query:s,path:i}),t++,this.handleRouteChange(r,o,s,i))},this.replace=function(n){const{route:r,params:o,query:s,path:i}=this.resolve(n);e[t]={route:r,params:o,query:s,path:i},this.handleRouteChange(r,o,s,i)},this.forward=function(){return t<e.length-1&&n(1)},this.back=function(){return t>0&&n(-1)},this.init=function(n){const r=n||window.location.pathname+window.location.search,{route:o,params:s,query:i,path:a}=this.resolve(r);e.push({route:o,params:s,query:i,path:a}),t=0,this.handleRouteChange(o,s,i,a)}}const kt="default";function It(e={}){const t=[],n={},o=[],s=[],i={route:null,params:null,query:null,path:null,hash:null};if("hash"===e.mode)St.apply(this,[]);else if("history"===e.mode)Et.apply(this,[]);else{if("memory"!==e.mode)throw new wt("Invalid router mode "+e.mode);At.apply(this,[])}const a=function(e,t){for(const n of s)try{n(e),t&&t(e)}catch(e){r.warn("Route Listener","Error in listener:",e)}};this.routes=()=>[...t],this.currentState=()=>({...i}),this.add=function(e,r,s){const i=new yt(Ct(o,e),r,{...s,middlewares:$t(o,s?.middlewares||[]),name:s?.name?Ot(o,s.name):null});return t.push(i),i.name()&&(n[i.name()]=i),this},this.group=function(e,t,n){if(!m.isFunction(n))throw new wt("Callback must be a function");return o.push({suffix:e,options:t}),n(),o.pop(),this},this.generateUrl=function(e,t={},r={}){const o=n[e];if(!o)throw new wt(`Route not found for name: ${e}`);return o.url({params:t,query:r})},this.resolve=function(e){if(m.isJson(e)){const t=n[e.name];if(!t)throw new wt(`Route not found for name: ${e.name}`);return{route:t,params:e.params,query:e.query,path:t.url({...e})}}const[r,o]=e.split("?"),s="/"+h(r,"/");let i,a=null;for(const e of t)if(i=e.match(s),i){a=e;break}if(!a)throw new wt(`Route not found for url: ${r}`);const u={};if(o){const e=new URLSearchParams(o).entries();for(const[t,n]of e)u[t]=n}return{route:a,params:i,query:u,path:e}},this.subscribe=function(e){if(!m.isFunction(e))throw new wt("Listener must be a function");return s.push(e),()=>{s.splice(s.indexOf(e),1)}},this.handleRouteChange=function(e,t,n,r){i.route=e,i.params=t,i.query=n,i.path=r;const o=[...e.middlewares(),a];let s=0;const u={...i},l=e=>{if(s++,!(s>=o.length))return o[s](e||u,l)};return o[s](u,l)}}function Dt(e,t){const{to:n,href:r,...o}=e,s=n||r;if(m.isString(s)){const e=It.get();return J({...o,href:s},t).nd.onPreventClick(()=>{e.push(s)})}const i=s.router||kt,a=It.get(i);if(!a)throw new wt('Router not found "'+i+'" for link "'+s.name+'"');const u=a.generateUrl(s.name,s.params,s.query);return J({...o,href:u},t).nd.onPreventClick(()=>{a.push(u)})}It.routers={},It.create=function(t,n){if(!m.isFunction(n))throw r.error("Router","Callback must be a function",e),new wt("Callback must be a function");const o=new It(t);return It.routers[t.name||kt]=o,n(o),o.init(t.entry),o.mount=function(e){if(m.isString(e)){const t=document.querySelector(e);if(!t)throw new wt(`Container not found for selector: ${e}`);e=t}else if(!m.isElement(e))throw new wt("Container must be a string or an Element");return function(e,t){const n=new Map,r=function(e){t.innerHTML="",t.appendChild(e)},o=function(e){if(!e.route)return;const{route:t,params:o,query:s,path:i}=e;if(n.has(i)){const e=n.get(i);return void r(e)}const a=t.component()({params:o,query:s});n.set(i,a),r(a)};return e.subscribe(o),o(e.currentState()),t}(o,e)},o},It.get=function(e){const t=It.routers[e||kt];if(!t)throw new wt(`Router not found for name: ${e}`);return t},It.push=function(e,t=null){return It.get(t).push(e)},It.replace=function(e,t=null){return It.get(t).replace(e)},It.forward=function(e=null){return It.get(e).forward()},It.back=function(e=null){return It.get(e).back()},Dt.blank=function(e,t){return J({...e,target:"_blank"},t)};var xt=Object.freeze({__proto__:null,Link:Dt,RouteParamPatterns:vt,Router:It});return t.ElementCreator=E,t.HtmlElementWrapper=I,t.NDElement=f,t.Observable=v,t.Store=x,t.classPropertyAccumulator=function(e=[]){let t=m.isString(e)?e.split(" ").filter(Boolean):e;const n=m.isArray(t);return{add(e,r=!0){n?t.push(e):t[e]=r},value:()=>n?t.join(" "):{...t}}},t.cssPropertyAccumulator=function(e={}){let t=m.isString(e)?e.split(";").filter(Boolean):e;const n=m.isArray(t);return{add(e,r){n?t.push(e+" : "+r):t[e]=r},value:()=>n?t.join(";").concat(";"):{...t}}},t.elements=gt,t.normalizeComponentArgs=k,t.router=xt,t.withValidation=A,t}({});
1
+ var NativeDocument=function(t){"use strict";let n={};n={log(){},warn(){},error(){},disable(){}};var r=n;const o=function(){let e=0;const t=new Map;return{register(n){const r=++e;return t.set(r,new WeakRef(n)),r},unregister(e){t.delete(e)},getObservableById:e=>t.get(e)?.deref(),cleanup(){for(const[e,n]of t){const e=n.deref();e&&e.cleanup()}t.clear()},cleanObservables(e){if(t.size<e)return;let n=0;for(const[e,r]of t)r.deref()||(t.delete(e),n++);n>0&&r.log("Memory Auto Clean",`🧹 Cleaned ${n} orphaned observables`)}}}();class s extends Error{constructor(e,t={}){super(e),this.name="NativeDocumentError",this.context=t,this.timestamp=(new Date).toISOString()}}function i(e,t){this.observable=e,this.checker=t,this.unSubscriptions=[]}i.prototype.__$isObservableChecker=!0,i.prototype.subscribe=function(e){const t=this.observable.subscribe(t=>{e&&e(this.checker(t))});return this.unSubscriptions.push(t),t},i.prototype.check=function(e){return this.observable.check(()=>e(this.val()))},i.prototype.val=function(){return this.checker&&this.checker(this.observable.val())},i.prototype.set=function(e){return this.observable.set(e)},i.prototype.trigger=function(){return this.observable.trigger()},i.prototype.cleanup=function(){return this.observable.cleanup()};const a=function(){const e=new Map,t=new Map;return{list:()=>t,add(n,r){if(!r||"object"!=typeof r)throw new Error(`Plugin ${n} must be an object`);if(!e.has(n)){r.$name=n,e.set(n,r),"function"==typeof r?.init&&r.init();for(const e in r)/^on[A-Z]/.test(e)&&(t.has(e)||t.set(e,new Set),t.get(e).add(r))}},remove(n){if(!e.has(n))return;const r=e.get(n);"function"==typeof r.cleanup&&r.cleanup();for(const[e,n]of t.entries())n.has(r)&&n.delete(r),0===n.size&&t.delete(e);e.delete(n)},emit(e,...n){const o="on"+e;if(!t.has(o))return;const s=t.get(o);for(const e of s){const t=e[o];if("function"==typeof t)try{t.call(e,...n)}catch(t){r.error("Plugin Manager",`Error in plugin ${e.$name} for event ${o}`,t)}}}}}();function u(e){this.$previousValue=e,this.$currentValue=e,this.$isCleanedUp=!1,this.$listeners=null,this.$watchers=null,this.$memoryId=null,a.emit("CreateObservable",this)}Object.defineProperty(u.prototype,"$value",{get(){return this.$currentValue},set(e){this.set(e)},configurable:!0}),u.prototype.__$isObservable=!0;const l=function(){};u.prototype.triggerListeners=function(e){const t=this.$listeners,n=this.$previousValue,r=this.$currentValue;if(e=e||{},t?.length)for(let o=0,s=t.length;o<s;o++)t[o](r,n,e)},u.prototype.triggerWatchers=function(){if(!this.$watchers)return;const e=this.$watchers,t=this.$previousValue,n=this.$currentValue;if(e.has(n)){const t=e.get(n);"function"==typeof t?t(!0):t.set?t.set(!0):t.forEach(e=>{e.set?e.set(!0):e(!0)})}if(e.has(t)){const n=e.get(t);"function"==typeof n?n(!1):n.set?n.set(!1):n.forEach(e=>{e.set?e.set(!1):e(!1)})}},u.prototype.triggerAll=function(e){this.triggerListeners(e),this.triggerWatchers()},u.prototype.assocTrigger=function(){this.$watchers?.size&&this.$listeners?.length?this.trigger=this.triggerAll:this.$listeners?.length?this.trigger=this.triggerListeners:this.$watchers?.size?this.trigger=this.triggerWatchers:this.trigger=l},u.prototype.trigger=l,u.prototype.set=function(e){const t="function"==typeof e?e(this.$currentValue):e;this.$currentValue!==t&&(this.$previousValue=this.$currentValue,this.$currentValue=t,a.emit("ObservableBeforeChange",this),this.trigger(),this.$previousValue=null,a.emit("ObservableAfterChange",this))},u.prototype.val=function(){return this.$currentValue},u.prototype.disconnectAll=function(){if(this.$listeners?.splice(0),this.$previousValue=null,this.$currentValue=null,this.$watchers)for(const[e,t]of this.$watchers)m.isArray(t)&&t.splice(0);this.$watchers?.clear(),this.$listeners=null,this.$watchers=null,this.trigger=l},u.prototype.cleanup=function(){o.unregister(this.$memoryId),this.disconnectAll(),this.$isCleanedUp=!0,delete this.$value},u.prototype.subscribe=function(e,t=null){if(this.$listeners=this.$listeners??[],this.$isCleanedUp)return r.warn("Observable subscription","⚠️ Attempted to subscribe to a cleaned up observable."),()=>{};if("function"!=typeof e)throw new s("Callback must be a function");return this.$listeners.push(e),this.assocTrigger(),a.emit("ObservableSubscribe",this,t),()=>{this.unsubscribe(e),this.assocTrigger(),a.emit("ObservableUnsubscribe",this)}},u.prototype.on=function(e,t){this.$watchers=this.$watchers??new Map;let n=this.$watchers.get(e);if(n){if(!m.isArray(n))return n=[n],void this.$watchers.set(e,n);n.push(t)}else this.$watchers.set(e,t);return this.assocTrigger(),()=>{const r=n.indexOf(t);n?.splice(r,1),1===n.size?this.$watchers.set(e,n[0]):0===n.size&&(this.$watchers?.delete(e),n=null),this.assocTrigger()}},u.prototype.unsubscribe=function(e){const t=this.$listeners.indexOf(e);t>-1&&this.$listeners.splice(t,1),this.assocTrigger()},u.prototype.check=function(e){return new i(this,e)},u.prototype.get=u.prototype.check,u.prototype.when=function(e){return{$target:e,$observer:this}},u.prototype.toString=function(){return this.$memoryId||o.register(this),"{{#ObItem::("+this.$memoryId+")}}"};const c=(e,t,n)=>{if(m.isFunction(n))return n(e,t);if(m.isObservable(e)){const r=e.val();return r&&n?r[n]:t}return m.isObject(e)?e[n]??t:e},h=function(e,t){return e.replace(new RegExp(`^[${t}]+|[${t}]+$`,"g"),"")},d={mounted:new WeakMap,mountedSupposedSize:0,unmounted:new WeakMap,unmountedSupposedSize:0,observer:null,checkMutation:function(e){for(const t of e){if(d.mountedSupposedSize>0)for(const e of t.addedNodes){const t=d.mounted.get(e);t&&(t.inDom=!0,t.mounted&&t.mounted(e))}if(d.unmountedSupposedSize>0)for(const e of t.removedNodes){const t=d.unmounted.get(e);t&&(t.inDom=!1,t.unmounted&&!0===t.unmounted(e)&&(t.disconnect(),e.nd?.remove()))}}},watch:function(e,t=!1){let n={inDom:t,mounted:null,unmounted:null,disconnect:()=>{d.mounted.delete(e),d.unmounted.delete(e),d.mountedSupposedSize--,d.unmountedSupposedSize--,n=null}};return{disconnect:n.disconnect,mounted:t=>{n.mounted=t,d.mounted.set(e,n),d.mountedSupposedSize++},unmounted:t=>{n.unmounted=t,d.unmounted.set(e,n),d.unmountedSupposedSize++}}}};d.observer=new MutationObserver(d.checkMutation),d.observer.observe(document.body,{childList:!0,subtree:!0});const p=["Click","DblClick","MouseDown","MouseEnter","MouseLeave","MouseMove","MouseOut","MouseOver","MouseUp","Wheel","KeyDown","KeyPress","KeyUp","Blur","Change","Focus","Input","Invalid","Reset","Search","Select","Submit","Drag","DragEnd","DragEnter","DragLeave","DragOver","DragStart","Drop","AfterPrint","BeforePrint","BeforeUnload","Error","HashChange","Load","Offline","Online","PageHide","PageShow","Resize","Scroll","Unload","Abort","CanPlay","CanPlayThrough","DurationChange","Emptied","Ended","LoadedData","LoadedMetadata","LoadStart","Pause","Play","Playing","Progress","RateChange","Seeked","Seeking","Stalled","Suspend","TimeUpdate","VolumeChange","Waiting","TouchCancel","TouchEnd","TouchMove","TouchStart","AnimationEnd","AnimationIteration","AnimationStart","TransitionEnd","Copy","Cut","Paste","FocusIn","FocusOut","ContextMenu"];function f(e){this.$element=e,this.$observer=null,a.emit("NDElementCreated",e,this)}f.prototype.__$isNDElement=!0;for(const e of p){const t=e.toLowerCase();f.prototype["on"+e]=function(e){return this.$element.addEventListener(t,e),this},f.prototype["onPrevent"+e]=function(e){return this.$element.addEventListener(t,function(t){t.preventDefault(),e&&e(t)}),this},f.prototype["onStop"+e]=function(e){return this.$element.addEventListener(t,function(t){t.stopPropagation(),e&&e(t)}),this},f.prototype["onPreventStop"+e]=function(e){return this.$element.addEventListener(t,function(t){t.stopPropagation(),t.preventDefault(),e&&e(t)}),this}}f.prototype.valueOf=function(){return this.$element},f.prototype.ref=function(e,t){return e[t]=this.$element,this},f.prototype.unmountChildren=function(){let e=this.$element;for(let t=0,n=e.children.length;t<n;t++){let n=e.children[t];n.$ndProx||n.nd?.remove(),n=null}return e=null,this},f.prototype.remove=function(){let e=this.$element;return e.nd.unmountChildren(),e.$ndProx=null,delete e.nd?.on?.prevent,delete e.nd?.on,delete e.nd,e=null,this},f.prototype.lifecycle=function(e){return this.$observer=this.$observer||d.watch(this.$element),e.mounted&&this.$observer.mounted(e.mounted),e.unmounted&&this.$observer.unmounted(e.unmounted),this},f.prototype.mounted=function(e){return this.lifecycle({mounted:e})},f.prototype.unmounted=function(e){return this.lifecycle({unmounted:e})},f.prototype.htmlElement=function(){return this.$element},f.prototype.node=f.prototype.htmlElement,f.prototype.attach=function(e,t){return t.$hydrate(this.$element,e),this.$element};const m={isObservable:e=>e instanceof u||e instanceof i||e?.__$isObservable,isProxy:e=>e?.__isProxy__,isObservableChecker:e=>e instanceof i||e?.__$isObservableChecker,isArray:e=>Array.isArray(e),isString:e=>"string"==typeof e,isNumber:e=>"number"==typeof e,isBoolean:e=>"boolean"==typeof e,isFunction:e=>"function"==typeof e,isAsyncFunction:e=>"function"==typeof e&&"AsyncFunction"===e.constructor.name,isObject:e=>"object"==typeof e,isJson:e=>"object"==typeof e&&null!==e&&"Object"===e.constructor.name&&!Array.isArray(e),isElement:e=>e instanceof HTMLElement||e instanceof DocumentFragment||e instanceof Text,isFragment:e=>e instanceof DocumentFragment,isStringOrObservable(e){return this.isString(e)||this.isObservable(e)},isValidChild(e){return null===e||this.isElement(e)||this.isObservable(e)||this.isNDElement(e)||["string","number","boolean"].includes(typeof e)},isNDElement:e=>e instanceof f||e?.constructor?.__$isNDElement,isValidChildren(e){Array.isArray(e)||(e=[e]);return 0===e.filter(e=>!this.isValidChild(e)).length},validateChildren(e){Array.isArray(e)||(e=[e]);const t=e.filter(e=>!this.isValidChild(e));if(t.length>0)throw new s(`Invalid children detected: ${t.map(e=>typeof e).join(", ")}`);return e},containsObservables:e=>!!e&&(m.isObject(e)&&Object.values(e).some(e=>m.isObservable(e))),containsObservableReference:e=>!(!e||"string"!=typeof e)&&/\{\{#ObItem::\([0-9]+\)\}\}/.test(e),validateAttributes(e){if(!e||"object"!=typeof e)return e;const t=[],n=Object.keys(e).filter(e=>t.includes(e));return n.length>0&&r.warn("Validator",`Reserved attributes found: ${n.join(", ")}`),e},validateEventCallback(e){if("function"!=typeof e)throw new s("Event callback must be a function")}};function b(e,t=!1){const n=document.createDocumentFragment(),o=document.createComment("Anchor Start : "+e),s=document.createComment("/ Anchor End "+e);n.appendChild(o),n.appendChild(s),n.nativeInsertBefore=n.insertBefore,n.nativeAppendChild=n.appendChild;return n.appendElement=function(e,r=null){t?r&&r!==s?s.parentNode.insertBefore(e,s):s.parentNode.append(e,s):s.parentNode!==n?s.parentNode?.insertBefore(e,r||s):s.parentNode.nativeInsertBefore(e,r||s)},n.appendChild=function(e,n=null){const o=s.parentNode;o?function(e,n,r){const o=m.isElement(n)?n:E.getChild(n);e!==o?t||r===s?e.append(o,r):e.insertBefore(o,r):e.nativeInsertBefore(o,r)}(o,e,n=n??s):r.error("Anchor","Anchor : parent not found",e)},n.removeChildren=function(){const e=s.parentNode;if(e===n)return;if(t||e.firstChild===o&&e.lastChild===s)return void e.replaceChildren(o,s);let r,i=o.nextSibling;const a=document.createDocumentFragment();for(;i&&i!==s;)r=i.nextSibling,a.append(i),i=r;a.replaceChildren()},n.remove=function(){const e=s.parentNode;if(e===n)return;if(t)return void e.replaceChildren(s,s);let r,i=o.nextSibling;for(;i!==s;)r=i.nextSibling,n.nativeAppendChild(i),i=r},n.removeWithAnchors=function(){n.removeChildren(),o.remove(),s.remove()},n.replaceContent=function(e){const r=s.parentNode;r&&(t||r.firstChild===o&&r.lastChild===s?r.replaceChildren(o,e,s):(n.removeChildren(),r.insertBefore(e,s)))},n.insertBefore=function(e,t=null){n.appendChild(e,t)},n.clear=function(){n.remove()},n.endElement=function(){return s},n.startElement=function(){return o},n}const g=["checked","selected","disabled","readonly","required","autofocus","multiple","autocomplete","hidden","contenteditable","spellcheck","translate","draggable","async","defer","autoplay","controls","loop","muted","download","reversed","open","default","formnovalidate","novalidate","scoped","itemscope","allowfullscreen","allowpaymentrequest","playsinline"];function v(e){return new u(e)}function y(e,t){for(let n in t){const r=t[n];m.isObservable(r)?(e.classList.toggle(n,r.val()),r.subscribe(t=>e.classList.toggle(n,t))):r.$observer?(e.classList.toggle(n,r.$observer.val()===r.$target),r.$observer.on(r.$target,function(t){e.classList.toggle(n,t)})):r.$hydrate?r.$hydrate(e,n):e.classList.toggle(n,r)}}function w(e,t){for(let n in t){const r=t[n];m.isObservable(r)?(e.style[n]=r.val(),r.subscribe(t=>{e.style[n]=t})):e.style[n]=r}}function $(e,t,n){const r=m.isObservable(n)?n.val():n;m.isBoolean(r)?e[t]=r:e[t]=r===e.value,m.isObservable(n)&&(["checked"].includes(t)&&e.addEventListener("input",()=>{m.isBoolean(r)?n.set(e[t]):n.set(e.value)}),n.subscribe(n=>{m.isBoolean(n)?e[t]=n:e[t]=n===e.value}))}function C(e,t,n){const r=n=>{"value"!==t?e.setAttribute(t,n):e.value=n};r(n.val()),n.subscribe(r),"value"===t&&e.addEventListener("input",()=>n.set(e.value))}v.getById=function(e){const t=o.getObservableById(parseInt(e));if(!t)throw new s("Observable.getById : No observable found with id "+e);return t},v.cleanup=function(e){e.cleanup()},v.autoCleanup=function(e=!1,t={}){if(!e)return;const{interval:n=6e4,threshold:r=100}=t;window.addEventListener("beforeunload",()=>{o.cleanup()}),setInterval(()=>o.cleanObservables(r),n)};const O=new Map;let S=null;const E={createTextNode:()=>(S||(S=document.createTextNode("")),S.cloneNode()),createObservableNode(e,t){const n=E.createTextNode();return t.subscribe(e=>n.nodeValue=e),n.nodeValue=t.val(),e&&e.appendChild(n),n},createHydratableNode(e,t){const n=E.createTextNode();return t.$hydrate(n),n},createStaticTextNode(e,t){let n=E.createTextNode();return n.nodeValue=t,e&&e.appendChild(n),n},createElement(e){if(e){if(O.has(e))return O.get(e).cloneNode();const t=document.createElement(e);return O.set(e,t),t.cloneNode()}return new b("Fragment")},processChildren(e,t){if(null===e)return;const n=Array.isArray(e)?e:[e];a.emit("BeforeProcessChildren",t);for(let e=0,r=n.length;e<r;e++){let r=this.getChild(n[e]);null!==r&&t.appendChild(r)}a.emit("AfterProcessChildren",t)},getChild(e){if(null===e)return null;if(m.isString(e)&&(e=e.resolveObservableTemplate?e.resolveObservableTemplate():e,m.isString(e)))return E.createStaticTextNode(null,e);if(m.isElement(e))return e;if(m.isObservable(e))return E.createObservableNode(null,e);if(m.isNDElement(e))return e.$element??e.$build?.()??null;if(m.isArray(e)){const t=document.createDocumentFragment();for(let n=0,r=e.length;n<r;n++)t.appendChild(this.getChild(e[n]));return t}return m.isFunction(e)?(a.emit("BeforeProcessComponent",e),this.getChild(e())):e?.$hydrate?E.createHydratableNode(null,e):E.createStaticTextNode(null,e)},processAttributes(e,t){m.isFragment(e)||t&&function(e,t){if(m.validateAttributes(t),!m.isObject(t))throw new s("Attributes must be an object");for(let n in t){const r=n.toLowerCase();let o=t[r];if(m.isString(o)){if(o=o.resolveObservableTemplate?o.resolveObservableTemplate():o,m.isString(o)){e.setAttribute(r,o);continue}const t=o.filter(e=>m.isObservable(e));o=v.computed(()=>o.map(e=>m.isObservable(e)?e.val():e).join(" ")||" ",t)}"class"===r&&m.isJson(o)?y(e,o):"style"===r&&m.isJson(o)?w(e,o):g.includes(r)?$(e,r,o):m.isObservable(o)?C(e,r,o):e.setAttribute(r,o)}}(e,t)},setup:(e,t,n)=>(a.emit("Setup",e,t,n),e)};Object.defineProperty(HTMLElement.prototype,"nd",{configurable:!0,get(){return this.$nd||(this.$nd=new f(this),this.$nd.nd=this.$nd),this.$nd}});let A=e=>e;t.ArgTypes={},t.ArgTypes={string:()=>!0,number:()=>!0,boolean:()=>!0,observable:()=>!0,element:()=>!0,function:()=>!0,object:()=>!0,objectNotNull:()=>!0,children:()=>!0,attributes:()=>!0,optional:()=>!0,oneOf:()=>!0};const k=function(e,t=null){if(!m.isJson(e)||e?.$hydrate){const n=t;t=e,e=n}return{props:e,children:t}},I=function(e){return m.isObservable(e)?E.createObservableNode(null,e):E.createStaticTextNode(null,e)};function x(e,t){return(n,r=null)=>function(e,t,n=null,r){const{props:o,children:s=null}=k(t,n),i=E.createElement(e),a="function"==typeof r?r(i):i;return E.processAttributes(a,o),E.processChildren(s,a),E.setup(a,o,r)}(e.toLowerCase(),n,r,t)}const N=new WeakMap;function T(e){let t=null;const n=(e,t)=>{const r=N.get(e);if(e instanceof Text)return r?.value?r.value(t):e.cloneNode(!0);const o=e.cloneNode();((e,t,n)=>{if(!t)return null;const r={};if(t.attributes)for(const e in t.attributes)r[e]=t.attributes[e](...n);if(t.classes){r.class={};for(const e in t.classes)r.class[e]=t.classes[e](...n)}if(t.styles){r.style={};for(const e in t.styles)r.style[e]=t.styles[e](...n)}Object.keys(r)&&E.processAttributes(e,r)})(o,r,t),function(e,t,n){if(!t?.attaches)return null;for(const r in t.attaches)e.nd[r](function(...e){t.attaches[r].call(this,...e,...n)})}(o,r,t);for(let r=0,s=e.childNodes.length;r<s;r++){const s=e.childNodes[r],i=n(s,t);o.appendChild(i)}return o};this.clone=r=>(t||(t=e(this)),n(t,r));const r=(e,t)=>({$hydrate:function(n,r){N.has(n)||N.set(n,{});const o=N.get(n);"value"!==t?(o[t]=o[t]||{},o[t][r]=e):o.value=e}});this.style=e=>r(e,"styles"),this.class=e=>r(e,"classes"),this.value=e=>r(function(t){return I(e(...t))},"value"),this.attr=e=>r(e,"attributes"),this.attach=e=>r(e,"attaches")}Function.prototype.args=function(...e){return this},Function.prototype.cached=function(...e){let t=null,n=function(){return t};return()=>(t||(t=this.apply(this,e),t.cloneNode?n=function(){return t.cloneNode(!0)}:t.$element&&(n=function(){return new f(t.$element.cloneNode(!0))})),n())},Function.prototype.errorBoundary=function(e){return(...t)=>{try{return this.apply(this,t)}catch(t){return e(t)}}},String.prototype.use=function(e){const t=this;return v.computed(()=>t.replace(/\$\{(.*?)}/g,(t,n)=>{const r=e[n];return m.isObservable(r)?r.val():r}),Object.values(e))},String.prototype.resolveObservableTemplate=function(){return m.containsObservableReference(this)?this.split(/(\{\{#ObItem::\([0-9]+\)\}\})/g).filter(Boolean).map(e=>{if(!m.containsObservableReference(e))return e;const[t,n]=e.match(/\{\{#ObItem::\(([0-9]+)\)\}\}/);return v.getById(n)}):this.valueOf()};const D=["push","pop","shift","unshift","reverse","sort","splice"];v.array=function(e){if(!Array.isArray(e))throw new s("Observable.array : target must be an array");const t=v(e);a.emit("CreateObservableArray",t),D.forEach(e=>{t[e]=function(...n){const r=t.val()[e](...n);return t.trigger({action:e,args:n,result:r}),r}}),t.clear=function(){return t.val().length=0,t.trigger({action:"clear"}),!0},t.merge=function(e){t.$value.push(...e),t.trigger({action:"merge",args:e})},t.populateAndRender=function(e,n){t.trigger({action:"populate",args:[t.val(),e,n]})},t.remove=function(e){const n=t.val().splice(e,1);return 0===n.length?[]:(t.trigger({action:"remove",args:[e],result:n[0]}),n)},t.swap=function(e,n){const r=t.val(),o=r.length;if(o<e||o<n)return!1;if(n<e){const t=e;e=n,n=t}const s=r[e],i=r[n];return r[e]=i,r[n]=s,t.trigger({action:"swap",args:[e,n],result:[s,i]}),!0},t.length=function(){return t.val().length};return["map","filter","reduce","some","every","find","findIndex","concat"].forEach(e=>{t[e]=function(...n){return t.val()[e](...n)}}),t},v.batch=function(e){const t=v(0),n=function(){if(m.isAsyncFunction(e))return e(...arguments).then(()=>{t.trigger()}).catch(e=>{throw e});e(...arguments),t.trigger()};return n.$observer=t,n},v.init=function(e){const t={};for(const n in e){const r=e[n];m.isJson(r)?t[n]=v.init(r):m.isArray(r)?t[n]=v.array(r):t[n]=v(r)}const n=function(){};return new Proxy(t,{get:(e,r)=>"__isProxy__"===r||("$value"===r?function(){const e={};for(const n in t){const r=t[n];m.isObservable(r)?e[n]=r.val():m.isProxy(r)?e[n]=r.$value:e[n]=r}return e}():"$clone"===r?n:void 0!==e[r]?e[r]:void 0),set(e,t,n){void 0!==e[t]&&e[t].set(n)}})},v.value=function(e){if(m.isObservable(e))return e.val();if(m.isProxy(e))return e.$value;if(m.isArray(e)){const t=[];for(let n=0,r=e.length;n<r;n++){const r=e[n];t.push(v.value(r))}return t}return e},v.update=function(e,t){for(const n in t){const r=e[n],o=t[n];if(m.isObservable(r)){if(m.isArray(o)){v.update(r,o);continue}r.set(o)}else m.isProxy(r)?v.update(r,o):e[n]=o}},v.object=v.init,v.json=v.init,v.computed=function(e,t=[]){const n=new u(e()),r=()=>n.set(e());if(a.emit("CreateObservableComputed",n,t),m.isFunction(t)){if(!m.isObservable(t.$observer))throw new s("Observable.computed : dependencies must be valid batch function");return t.$observer.subscribe(r),n}return t.forEach(e=>e.subscribe(r)),n};const F=function(){const e=new Map;return{use(t){const{observer:n,subscribers:r}=e.get(t),o=v(n.val()),s=n.subscribe(e=>o.set(e)),i=o.subscribe(e=>n.set(e));return o.destroy=()=>{s(),i(),o.cleanup()},r.add(o),o},follow(e){return this.use(e)},create(t,n){const r=v(n);return e.set(t,{observer:r,subscribers:new Set}),r},get(t){const n=e.get(t);return n?n.observer:null},getWithSubscribers:t=>e.get(t),delete(t){const n=e.get(t);n&&(n.observer.cleanup(),n.subscribers.forEach(e=>e.destroy()),n.observer.clear())}}}();const P=function(e,t,n=null){if(!m.isObservable(e))return r.warn("ShowIf","ShowIf : condition must be an Observable / "+n,e);const o=new b("Show if : "+(n||""));let s=null;const i=()=>s||(s=E.getChild(t),s);return e.val()&&o.appendChild(i()),e.subscribe(e=>{e?o.appendChild(i()):o.remove()}),o},R=function(e,t,n=!0){if(!m.isObservable(e))throw new s("Toggle : condition must be an Observable");const r=new b,o=new Map,i=function(e){if(n&&o.has(e))return o.get(e);let r=t[e];return r?(r=E.getChild(r),n&&o.set(e,r),r):null},a=e.val(),u=i(a);return u&&r.appendChild(u),e.subscribe(e=>{const t=i(e);r.remove(),t&&r.appendChild(t)}),r},L=function(e,t,n){if(!m.isObservable(e))throw new s("Toggle : condition must be an Observable");return R(e,{true:t,false:n})},B=x("div"),M=x("span"),q=x("label"),j=x("p"),_=j,V=x("strong"),H=x("h1"),z=x("h2"),W=x("h3"),U=x("h4"),J=x("h5"),K=x("h6"),Q=x("br"),Z=x("a"),G=x("pre"),X=x("code"),Y=x("blockquote"),ee=x("hr"),te=x("em"),ne=x("small"),re=x("mark"),oe=x("del"),se=x("ins"),ie=x("sub"),ae=x("sup"),ue=x("abbr"),le=x("cite"),ce=x("q"),he=x("dl"),de=x("dt"),pe=x("dd"),fe=x("form",function(e){return e.submit=function(t){return"function"==typeof t?(e.onSubmit(e=>{e.preventDefault(),t(e)}),e):(this.setAttribute("action",t),e)},e.multipartFormData=function(){return this.setAttribute("enctype","multipart/form-data"),e},e.post=function(t){return this.setAttribute("method","post"),this.setAttribute("action",t),e},e.get=function(e){this.setAttribute("method","get"),this.setAttribute("action",e)},e}),me=x("input"),be=x("textarea"),ge=be,ve=x("select"),ye=x("fieldset"),we=x("option"),$e=x("legend"),Ce=x("datalist"),Oe=x("output"),Se=x("progress"),Ee=x("meter"),Ae=x("button"),ke=x("main"),Ie=x("section"),xe=x("article"),Ne=x("aside"),Te=x("nav"),De=x("figure"),Fe=x("figcaption"),Pe=x("header"),Re=x("footer"),Le=x("img"),Be=function(e,t){return Le({src:e,...t})},Me=x("details"),qe=x("summary"),je=x("dialog"),_e=x("menu"),Ve=x("ol"),He=x("ul"),ze=x("li"),We=ze,Ue=Ve,Je=He,Ke=x("audio"),Qe=x("video"),Ze=x("source"),Ge=x("track"),Xe=x("canvas"),Ye=x("svg"),et=x("time"),tt=x("data"),nt=x("address"),rt=x("kbd"),ot=x("samp"),st=x("var"),it=x("wbr"),at=x("caption"),ut=x("table"),lt=x("thead"),ct=x("tfoot"),ht=x("tbody"),dt=x("tr"),pt=dt,ft=x("th"),mt=ft,bt=ft,gt=x("td"),vt=gt,yt=x("");var wt=Object.freeze({__proto__:null,Abbr:ue,Address:nt,Anchor:b,Article:xe,Aside:Ne,AsyncImg:function(e,t,n,r){const o=Be(t||e,n),i=new Image;return i.onload=()=>{m.isFunction(r)&&r(null,o),o.src=e},i.onerror=()=>{m.isFunction(r)&&r(new s("Image not found"))},m.isObservable(e)&&e.subscribe(e=>{i.src=e}),i.src=e,o},Audio:Ke,BaseImage:Le,Blockquote:Y,Br:Q,Button:Ae,Canvas:Xe,Caption:at,Checkbox:e=>me({type:"checkbox",...e}),Cite:le,Code:X,ColorInput:e=>me({type:"color",...e}),Data:tt,Datalist:Ce,DateInput:e=>me({type:"date",...e}),DateTimeInput:e=>me({type:"datetime-local",...e}),Dd:pe,Del:oe,Details:Me,Dialog:je,Div:B,Dl:he,Dt:de,Em:te,EmailInput:e=>me({type:"email",...e}),FieldSet:ye,FigCaption:Fe,Figure:De,FileInput:e=>me({type:"file",...e}),Footer:Re,ForEach:function(e,t,n){const o=new b("ForEach"),s=o.endElement();o.startElement();let i=new Map,a=null;const u=new Set,l=e=>{for(const[t,n]of i.entries()){if(u.has(t))continue;const r=n.child?.deref();e&&r&&e.removeChild(r),n.indexObserver?.cleanup(),n.child=null,n.indexObserver=null,i.delete(n.keyId),a&&a.delete(n.keyId)}},h=(e,o)=>{const s=c(e,o,n);if(i.has(s)){const e=i.get(s);if(e.indexObserver?.set(o),e.isNew=!1,e.child?.deref())return s;i.delete(s)}try{const n=t.length>=2?v(o):null;let r=E.getChild(t(e,n));i.set(s,{keyId:s,isNew:!0,child:new WeakRef(r),indexObserver:n})}catch(e){throw r.error("ForEach",`Error creating element for key ${s}`,e),e}return s},d=()=>{const t=s.parentNode;if(!t)return;const n=m.isObservable(e)?e.val():e;if(u.clear(),Array.isArray(n))for(let e=0,t=n.length;e<t;e++){const t=h(n[e],e);u.add(t)}else for(const e in n){const t=h(n[e],e);u.add(t)}if(0===u.size)return o.removeChildren(),l(),void a?.clear();l(t),a&&0!==a.size?(()=>{let e=document.createDocumentFragment();const t=Array.from(u);Array.from(a);for(const n in t){const r=t[n],o=i.get(r);if(!o)continue;const s=o.child.deref();s&&e.appendChild(s)}o.replaceContent(e)})():(e=>{const t=document.createDocumentFragment();for(const e of u){const n=i.get(e);if(!n)continue;const r=n.child?.deref();r&&t.appendChild(r)}e.insertBefore(t,s)})(t),a?.clear(),a=new Set([...u])};return d(),m.isObservable(e)&&e.subscribe(d),o},ForEachArray:function(e,t,n,r={}){const o=new b("ForEach Array"),s=o.endElement(),i=o.startElement();let a=new Map,u=0;const l=t.length>=2,h=new WeakMap,d=()=>{o.removeChildren(),y(),u=0},p=(e,t)=>h.has(e)?h.get(e):c(e,t,n),f=e=>$(p(e)),g=(e,t=!0)=>{if(!e)return;const n=e.child;e.indexObserver?.deref()?.cleanup(),e.child=null,e.indexObserver=null,t&&(n?.remove(),a.delete(e.keyId))},y=()=>{for(const[e,t]of a.entries())g(t,!1);a.clear()},w=(e,n)=>{const r=p(e,n);if(a.has(r)){const e=a.get(r);e.indexObserver?.deref()?.set(n);const t=e.child;if(t)return t;a.delete(r)}const o=l?v(n):null;let s=E.getChild(t(e,o));return a.set(r,{keyId:r,child:s,indexObserver:o?new WeakRef(o):null}),h.set(e,r),s},$=function(e){const t=a.get(e);if(!t)return null;const n=t.child;return n||(g(t,!1),null)},C=function(e,t){const n=a.get(e);if(!n)return null;const r=n.child;if(!r)return null;t?t.appendChild(r):r.remove()},O={toFragment(e,t=0){const n=document.createDocumentFragment();for(let t=0,r=e.length;t<r;t++)n.append(w(e[t],u)),u++;return n},add(e,t=0){const n=O.toFragment(e);setTimeout(()=>{o.appendElement(n)},t)},replace(e){d(),O.add(e)},reOrder(e){let t=null;const n=document.createDocumentFragment();for(const r of e)t=f(r),t&&n.appendChild(t);t=null,o.appendElement(n,s)},removeOne(e,t){((e,t=!0)=>{g(a.get(e),t)})(p(e,t),!0)},clear:d,merge(e){O.add(e,0)},push(e){let t=0;r.pushDelay&&(t=r.pushDelay(e)??0),O.add(e,t)},populate([e,t,n]){const r=document.createDocumentFragment();for(let o=0;o<t;o++){const t=n(o);e.push(t),r.append(w(t,o)),u++}o.appendChild(r),r.replaceChildren()},unshift(e){o.insertBefore(O.toFragment(e),i.nextSibling)},splice(e,t){const[n,r,...i]=e;let a=null;const u=document.createDocumentFragment();if(t.length>0){let e=p(t[0],n);if(1===t.length)C(e,u);else if(t.length>1){const r=$(e);a=r?.previousSibling;for(let e=0;e<t.length;e++){const r=p(t[e],n+e);C(r,u)}}}else a=s;u.replaceChildren(),i&&i.length&&a&&o.insertBefore(O.toFragment(i),a.nextSibling)},reverse(e,t){O.reOrder(t)},sort(e,t){O.reOrder(t)},remove(e,t){O.removeOne(t)},pop(e,t){O.removeOne(t)},shift(e,t){O.removeOne(t)},swap(e,t){const n=s.parentNode;let r=f(t[0]),o=f(t[1]);if(!r||!o)return;const i=o.nextSibling;n.insertBefore(o,r),n.insertBefore(r,i),r=null,o=null}},S=(e,t,n)=>{if("clear"!==n.action&&e.length){if(n?.action)O[n.action]&&O[n.action](n.args,n.result);else{if(0===u)return void O.add(e);O.replace(e)}((e,t=0)=>{if(!l)return;let n=t;for(let r=t,o=e?.length;r<o;r++){const t=a.get(p(e[r],r));t&&(t.indexObserver?.deref()?.set(n),n++)}})(e,0)}else{if(0===u)return;d()}};return S(e.val(),0,{action:null}),m.isObservable(e)&&e.subscribe(S),o},Form:fe,Fragment:yt,H1:H,H2:z,H3:W,H4:U,H5:J,H6:K,Header:Pe,HiddenInput:e=>me({type:"hidden",...e}),HideIf:function(e,t,n){const r=v(!e.val());return e.subscribe(e=>r.set(!e)),P(r,t,n)},HideIfNot:function(e,t,n){return P(e,t,n)},Hr:ee,Img:Be,Input:me,Ins:se,Kbd:rt,Label:q,LazyImg:function(e,t){return Be(e,{...t,loading:"lazy"})},Legend:$e,Li:We,Link:Z,ListItem:ze,Main:ke,Mark:re,Match:R,Menu:_e,Meter:Ee,MonthInput:e=>me({type:"month",...e}),NativeDocumentFragment:b,Nav:Te,NumberInput:e=>me({type:"number",...e}),Ol:Ue,Option:we,OrderedList:Ve,Output:Oe,P:j,Paragraph:_,PasswordInput:e=>me({type:"password",...e}),Pre:G,Progress:Se,Quote:ce,Radio:e=>me({type:"radio",...e}),RangeInput:e=>me({type:"range",...e}),ReadonlyInput:e=>me({readonly:!0,...e}),Samp:ot,SearchInput:e=>me({type:"search",...e}),Section:Ie,Select:ve,ShowIf:P,SimpleButton:(e,t)=>Ae(e,{type:"button",...t}),Small:ne,Source:Ze,Span:M,Strong:V,Sub:ie,SubmitButton:(e,t)=>Ae(e,{type:"submit",...t}),Summary:qe,Sup:ae,Svg:Ye,Switch:L,TBody:ht,TBodyCell:vt,TFoot:ct,TFootCell:bt,THead:lt,THeadCell:mt,TRow:pt,Table:ut,Td:gt,TelInput:e=>me({type:"tel",...e}),TextArea:be,TextInput:ge,Th:ft,Time:et,TimeInput:e=>me({type:"time",...e}),Tr:dt,Track:Ge,Ul:Je,UnorderedList:He,UrlInput:e=>me({type:"url",...e}),Var:st,Video:Qe,Wbr:it,WeekInput:e=>me({type:"week",...e}),When:function(e){if(!m.isObservable(e))throw new s("When : condition must be an Observable");let t=null,n=null;return{show(e){return t=e,this},otherwise:r=>(n=r,L(e,t,n))}}});const $t={};function Ct(e,t,n={}){e="/"+h(e,"/");let r=null,o=n.name||null;const s=n.middlewares||[],i=n.shouldRebuild||!1,a=n.with||{},u={},l=[],c=e=>{if(!e)return null;const[t,n]=e.split(":");let r=a[t];return!r&&n&&(r=$t[n]),r||(r="[^/]+"),r=r.replace("(","(?:"),{name:t,pattern:`(${r})`}},d=()=>{if(r)return r;const t=e.replace(/\{(.*?)}/gi,(e,t)=>{const n=c(t);return n&&n.pattern?(u[n.name]=n.pattern,l.push(n.name),n.pattern):e});return r=new RegExp("^"+t+"$"),r};this.name=()=>o,this.component=()=>t,this.middlewares=()=>s,this.shouldRebuild=()=>i,this.path=()=>e,this.match=function(e){e="/"+h(e,"/");if(!d().exec(e))return!1;const t={};return d().exec(e).forEach((e,n)=>{if(n<1)return;const r=l[n-1];t[r]=e}),t},this.url=function(t){const n=e.replace(/\{(.*?)}/gi,(e,n)=>{const r=c(n);if(t.params&&t.params[r.name])return t.params[r.name];throw new Error(`Missing parameter '${r.name}'`)}),r="object"==typeof t.query?new URLSearchParams(t.query).toString():null;return(t.basePath?t.basePath:"")+(r?`${n}?${r}`:n)}}class Ot extends Error{constructor(e,t){super(e),this.context=t}}const St=(e,t)=>{const n=[];return e.forEach(e=>{n.push(h(e.suffix,"/"))}),n.push(h(t,"/")),n.join("/")},Et=(e,t)=>{const n=[];return e.forEach(e=>{e.options.middlewares&&n.push(...e.options.middlewares)}),t&&n.push(...t),n},At=(e,t)=>{const n=[];return e.forEach(e=>{e.options?.name&&n.push(e.options.name)}),t&&n.push(t),n.join(".")};function kt(){const e=[];let t=0;const n=n=>{const o=t+n;if(!e[o])return;t=o;const{route:s,params:i,query:a,path:u}=e[o];r(u)},r=e=>{window.location.replace(`${window.location.pathname}${window.location.search}#${e}`)},o=()=>window.location.hash.slice(1);this.push=function(n){const{route:s,params:i,query:a,path:u}=this.resolve(n);u!==o()&&(e.splice(t+1),e.push({route:s,params:i,query:a,path:u}),t++,r(u))},this.replace=function(n){const{route:r,params:s,query:i,path:a}=this.resolve(n);a!==o()&&(e[t]={route:r,params:s,query:i,path:a})},this.forward=function(){return t<e.length-1&&n(1)},this.back=function(){return t>0&&n(-1)},this.init=function(n){window.addEventListener("hashchange",()=>{const{route:e,params:t,query:n,path:r}=this.resolve(o());this.handleRouteChange(e,t,n,r)});const{route:r,params:s,query:i,path:a}=this.resolve(n||o());e.push({route:r,params:s,query:i,path:a}),t=0,this.handleRouteChange(r,s,i,a)}}function It(){this.push=function(e){try{const{route:t,path:n,params:r,query:o}=this.resolve(e);if(window.history.state&&window.history.state.path===n)return;window.history.pushState({name:t.name(),params:r,path:n},t.name()||n,n),this.handleRouteChange(t,r,o,n)}catch(e){r.error("HistoryRouter","Error in pushState",e)}},this.replace=function(e){const{route:t,path:n,params:o}=this.resolve(e);try{window.history.replaceState({name:t.name(),params:o,path:n},t.name()||n,n),this.handleRouteChange(t,o,{},n)}catch(e){r.error("HistoryRouter","Error in replaceState",e)}},this.forward=function(){window.history.forward()},this.back=function(){window.history.back()},this.init=function(e){window.addEventListener("popstate",e=>{try{if(!e.state||!e.state.path)return;const t=e.state.path,{route:n,params:r,query:o,path:s}=this.resolve(t);if(!n)return;this.handleRouteChange(n,r,o,s)}catch(e){r.error("HistoryRouter","Error in popstate event",e)}});const{route:t,params:n,query:o,path:s}=this.resolve(e||window.location.pathname+window.location.search);this.handleRouteChange(t,n,o,s)}}function xt(){const e=[];let t=0;const n=n=>{const r=t+n;if(!e[r])return;t=r;const{route:o,params:s,query:i,path:a}=e[r];this.handleRouteChange(o,s,i,a)};this.push=function(n){const{route:r,params:o,query:s,path:i}=this.resolve(n);e[t]&&e[t].path===i||(e.splice(t+1),e.push({route:r,params:o,query:s,path:i}),t++,this.handleRouteChange(r,o,s,i))},this.replace=function(n){const{route:r,params:o,query:s,path:i}=this.resolve(n);e[t]={route:r,params:o,query:s,path:i},this.handleRouteChange(r,o,s,i)},this.forward=function(){return t<e.length-1&&n(1)},this.back=function(){return t>0&&n(-1)},this.init=function(n){const r=n||window.location.pathname+window.location.search,{route:o,params:s,query:i,path:a}=this.resolve(r);e.push({route:o,params:s,query:i,path:a}),t=0,this.handleRouteChange(o,s,i,a)}}const Nt="default";function Tt(e={}){const t=[],n={},o=[],s=[],i={route:null,params:null,query:null,path:null,hash:null};if("hash"===e.mode)kt.apply(this,[]);else if("history"===e.mode)It.apply(this,[]);else{if("memory"!==e.mode)throw new Ot("Invalid router mode "+e.mode);xt.apply(this,[])}const a=function(e,t){for(const n of s)try{n(e),t&&t(e)}catch(e){r.warn("Route Listener","Error in listener:",e)}};this.routes=()=>[...t],this.currentState=()=>({...i}),this.add=function(e,r,s){const i=new Ct(St(o,e),r,{...s,middlewares:Et(o,s?.middlewares||[]),name:s?.name?At(o,s.name):null});return t.push(i),i.name()&&(n[i.name()]=i),this},this.group=function(e,t,n){if(!m.isFunction(n))throw new Ot("Callback must be a function");return o.push({suffix:e,options:t}),n(),o.pop(),this},this.generateUrl=function(e,t={},r={}){const o=n[e];if(!o)throw new Ot(`Route not found for name: ${e}`);return o.url({params:t,query:r})},this.resolve=function(e){if(m.isJson(e)){const t=n[e.name];if(!t)throw new Ot(`Route not found for name: ${e.name}`);return{route:t,params:e.params,query:e.query,path:t.url({...e})}}const[r,o]=e.split("?"),s="/"+h(r,"/");let i,a=null;for(const e of t)if(i=e.match(s),i){a=e;break}if(!a)throw new Ot(`Route not found for url: ${r}`);const u={};if(o){const e=new URLSearchParams(o).entries();for(const[t,n]of e)u[t]=n}return{route:a,params:i,query:u,path:e}},this.subscribe=function(e){if(!m.isFunction(e))throw new Ot("Listener must be a function");return s.push(e),()=>{s.splice(s.indexOf(e),1)}},this.handleRouteChange=function(e,t,n,r){i.route=e,i.params=t,i.query=n,i.path=r;const o=[...e.middlewares(),a];let s=0;const u={...i},l=e=>{if(s++,!(s>=o.length))return o[s](e||u,l)};return o[s](u,l)}}function Dt(e,t){const{to:n,href:r,...o}=e,s=n||r;if(m.isString(s)){const e=Tt.get();return Z({...o,href:s},t).nd.onPreventClick(()=>{e.push(s)})}const i=s.router||Nt,a=Tt.get(i);if(!a)throw new Ot('Router not found "'+i+'" for link "'+s.name+'"');const u=a.generateUrl(s.name,s.params,s.query);return Z({...o,href:u},t).nd.onPreventClick(()=>{a.push(u)})}Tt.routers={},Tt.create=function(t,n){if(!m.isFunction(n))throw r.error("Router","Callback must be a function",e),new Ot("Callback must be a function");const o=new Tt(t);return Tt.routers[t.name||Nt]=o,n(o),o.init(t.entry),o.mount=function(e){if(m.isString(e)){const t=document.querySelector(e);if(!t)throw new Ot(`Container not found for selector: ${e}`);e=t}else if(!m.isElement(e))throw new Ot("Container must be a string or an Element");return function(e,t){const n=new Map,r=function(e){t.innerHTML="",t.appendChild(e)},o=function(e){if(!e.route)return;const{route:t,params:o,query:s,path:i}=e;if(n.has(i)){const e=n.get(i);return void r(e)}const a=t.component()({params:o,query:s});n.set(i,a),r(a)};return e.subscribe(o),o(e.currentState()),t}(o,e)},o},Tt.get=function(e){const t=Tt.routers[e||Nt];if(!t)throw new Ot(`Router not found for name: ${e}`);return t},Tt.push=function(e,t=null){return Tt.get(t).push(e)},Tt.replace=function(e,t=null){return Tt.get(t).replace(e)},Tt.forward=function(e=null){return Tt.get(e).forward()},Tt.back=function(e=null){return Tt.get(e).back()},Dt.blank=function(e,t){return Z({...e,target:"_blank"},t)};var Ft=Object.freeze({__proto__:null,Link:Dt,RouteParamPatterns:$t,Router:Tt});return t.ElementCreator=E,t.HtmlElementWrapper=x,t.NDElement=f,t.Observable=v,t.Store=F,t.TemplateCloner=T,t.classPropertyAccumulator=function(e=[]){let t=m.isString(e)?e.split(" ").filter(Boolean):e;const n=m.isArray(t);return{add(e,r=!0){n?t.push(e):t[e]=r},value:()=>n?t.join(" "):{...t}}},t.createTextNode=I,t.cssPropertyAccumulator=function(e={}){let t=m.isString(e)?e.split(";").filter(Boolean):e;const n=m.isArray(t);return{add(e,r){n?t.push(e+" : "+r):t[e]=r},value:()=>n?t.join(";").concat(";"):{...t}}},t.elements=wt,t.normalizeComponentArgs=k,t.router=Ft,t.useCache=function(e){let t=null;return function(...n){return t||(t=new T(e)),t.clone(n)}},t.withValidation=A,t}({});
package/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export * from './types/plugins-manager';
5
5
  export * from './types/property-accumulator';
6
6
  export * from './types/validator';
7
7
  export * from './types/args-types';
8
+ export * from './types/template-cloner';
8
9
 
9
10
  // Main static exports
10
11
  import { ObservableStatic } from './types/observable';
package/index.js CHANGED
@@ -1,6 +1,7 @@
1
- export { default as HtmlElementWrapper } from './src/wrappers/HtmlElementWrapper'
1
+ export { default as HtmlElementWrapper, createTextNode } from './src/wrappers/HtmlElementWrapper'
2
2
  export { ElementCreator } from './src/wrappers/ElementCreator'
3
3
  export { NDElement } from './src/wrappers/NDElement'
4
+ export { TemplateCloner, useCache } from './src/wrappers/TemplateCloner'
4
5
 
5
6
  import './src/utils/prototypes.js';
6
7
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "native-document",
3
- "version": "1.0.32",
3
+ "version": "1.0.34",
4
4
  "main": "index.js",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -3,6 +3,7 @@ import MemoryManager from "./MemoryManager";
3
3
  import NativeDocumentError from "../errors/NativeDocumentError";
4
4
  import ObservableChecker from "./ObservableChecker";
5
5
  import PluginsManager from "../utils/plugins-manager";
6
+ import Validator from "../utils/validator";
6
7
 
7
8
  /**
8
9
  *
@@ -57,14 +58,29 @@ ObservableItem.prototype.triggerWatchers = function() {
57
58
  const $currentValue = this.$currentValue;
58
59
 
59
60
  if($watchers.has($currentValue)) {
60
- $watchers.get($currentValue).forEach(callback => {
61
- callback.set ? callback.set(true) : callback(true);
62
- });
61
+ const $currentValueCallbacks = $watchers.get($currentValue);
62
+ if(typeof $currentValueCallbacks === "function") {
63
+ $currentValueCallbacks(true);
64
+ } else if ($currentValueCallbacks.set) {
65
+ $currentValueCallbacks.set(true)
66
+ }
67
+ else {
68
+ $currentValueCallbacks.forEach(callback => {
69
+ callback.set ? callback.set(true) : callback(true);
70
+ });
71
+ }
63
72
  }
64
73
  if($watchers.has($previousValue)) {
65
- $watchers.get($previousValue).forEach(callback => {
66
- callback.set ? callback.set(false) : callback(false);
67
- });
74
+ const $previousValueCallbacks = $watchers.get($previousValue);
75
+ if(typeof $previousValueCallbacks === "function") {
76
+ $previousValueCallbacks(false);
77
+ } else if($previousValueCallbacks.set) {
78
+ $previousValueCallbacks.set(false)
79
+ } else {
80
+ $previousValueCallbacks.forEach(callback => {
81
+ callback.set ? callback.set(false) : callback(false);
82
+ });
83
+ }
68
84
  }
69
85
  };
70
86
 
@@ -116,7 +132,9 @@ ObservableItem.prototype.disconnectAll = function() {
116
132
  this.$currentValue = null;
117
133
  if(this.$watchers) {
118
134
  for (const [_, watchValueList] of this.$watchers) {
119
- watchValueList.splice(0);
135
+ if(Validator.isArray(watchValueList)) {
136
+ watchValueList.splice(0);
137
+ }
120
138
  }
121
139
  }
122
140
  this.$watchers?.clear();
@@ -162,17 +180,25 @@ ObservableItem.prototype.on = function(value, callback) {
162
180
  this.$watchers = this.$watchers ?? new Map();
163
181
 
164
182
  let watchValueList = this.$watchers.get(value);
183
+
165
184
  if(!watchValueList) {
166
- watchValueList = [];
185
+ this.$watchers.set(value, callback);
186
+ } else if(!Validator.isArray(watchValueList)) {
187
+ watchValueList = [watchValueList];
167
188
  this.$watchers.set(value, watchValueList);
189
+ return;
190
+ } else {
191
+ watchValueList.push(callback);
168
192
  }
169
193
 
170
- watchValueList.push(callback);
171
194
  this.assocTrigger();
172
195
  return () => {
173
196
  const index = watchValueList.indexOf(callback);
174
197
  watchValueList?.splice(index, 1);
175
- if(watchValueList.size === 0) {
198
+ if(watchValueList.size === 1) {
199
+ this.$watchers.set(value, watchValueList[0]);
200
+ }
201
+ else if(watchValueList.size === 0) {
176
202
  this.$watchers?.delete(value);
177
203
  watchValueList = null;
178
204
  }
@@ -157,7 +157,6 @@ export function ForEachArray(data, callback, key, configs = {}) {
157
157
  },
158
158
  removeOne(element, index) {
159
159
  removeCacheItemByKey(getItemKey(element, index), true);
160
- child = null;
161
160
  },
162
161
  clear,
163
162
  merge(items) {
@@ -128,7 +128,7 @@ if(process.env.NODE_ENV === 'production') {
128
128
  }
129
129
 
130
130
  export const normalizeComponentArgs = function(props, children = null) {
131
- if(!Validator.isJson(props)) {
131
+ if(!Validator.isJson(props) || props?.$hydrate) {
132
132
  const temp = children;
133
133
  children = props;
134
134
  props = temp;
@@ -23,6 +23,10 @@ function bindClassAttribute(element, data) {
23
23
  });
24
24
  continue;
25
25
  }
26
+ if(value.$hydrate) {
27
+ value.$hydrate(element, className);
28
+ continue;
29
+ }
26
30
  element.classList.toggle(className, value)
27
31
  }
28
32
  }
@@ -26,6 +26,17 @@ export const ElementCreator = {
26
26
  parent && parent.appendChild(text);
27
27
  return text;
28
28
  },
29
+ /**
30
+ *
31
+ * @param {HTMLElement|DocumentFragment} parent
32
+ * @param {{$hydrate: Function}} item
33
+ * @returns {Text}
34
+ */
35
+ createHydratableNode(parent, item) {
36
+ const text = ElementCreator.createTextNode();
37
+ item.$hydrate(text);
38
+ return text;
39
+ },
29
40
 
30
41
  /**
31
42
  *
@@ -104,6 +115,9 @@ export const ElementCreator = {
104
115
  PluginsManager.emit('BeforeProcessComponent', child);
105
116
  return this.getChild(child());
106
117
  }
118
+ if(child?.$hydrate) {
119
+ return ElementCreator.createHydratableNode(null, child);
120
+ }
107
121
  return ElementCreator.createStaticTextNode(null, child);
108
122
  },
109
123
  /**
@@ -91,4 +91,9 @@ NDElement.prototype.htmlElement = function() {
91
91
  return this.$element;
92
92
  };
93
93
 
94
- NDElement.prototype.node = NDElement.prototype.htmlElement;
94
+ NDElement.prototype.node = NDElement.prototype.htmlElement;
95
+
96
+ NDElement.prototype.attach = function(methodName, bindingHydrator) {
97
+ bindingHydrator.$hydrate(this.$element, methodName);
98
+ return this.$element;
99
+ };
@@ -0,0 +1,129 @@
1
+ import {ElementCreator} from "./ElementCreator";
2
+ import {createTextNode} from "./HtmlElementWrapper";
3
+
4
+ const cloneBindingsDataCache = new WeakMap();
5
+
6
+
7
+ const bindAttributes = (node, bindDingData, data) => {
8
+ if(!bindDingData) {
9
+ return null;
10
+ }
11
+ const attributes = { };
12
+ if(bindDingData.attributes) {
13
+ for (const attr in bindDingData.attributes) {
14
+ attributes[attr] = bindDingData.attributes[attr](...data);
15
+ }
16
+ }
17
+
18
+ if(bindDingData.classes) {
19
+ attributes.class = {};
20
+ for (const className in bindDingData.classes) {
21
+ attributes.class[className] = bindDingData.classes[className](...data);
22
+ }
23
+ }
24
+
25
+ if(bindDingData.styles) {
26
+ attributes.style = {};
27
+ for (const property in bindDingData.styles) {
28
+ attributes.style[property] = bindDingData.styles[property](...data);
29
+ }
30
+ }
31
+
32
+ if(Object.keys(attributes)) {
33
+ ElementCreator.processAttributes(node, attributes);
34
+ return attributes;
35
+ }
36
+
37
+ return null;
38
+ };
39
+
40
+
41
+ const bindAttachesMethods = function(node, bindDingData, data) {
42
+ if(!bindDingData?.attaches) {
43
+ return null;
44
+ }
45
+ for(const methodName in bindDingData.attaches) {
46
+ node.nd[methodName](function(...args) {
47
+ bindDingData.attaches[methodName].call(this, ...[...args, ...data]);
48
+ });
49
+ }
50
+ }
51
+
52
+ export function TemplateCloner($fn) {
53
+ let $node = null;
54
+
55
+ const clone = (node, data) => {
56
+ const bindDingData = cloneBindingsDataCache.get(node);
57
+ if(node instanceof Text) {
58
+ if(bindDingData?.value) {
59
+ return bindDingData.value(data);
60
+ }
61
+ return node.cloneNode(true);
62
+ }
63
+ const nodeCloned = node.cloneNode();
64
+ bindAttributes(nodeCloned, bindDingData, data);
65
+ bindAttachesMethods(nodeCloned, bindDingData, data);
66
+
67
+ for(let i = 0, length = node.childNodes.length; i < length; i++) {
68
+ const childNode = node.childNodes[i];
69
+ const childNodeCloned = clone(childNode, data);
70
+ nodeCloned.appendChild(childNodeCloned);
71
+ }
72
+ return nodeCloned;
73
+ };
74
+
75
+ this.clone = (data) => {
76
+ if(!$node) {
77
+ $node = $fn(this);
78
+ }
79
+ return clone($node, data);
80
+ };
81
+
82
+ const createBinding = (hydrateFunction, target) => {
83
+ return {
84
+ $hydrate : function(element, property) {
85
+ if(!cloneBindingsDataCache.has(element)) {
86
+ // { classes, styles, attributes, value, attaches }
87
+ cloneBindingsDataCache.set(element, {});
88
+ }
89
+ const hydrationState = cloneBindingsDataCache.get(element);
90
+ if(target === 'value') {
91
+ hydrationState.value = hydrateFunction;
92
+ return;
93
+ }
94
+ hydrationState[target] = hydrationState[target] || {};
95
+ hydrationState[target][property] = hydrateFunction;
96
+ }
97
+ }
98
+ };
99
+
100
+ this.style = (fn) => {
101
+ return createBinding(fn, 'styles');
102
+ };
103
+ this.class = (fn) => {
104
+ return createBinding(fn, 'classes');
105
+ };
106
+ this.value = (fn) => {
107
+ return createBinding(function(data) {
108
+ return createTextNode(fn(...data));
109
+ }, 'value');
110
+ };
111
+ this.attr = (fn) => {
112
+ return createBinding(fn, 'attributes');
113
+ };
114
+ this.attach = (fn) => {
115
+ return createBinding(fn, 'attaches');
116
+ };
117
+ }
118
+
119
+ export function useCache(fn) {
120
+ let $cache = null;
121
+
122
+ return function(...args) {
123
+ if(!$cache) {
124
+ $cache = new TemplateCloner(fn);
125
+ }
126
+
127
+ return $cache.clone(args);
128
+ };
129
+ }
@@ -1,5 +1,6 @@
1
1
  // DOM elements and components type definitions - Version complète
2
2
  import { ObservableItem } from './observable';
3
+ import {BindingHydrator} from "./template-cloner";
3
4
 
4
5
  export interface NDElement {
5
6
  readonly __$isNDElement: true;
@@ -16,6 +17,7 @@ export interface NDElement {
16
17
 
17
18
  htmlElement(): HTMLElement;
18
19
  node(): HTMLElement;
20
+ attach(methodeName: string, bindingHydrator: BindingHydrator): HTMLElement;
19
21
 
20
22
  // Mouse Events
21
23
  onClick(callback: (event: MouseEvent) => void): this;
@@ -0,0 +1,36 @@
1
+
2
+ interface BindingData {
3
+ attributes?: Record<string, (...data: any[]) => any>;
4
+ classes?: Record<string, (...data: any[]) => any>;
5
+ styles?: Record<string, (...data: any[]) => any>;
6
+ value?: (...data: any[]) => any;
7
+ events?: Record<string, (this: Element, event: Event, ...data: any[]) => void>;
8
+ }
9
+
10
+ interface ProcessedAttributes {
11
+ class?: Record<string, any>;
12
+ style?: Record<string, any>;
13
+ [key: string]: any;
14
+ }
15
+
16
+ export interface BindingHydrator {
17
+ $hydrate: (element: Element | Text, property?: string) => void;
18
+ }
19
+
20
+ export type TemplateBuilder = (templateCloner: TemplateCloner) => Node;
21
+
22
+ type CachedTemplateFunction = (...args: any[]) => Node;
23
+
24
+ export declare class TemplateCloner {
25
+ constructor($fn: TemplateBuilder);
26
+
27
+ clone(data: any[]): Node;
28
+
29
+ style(fn: (...data: any[]) => any): BindingHydrator;
30
+ class(fn: (...data: any[]) => any): BindingHydrator;
31
+ value(fn: (...data: any[]) => any): BindingHydrator;
32
+ attr(fn: (...data: any[]) => any): BindingHydrator;
33
+ event(fn: (event: Event, ...data: any[]) => void): BindingHydrator;
34
+ }
35
+
36
+ export declare function useCache(fn: TemplateBuilder): CachedTemplateFunction;