diff --git a/dist/jails.js b/dist/jails.js index 0751acf..4ed1f66 100644 --- a/dist/jails.js +++ b/dist/jails.js @@ -1,2 +1,2 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jails={})}(this,(function(e){"use strict";const t=new DOMParser;const n=(e,t,n)=>{var r,o;null==(r=t.parentNode)||r.insertBefore(e,t),null==(o=t.parentNode)||o.insertBefore(n,t.nextSibling)},r=document.createElement("textarea"),o=e=>(r.innerHTML=e,r.value),l=e=>requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,1e3/60),a=e=>JSON.parse(JSON.stringify(e)),i=e=>{var t,n,r,o=e.attributes;if(o)for(t=o.length-1;t>=0;t-=1)"function"==typeof e[r=o[t].name]&&(e[r]=null);if(o=e.childNodes)for(n=o.length,t=0;t{try{return e()}catch(n){return t||""}},c={tags:["${","}"]};function u(e){const r=function(e,r){const o=new RegExp(`\\${r.tags[0]}(.+?)\\${r.tags[1]}`,"g"),l=t.parseFromString(e.replace(/<\/?template[^>]*>/g,""),"text/html");return l.querySelectorAll("[html-for], [html-if], [html-inner], [html-class], [html-model]").forEach((e=>{const t=e.getAttribute("html-foreach"),r=e.getAttribute("html-for"),o=e.getAttribute("html-if"),l=e.getAttribute("html-inner"),a=e.getAttribute("html-class"),i=r||t;if(i){const t=r?"html-for":"html-foreach",o=i.match(/(.*)\sin\s(.*)/)||"",l=o[1],a=o[2];e.removeAttribute(t),e.setAttribute("scope","");const s=document.createElement("script");s.dataset.scope="",s.type="text/html",s.text="%%_= $scope _%%",e.appendChild(s);const c=document.createTextNode(`%%_(function(){ var $index = 0; for(var $key in safe(function(){ return ${a} }) ){ var ${l} = ${a}[$key]; var $scope = JSON.stringify({ '${l}':${l}, $index: $index, $key:$key }); _%%`),u=document.createTextNode("%%_ $index++; } })() _%%");n(c,e,u)}if(o){e.removeAttribute("html-if");const t=document.createTextNode(`%%_ if ( safe(function(){ return ${o} }) ){ _%%`),r=document.createTextNode("%%_ } _%%");n(t,e,r)}l&&(e.removeAttribute("html-inner"),e.innerHTML=`%%_=${l}_%%`),a&&(e.removeAttribute("html-class"),e.className=(e.className+` %%_=${a}_%%`).trim())})),l.body.innerHTML.replace(o,"%%_=$1_%%").replace(/html-(allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|formnovalidate|inert|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected)=\"(.*?)\"/g,"%%_if(safe(function(){ return $2 })){_%%$1%%_}_%%").replace(/html-(.*?)=\"(.*?)\"/g,((e,t,n)=>"key"===t||"model"===t||"scope"==t?e:n?`${t}="%%_=safe(function(){ return ${n=n.replace(/^{|}$/g,"")} })_%%"`:e))}(e.outerHTML,c),l=JSON.stringify(r);return new Function("$element","safe",`\n\t\tvar $data = this;\n\t\twith( $data ){\n\t\t\tvar output=${l.replace(/%%_=(.+?)_%%/g,(function(e,t){return'"+safe(function(){return '+o(t)+';})+"'})).replace(/%%_(.+?)_%%/g,(function(e,t){return'";'+o(t)+'\noutput+="'}))};return output;\n\t\t}\n\t`)}const d=(e,t,n,r)=>{[].concat(e.matches&&e.matches(t)?e:[]).concat(Array.from(e.querySelectorAll(t))).reverse().forEach((e=>{e.querySelectorAll("template").forEach((e=>d(e.content,t,n,r))),f(e,n,r)}))},f=(e,t,n)=>{if(!e.getAttribute("tplid")){const r="xxxxxxxx".replace(/[xy]/g,(e=>{const t=8*Math.random()|0;return("x"==e?t:3&t|8).toString(8)}));e.setAttribute("tplid",r);const o=e.localName;if(o in n&&n[o].module.template){const l=n[o].module.template();l.constructor===Promise?(e.__template=l,l.then((n=>{e.innerHTML=n,t[r]=u(e)}))):e.innerHTML=l}t[r]=u(e)}},m={},h={},p=(e,t)=>{h[e]=Object.assign({},h[e],t),m[e]&&m[e].forEach((e=>e(t)))},b=(e,t)=>(m[e]=m[e]||[],m[e].push(t),e in h&&t(h[e]),()=>{m[e]=m[e].filter((e=>e!=t))}),g=function(){let e=new Set,t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:c,afterNodeAdded:c,beforeNodeMorphed:c,afterNodeMorphed:c,beforeNodeRemoved:c,afterNodeRemoved:c,beforeAttributeUpdated:c},head:{style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:c,afterHeadMorphed:c}};function n(e,t,r){if(r.head.block){let o=e.querySelector("head"),l=t.querySelector("head");if(o&&l){let a=s(l,o,r);return void Promise.all(a).then((function(){n(e,t,Object.assign(r,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===r.morphStyle)return l(t,e,r),e.children;if("outerHTML"===r.morphStyle||null==r.morphStyle){let n=function(e,t,n){let r;r=e.firstChild;let o=r,l=0;for(;r;){let e=p(r,t,n);e>l&&(o=r,l=e),r=r.nextSibling}return o}(t,e,r),l=null==n?void 0:n.previousSibling,a=null==n?void 0:n.nextSibling,i=o(e,n,r);return n?function(e,t,n){let r=[],o=[];for(;null!=e;)r.push(e),e=e.previousSibling;for(;r.length>0;){let e=r.pop();o.push(e),t.parentElement.insertBefore(e,t)}o.push(t);for(;null!=n;)r.push(n),o.push(n),n=n.nextSibling;for(;r.length>0;)t.parentElement.insertBefore(r.pop(),t.nextSibling);return o}(l,i,a):[]}throw"Do not understand how to morph style "+r.morphStyle}function r(e,t){return t.ignoreActiveValue&&e===document.activeElement}function o(e,t,n){if(!n.ignoreActive||e!==document.activeElement)return null==t?!1===n.callbacks.beforeNodeRemoved(e)?e:(e.remove(),n.callbacks.afterNodeRemoved(e),null):d(e,t)?(!1===n.callbacks.beforeNodeMorphed(e,t)||(e instanceof HTMLHeadElement&&n.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==n.head.style?s(t,e,n):(!function(e,t,n){let o=e.nodeType;if(1===o){const r=e.attributes,o=t.attributes;for(const e of r)a(e.name,t,"update",n)||t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(let l=o.length-1;0<=l;l--){const r=o[l];a(r.name,t,"remove",n)||(e.hasAttribute(r.name)||t.removeAttribute(r.name))}}8!==o&&3!==o||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);r(t,n)||function(e,t,n){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type){let r=e.value,o=t.value;i(e,t,"checked",n),i(e,t,"disabled",n),e.hasAttribute("value")?r!==o&&(a("value",t,"update",n)||(t.setAttribute("value",r),t.value=r)):a("value",t,"remove",n)||(t.value="",t.removeAttribute("value"))}else if(e instanceof HTMLOptionElement)i(e,t,"selected",n);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let r=e.value,o=t.value;if(a("value",t,"update",n))return;r!==o&&(t.value=r),t.firstChild&&t.firstChild.nodeValue!==r&&(t.firstChild.nodeValue=r)}}(e,t,n)}(t,e,n),r(e,n)||l(t,e,n))),n.callbacks.afterNodeMorphed(e,t)),e):!1===n.callbacks.beforeNodeRemoved(e)||!1===n.callbacks.beforeNodeAdded(t)?e:(e.parentElement.replaceChild(t,e),n.callbacks.afterNodeAdded(t),n.callbacks.afterNodeRemoved(e),t)}function l(e,t,n){let r,l=e.firstChild,a=t.firstChild;for(;l;){if(r=l,l=r.nextSibling,null==a){if(!1===n.callbacks.beforeNodeAdded(r))return;t.appendChild(r),n.callbacks.afterNodeAdded(r),_(n,r);continue}if(u(r,a,n)){o(a,r,n),a=a.nextSibling,_(n,r);continue}let i=m(e,t,r,a,n);if(i){a=f(a,i,n),o(i,r,n),_(n,r);continue}let s=h(e,t,r,a,n);if(s)a=f(a,s,n),o(s,r,n),_(n,r);else{if(!1===n.callbacks.beforeNodeAdded(r))return;t.insertBefore(r,a),n.callbacks.afterNodeAdded(r),_(n,r)}}for(;null!==a;){let e=a;a=a.nextSibling,b(e,n)}}function a(e,t,n,r){return!("value"!==e||!r.ignoreActiveValue||t!==document.activeElement)||!1===r.callbacks.beforeAttributeUpdated(e,t,n)}function i(e,t,n,r){if(e[n]!==t[n]){let o=a(n,t,"update",r);o||(t[n]=e[n]),e[n]?o||t.setAttribute(n,e[n]):a(n,t,"remove",r)||t.removeAttribute(n)}}function s(e,t,n){let r=[],o=[],l=[],a=[],i=n.head.style,s=new Map;for(const u of e.children)s.set(u.outerHTML,u);for(const u of t.children){let e=s.has(u.outerHTML),t=n.head.shouldReAppend(u),r=n.head.shouldPreserve(u);e||r?t?o.push(u):(s.delete(u.outerHTML),l.push(u)):"append"===i?t&&(o.push(u),a.push(u)):!1!==n.head.shouldRemove(u)&&o.push(u)}a.push(...s.values());let c=[];for(const u of a){let e=document.createRange().createContextualFragment(u.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(e)){if(e.href||e.src){let t=null,n=new Promise((function(e){t=e}));e.addEventListener("load",(function(){t()})),c.push(n)}t.appendChild(e),n.callbacks.afterNodeAdded(e),r.push(e)}}for(const u of o)!1!==n.callbacks.beforeNodeRemoved(u)&&(t.removeChild(u),n.callbacks.afterNodeRemoved(u));return n.head.afterHeadMorphed(t,{added:r,kept:l,removed:o}),c}function c(){}function u(e,t,n){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||y(n,e,t)>0))}function d(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function f(e,t,n){for(;e!==t;){let t=e;e=e.nextSibling,b(t,n)}return _(n,t),t.nextSibling}function m(e,t,n,r,o){let l=y(o,n,t);if(l>0){let t=r,a=0;for(;null!=t;){if(u(n,t,o))return t;if(a+=y(o,t,e),a>l)return null;t=t.nextSibling}}return null}function h(e,t,n,r,o){let l=r,a=n.nextSibling,i=0;for(;null!=l;){if(y(o,l,e)>0)return null;if(d(n,l))return l;if(d(a,l)&&(i++,a=a.nextSibling,i>=2))return null;l=l.nextSibling}return l}function p(e,t,n){return d(e,t)?.5+y(n,e,t):0}function b(e,t){_(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function g(e,t){return!e.deadIds.has(t)}function v(t,n,r){return(t.idMap.get(r)||e).has(n)}function _(t,n){let r=t.idMap.get(n)||e;for(const e of r)t.deadIds.add(e)}function y(t,n,r){let o=t.idMap.get(n)||e,l=0;for(const e of o)g(t,e)&&v(t,e,r)&&++l;return l}function A(e,t){let n=e.parentElement,r=e.querySelectorAll("[id]");for(const o of r){let e=o;for(;e!==n&&null!=e;){let n=t.get(e);null==n&&(n=new Set,t.set(e,n)),n.add(o.id),e=e.parentElement}}}function S(e,t){let n=new Map;return A(e,n),A(t,n),n}return{morph:function(e,r,o={}){e instanceof Document&&(e=e.documentElement),"string"==typeof r&&(r=function(e){let t=new DOMParser,n=e.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let r=t.parseFromString(e,"text/html");if(n.match(/<\/html>/))return r.generatedByIdiomorph=!0,r;{let e=r.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let n=t.parseFromString("","text/html").body.querySelector("template").content;return n.generatedByIdiomorph=!0,n}}(r));let l=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const n of[...e])t.append(n);return t}}(r),a=function(e,n,r){return r=function(e){let n={};return Object.assign(n,t),Object.assign(n,e),n.callbacks={},Object.assign(n.callbacks,t.callbacks),Object.assign(n.callbacks,e.callbacks),n.head={},Object.assign(n.head,t.head),Object.assign(n.head,e.head),n}(r),{target:e,newContent:n,config:r,morphStyle:r.morphStyle,ignoreActive:r.ignoreActive,ignoreActiveValue:r.ignoreActiveValue,idMap:S(e,n),deadIds:new Set,callbacks:r.callbacks,head:r.head}}(e,l,o);return n(e,l,a)},defaults:t}}(),v="CustomEvent"in window&&"function"==typeof window.CustomEvent?(e,t)=>new CustomEvent(e,t):(e,t)=>{const n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!0,!0,t),n},_=(e,t)=>function(n){const r=this,o=n.detail||{};e.__events[t].forEach((e=>{e.handler.apply(r,[n].concat(o.args))}))},y=(e,t)=>{e.__events[t]&&e.__events[t].listener&&(e.removeEventListener(t,e.__events[t].listener,"focus"==t||"blur"==t||"mouseenter"==t||"mouseleave"==t),delete e.__events[t])},A=(e,t,n)=>function(r){const o=this,l=r.detail||{};let a=r.target;for(;a&&(a.matches(t)&&(r.delegateTarget=a,n.apply(o,[r].concat(l.args))),a!==e);)a=a.parentNode},S=(e,t,n,r)=>{if(e.__events=e.__events||{},e.__events[t]=e.__events[t]||[],!e.__events[t].length){const n=_(e,t);e.addEventListener(t,n,"focus"==t||"blur"==t||"mouseenter"==t||"mouseleave"==t),e.__events[t].listener=n}n.call?e.__events[t].push({handler:n,callback:n}):e.__events[t].push({handler:A(e,n,r),callback:r})},E=(e,t,n)=>{if(n&&e.__events[t]&&e.__events[t].length){var r=e.__events[t];e.__events[t]=e.__events[t].filter((function(e){return e.callback!=n})),e.__events[t].listener=r.listener,e.__events[t].length||y(e,t)}else y(e,t)},x=(e,t,n)=>{e.dispatchEvent(v(t,{bubbles:!0,detail:n}))};const N=e=>({main:e=>e,unmount:e=>e,onupdate:e=>e,view:e.view?e.view:e=>e}),k=e=>{e.querySelectorAll("[scope]").forEach((e=>{e.querySelectorAll("[tplid]").forEach((t=>{if(!t.___scope___){const n=e.lastElementChild;t.___scope___="scope"in n.dataset?new Function(`return ${n.text}`)():{}}}))}))},M=e=>({callbacks:{beforeNodeMorphed(t){if(1===t.nodeType){if("html-static"in t.attributes)return!1;if(t.base&&t!==e)return!1}}}});function T(e,t,n,r){return class extends HTMLElement{constructor(){super();const{base:o,options:i}=function(e,{module:t,dependencies:n,templates:r,components:o}){const i=N(t),c=new Function(`return ${e.getAttribute("html-model")||"{}"}`)(),u=Object.keys(o).toString();d(e,u,r,o);const f=e.getAttribute("tplid"),m=f?r[f]:null,h={data:t.model?a(t.model):{}};h.data=Object.assign(h.data,c);const v={template:m,elm:e,dependencies:n,publish:p,subscribe:b,main(e){i.main=e},unmount(e){i.unmount=e},onupdate(e){i.onupdate=e},on(t,n,r){S(e,t,n,r)},off(t,n){E(e,t,n)},trigger(t,n,r){n.constructor===String?Array.from(e.querySelectorAll(n)).forEach((e=>x(e,t,{args:r}))):x(e,t,{args:n})},emit:(...t)=>{x(e,t.shift(),{args:t})},state:{set(e){if(e.constructor===Function){const t=a(h.data);e(t),v.render(t)}else v.render(e);return new Promise((e=>l((t=>l((()=>e(h.data)))))))},get:()=>a(h.data),getRaw:()=>h.data},render(t=h.data){if(!document.body.contains(e))return;h.data=Object.assign(h.data,t);const n=a(h.data),o=r[f].call(Object.assign(i.view(n),e.___scope___),e,s);g.morph(e,o,M(e)),k(e),l((n=>{Array.from(e.querySelectorAll("[tplid]")).forEach((e=>{const n=Object.assign(e.base.state.getRaw(),t);e.options.onupdate(n),e.base.render(n)}))}))},innerHTML(t,n){const r=n?t:e,o=r.cloneNode(),a=n||t;o.innerHTML=a,l((e=>g.morph(r,o,M)))}};return{base:v,options:i}}(this,{module:e,dependencies:t,templates:n,components:r});this.base=o,this.options=i,this.returns=e.default(o)}connectedCallback(){if(this.base.render(),this.__template&&this.__template.constructor===Promise)this.__template.then((e=>{if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}));else if(this.returns&&this.returns.constructor===Promise)this.returns.then((e=>{if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}));else if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}disconnectedCallback(){this.options.unmount(this.base),l((()=>{document.body.contains(this)||(this.__events&&(this.__events=null),this.base&&(this.base.elm=null),this.base&&(this.base=null),i(this))}))}attributeChangedCallback(){}}}const $={},w={},H={templateConfig:e=>{Object.assign(c,e)},publish:p,subscribe:b,register(e,t,n={}){w[e]={name:e,module:t,dependencies:n}},start(e=document.body){const t=Object.keys(w),n=t.toString();t.length&&(d(e,n,$,w),C())}},C=()=>{Object.values(w).forEach((e=>{const{name:t,module:n,dependencies:r}=e;if(!customElements.get(t)){const e=T(n,r,$,w);customElements.define(t,e)}}))};e.default=H,e.html=(e,...t)=>{let n=e.raw,r="";return t.forEach(((e,t)=>{let o=n[t];Array.isArray(e)&&(e=e.join("")),r+=o,r+=e})),r+=n[n.length-1],r},Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jails={})}(this,(function(e){"use strict";const t=new DOMParser;const n=(e,t,n)=>{var r,o;null==(r=t.parentNode)||r.insertBefore(e,t),null==(o=t.parentNode)||o.insertBefore(n,t.nextSibling)},r=document.createElement("textarea"),o=e=>(r.innerHTML=e,r.value),l=e=>requestAnimationFrame?requestAnimationFrame(e):setTimeout(e,1e3/60),a=e=>JSON.parse(JSON.stringify(e)),i=e=>{var t,n,r,o=e.attributes;if(o)for(t=o.length-1;t>=0;t-=1)"function"==typeof e[r=o[t].name]&&(e[r]=null);if(o=e.childNodes)for(n=o.length,t=0;t{try{return e()}catch(n){return t||""}},c={tags:["${","}"]};function u(e){const r=function(e,r){const o=new RegExp(`\\${r.tags[0]}(.+?)\\${r.tags[1]}`,"g"),l=t.parseFromString(e.replace(/<\/?template[^>]*>/g,""),"text/html");return l.querySelectorAll("[html-for], [html-if], [html-inner], [html-class], [html-model]").forEach((e=>{const t=e.getAttribute("html-foreach"),r=e.getAttribute("html-for"),o=e.getAttribute("html-if"),l=e.getAttribute("html-inner"),a=e.getAttribute("html-class"),i=r||t;if(i){const t=r?"html-for":"html-foreach",o=i.match(/(.*)\sin\s(.*)/)||"",l=o[1],a=o[2];e.removeAttribute(t),e.setAttribute("scope","");const s=document.createElement("script");s.dataset.scope="",s.type="text/html",s.text="%%_= $scope _%%",e.appendChild(s);const c=document.createTextNode(`%%_(function(){ var $index = 0; for(var $key in safe(function(){ return ${a} }) ){ var ${l} = ${a}[$key]; var $scope = JSON.stringify({ '${l}':${l}, $index: $index, $key:$key }); _%%`),u=document.createTextNode("%%_ $index++; } })() _%%");n(c,e,u)}if(o){e.removeAttribute("html-if");const t=document.createTextNode(`%%_ if ( safe(function(){ return ${o} }) ){ _%%`),r=document.createTextNode("%%_ } _%%");n(t,e,r)}l&&(e.removeAttribute("html-inner"),e.innerHTML=`%%_=${l}_%%`),a&&(e.removeAttribute("html-class"),e.className=(e.className+` %%_=${a}_%%`).trim())})),l.body.innerHTML.replace(o,"%%_=$1_%%").replace(/html-(allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|formnovalidate|inert|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected)=\"(.*?)\"/g,"%%_if(safe(function(){ return $2 })){_%%$1%%_}_%%").replace(/html-(.*?)=\"(.*?)\"/g,((e,t,n)=>"key"===t||"model"===t||"scope"==t?e:n?`${t}="%%_=safe(function(){ return ${n=n.replace(/^{|}$/g,"")} })_%%"`:e))}(e.outerHTML,c),l=JSON.stringify(r);return new Function("$element","safe",`\n\t\tvar $data = this;\n\t\twith( $data ){\n\t\t\tvar output=${l.replace(/%%_=(.+?)_%%/g,(function(e,t){return'"+safe(function(){return '+o(t)+';})+"'})).replace(/%%_(.+?)_%%/g,(function(e,t){return'";'+o(t)+'\noutput+="'}))};return output;\n\t\t}\n\t`)}const d=(e,t,n,r)=>{[].concat(e.matches&&e.matches(t)?e:[]).concat(Array.from(e.querySelectorAll(t))).reverse().forEach((e=>{e.querySelectorAll("template").forEach((e=>d(e.content,t,n,r))),f(e,n,r)}))},f=(e,t,n)=>{if(!e.getAttribute("tplid")){const r="xxxxxxxx".replace(/[xy]/g,(e=>{const t=8*Math.random()|0;return("x"==e?t:3&t|8).toString(8)}));e.setAttribute("tplid",r);const o=e.localName;if(o in n&&n[o].module.template){const l=n[o].module.template();l.constructor===Promise?(e.__template=l,l.then((n=>{e.innerHTML=n,t[r]=u(e)}))):e.innerHTML=l}t[r]=u(e)}},m={},h={},p=(e,t)=>{h[e]=Object.assign({},h[e],t),m[e]&&m[e].forEach((e=>e(t)))},b=(e,t)=>(m[e]=m[e]||[],m[e].push(t),e in h&&t(h[e]),()=>{m[e]=m[e].filter((e=>e!=t))});var g=function(){let e=new Set,t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:c,afterNodeAdded:c,beforeNodeMorphed:c,afterNodeMorphed:c,beforeNodeRemoved:c,afterNodeRemoved:c,beforeAttributeUpdated:c},head:{style:"merge",shouldPreserve:function(e){return"true"===e.getAttribute("im-preserve")},shouldReAppend:function(e){return"true"===e.getAttribute("im-re-append")},shouldRemove:c,afterHeadMorphed:c}};function n(e,t,r){if(r.head.block){let o=e.querySelector("head"),l=t.querySelector("head");if(o&&l){let a=s(l,o,r);return void Promise.all(a).then((function(){n(e,t,Object.assign(r,{head:{block:!1,ignore:!0}}))}))}}if("innerHTML"===r.morphStyle)return l(t,e,r),e.children;if("outerHTML"===r.morphStyle||null==r.morphStyle){let n=function(e,t,n){let r;r=e.firstChild;let o=r,l=0;for(;r;){let e=p(r,t,n);e>l&&(o=r,l=e),r=r.nextSibling}return o}(t,e,r),l=null==n?void 0:n.previousSibling,a=null==n?void 0:n.nextSibling,i=o(e,n,r);return n?function(e,t,n){let r=[],o=[];for(;null!=e;)r.push(e),e=e.previousSibling;for(;r.length>0;){let e=r.pop();o.push(e),t.parentElement.insertBefore(e,t)}o.push(t);for(;null!=n;)r.push(n),o.push(n),n=n.nextSibling;for(;r.length>0;)t.parentElement.insertBefore(r.pop(),t.nextSibling);return o}(l,i,a):[]}throw"Do not understand how to morph style "+r.morphStyle}function r(e,t){return t.ignoreActiveValue&&e===document.activeElement}function o(e,t,n){if(!n.ignoreActive||e!==document.activeElement)return null==t?!1===n.callbacks.beforeNodeRemoved(e)?e:(e.remove(),n.callbacks.afterNodeRemoved(e),null):d(e,t)?(!1===n.callbacks.beforeNodeMorphed(e,t)||(e instanceof HTMLHeadElement&&n.head.ignore||(e instanceof HTMLHeadElement&&"morph"!==n.head.style?s(t,e,n):(!function(e,t,n){let o=e.nodeType;if(1===o){const r=e.attributes,o=t.attributes;for(const e of r)a(e.name,t,"update",n)||t.getAttribute(e.name)!==e.value&&t.setAttribute(e.name,e.value);for(let l=o.length-1;0<=l;l--){const r=o[l];a(r.name,t,"remove",n)||(e.hasAttribute(r.name)||t.removeAttribute(r.name))}}8!==o&&3!==o||t.nodeValue!==e.nodeValue&&(t.nodeValue=e.nodeValue);r(t,n)||function(e,t,n){if(e instanceof HTMLInputElement&&t instanceof HTMLInputElement&&"file"!==e.type){let r=e.value,o=t.value;i(e,t,"checked",n),i(e,t,"disabled",n),e.hasAttribute("value")?r!==o&&(a("value",t,"update",n)||(t.setAttribute("value",r),t.value=r)):a("value",t,"remove",n)||(t.value="",t.removeAttribute("value"))}else if(e instanceof HTMLOptionElement)i(e,t,"selected",n);else if(e instanceof HTMLTextAreaElement&&t instanceof HTMLTextAreaElement){let r=e.value,o=t.value;if(a("value",t,"update",n))return;r!==o&&(t.value=r),t.firstChild&&t.firstChild.nodeValue!==r&&(t.firstChild.nodeValue=r)}}(e,t,n)}(t,e,n),r(e,n)||l(t,e,n))),n.callbacks.afterNodeMorphed(e,t)),e):!1===n.callbacks.beforeNodeRemoved(e)||!1===n.callbacks.beforeNodeAdded(t)?e:(e.parentElement.replaceChild(t,e),n.callbacks.afterNodeAdded(t),n.callbacks.afterNodeRemoved(e),t)}function l(e,t,n){let r,l=e.firstChild,a=t.firstChild;for(;l;){if(r=l,l=r.nextSibling,null==a){if(!1===n.callbacks.beforeNodeAdded(r))return;t.appendChild(r),n.callbacks.afterNodeAdded(r),_(n,r);continue}if(u(r,a,n)){o(a,r,n),a=a.nextSibling,_(n,r);continue}let i=m(e,t,r,a,n);if(i){a=f(a,i,n),o(i,r,n),_(n,r);continue}let s=h(e,t,r,a,n);if(s)a=f(a,s,n),o(s,r,n),_(n,r);else{if(!1===n.callbacks.beforeNodeAdded(r))return;t.insertBefore(r,a),n.callbacks.afterNodeAdded(r),_(n,r)}}for(;null!==a;){let e=a;a=a.nextSibling,b(e,n)}}function a(e,t,n,r){return!("value"!==e||!r.ignoreActiveValue||t!==document.activeElement)||!1===r.callbacks.beforeAttributeUpdated(e,t,n)}function i(e,t,n,r){if(e[n]!==t[n]){let o=a(n,t,"update",r);o||(t[n]=e[n]),e[n]?o||t.setAttribute(n,e[n]):a(n,t,"remove",r)||t.removeAttribute(n)}}function s(e,t,n){let r=[],o=[],l=[],a=[],i=n.head.style,s=new Map;for(const u of e.children)s.set(u.outerHTML,u);for(const u of t.children){let e=s.has(u.outerHTML),t=n.head.shouldReAppend(u),r=n.head.shouldPreserve(u);e||r?t?o.push(u):(s.delete(u.outerHTML),l.push(u)):"append"===i?t&&(o.push(u),a.push(u)):!1!==n.head.shouldRemove(u)&&o.push(u)}a.push(...s.values());let c=[];for(const u of a){let e=document.createRange().createContextualFragment(u.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(e)){if(e.href||e.src){let t=null,n=new Promise((function(e){t=e}));e.addEventListener("load",(function(){t()})),c.push(n)}t.appendChild(e),n.callbacks.afterNodeAdded(e),r.push(e)}}for(const u of o)!1!==n.callbacks.beforeNodeRemoved(u)&&(t.removeChild(u),n.callbacks.afterNodeRemoved(u));return n.head.afterHeadMorphed(t,{added:r,kept:l,removed:o}),c}function c(){}function u(e,t,n){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName&&(""!==e.id&&e.id===t.id||y(n,e,t)>0))}function d(e,t){return null!=e&&null!=t&&(e.nodeType===t.nodeType&&e.tagName===t.tagName)}function f(e,t,n){for(;e!==t;){let t=e;e=e.nextSibling,b(t,n)}return _(n,t),t.nextSibling}function m(e,t,n,r,o){let l=y(o,n,t);if(l>0){let t=r,a=0;for(;null!=t;){if(u(n,t,o))return t;if(a+=y(o,t,e),a>l)return null;t=t.nextSibling}}return null}function h(e,t,n,r,o){let l=r,a=n.nextSibling,i=0;for(;null!=l;){if(y(o,l,e)>0)return null;if(d(n,l))return l;if(d(a,l)&&(i++,a=a.nextSibling,i>=2))return null;l=l.nextSibling}return l}function p(e,t,n){return d(e,t)?.5+y(n,e,t):0}function b(e,t){_(t,e),!1!==t.callbacks.beforeNodeRemoved(e)&&(e.remove(),t.callbacks.afterNodeRemoved(e))}function g(e,t){return!e.deadIds.has(t)}function v(t,n,r){return(t.idMap.get(r)||e).has(n)}function _(t,n){let r=t.idMap.get(n)||e;for(const e of r)t.deadIds.add(e)}function y(t,n,r){let o=t.idMap.get(n)||e,l=0;for(const e of o)g(t,e)&&v(t,e,r)&&++l;return l}function A(e,t){let n=e.parentElement,r=e.querySelectorAll("[id]");for(const o of r){let e=o;for(;e!==n&&null!=e;){let n=t.get(e);null==n&&(n=new Set,t.set(e,n)),n.add(o.id),e=e.parentElement}}}function S(e,t){let n=new Map;return A(e,n),A(t,n),n}return{morph:function(e,r,o={}){e instanceof Document&&(e=e.documentElement),"string"==typeof r&&(r=function(e){let t=new DOMParser,n=e.replace(/]*>|>)([\s\S]*?)<\/svg>/gim,"");if(n.match(/<\/html>/)||n.match(/<\/head>/)||n.match(/<\/body>/)){let r=t.parseFromString(e,"text/html");if(n.match(/<\/html>/))return r.generatedByIdiomorph=!0,r;{let e=r.firstChild;return e?(e.generatedByIdiomorph=!0,e):null}}{let n=t.parseFromString("","text/html").body.querySelector("template").content;return n.generatedByIdiomorph=!0,n}}(r));let l=function(e){if(null==e){return document.createElement("div")}if(e.generatedByIdiomorph)return e;if(e instanceof Node){const t=document.createElement("div");return t.append(e),t}{const t=document.createElement("div");for(const n of[...e])t.append(n);return t}}(r),a=function(e,n,r){return r=function(e){let n={};return Object.assign(n,t),Object.assign(n,e),n.callbacks={},Object.assign(n.callbacks,t.callbacks),Object.assign(n.callbacks,e.callbacks),n.head={},Object.assign(n.head,t.head),Object.assign(n.head,e.head),n}(r),{target:e,newContent:n,config:r,morphStyle:r.morphStyle,ignoreActive:r.ignoreActive,ignoreActiveValue:r.ignoreActiveValue,idMap:S(e,n),deadIds:new Set,callbacks:r.callbacks,head:r.head}}(e,l,o);return n(e,l,a)},defaults:t}}();const v="CustomEvent"in window&&"function"==typeof window.CustomEvent?(e,t)=>new CustomEvent(e,t):(e,t)=>{const n=document.createEvent("CustomEvent");return n.initCustomEvent(e,!0,!0,t),n},_=(e,t)=>function(n){const r=this,o=n.detail||{};e.__events[t].forEach((e=>{e.handler.apply(r,[n].concat(o.args))}))},y=(e,t)=>{e.__events[t]&&e.__events[t].listener&&(e.removeEventListener(t,e.__events[t].listener,"focus"==t||"blur"==t||"mouseenter"==t||"mouseleave"==t),delete e.__events[t])},A=(e,t,n)=>function(r){const o=this,l=r.detail||{};let a=r.target;for(;a&&(a.matches(t)&&(r.delegateTarget=a,n.apply(o,[r].concat(l.args))),a!==e);)a=a.parentNode},S=(e,t,n,r)=>{if(e.__events=e.__events||{},e.__events[t]=e.__events[t]||[],!e.__events[t].length){const n=_(e,t);e.addEventListener(t,n,"focus"==t||"blur"==t||"mouseenter"==t||"mouseleave"==t),e.__events[t].listener=n}n.call?e.__events[t].push({handler:n,callback:n}):e.__events[t].push({handler:A(e,n,r),callback:r})},E=(e,t,n)=>{if(n&&e.__events[t]&&e.__events[t].length){var r=e.__events[t];e.__events[t]=e.__events[t].filter((function(e){return e.callback!=n})),e.__events[t].listener=r.listener,e.__events[t].length||y(e,t)}else y(e,t)},x=(e,t,n)=>{e.dispatchEvent(v(t,{bubbles:!0,detail:n}))};const N=e=>({main:e=>e,unmount:e=>e,onupdate:e=>e,view:e.view?e.view:e=>e}),k=e=>{e.querySelectorAll("[scope]").forEach((e=>{e.querySelectorAll("[tplid]").forEach((t=>{if(!t.___scope___){const n=e.lastElementChild;t.___scope___="scope"in n.dataset?new Function(`return ${n.text}`)():{}}}))}))},M=e=>({callbacks:{beforeNodeMorphed(t){if(1===t.nodeType){if("html-static"in t.attributes)return!1;if(t.base&&t!==e)return!1}}}});function T(e,t,n,r){return class extends HTMLElement{constructor(){super();const{base:o,options:i}=function(e,{module:t,dependencies:n,templates:r,components:o}){const i=N(t),c=new Function(`return ${e.getAttribute("html-model")||"{}"}`)(),u=Object.keys(o).toString();d(e,u,r,o);const f=e.getAttribute("tplid"),m=f?r[f]:null,h={data:t.model?a(t.model):{}};h.data=Object.assign(h.data,c);const v={template:m,elm:e,dependencies:n,publish:p,subscribe:b,main(e){i.main=e},unmount(e){i.unmount=e},onupdate(e){i.onupdate=e},on(t,n,r){S(e,t,n,r)},off(t,n){E(e,t,n)},trigger(t,n,r){n.constructor===String?Array.from(e.querySelectorAll(n)).forEach((e=>x(e,t,{args:r}))):x(e,t,{args:n})},emit:(...t)=>{x(e,t.shift(),{args:t})},state:{set(e){if(e.constructor===Function){const t=a(h.data);e(t),v.render(t)}else v.render(e);return new Promise((e=>l((t=>l((()=>e(h.data)))))))},get:()=>a(h.data),getRaw:()=>h.data},render(t=h.data){if(!document.body.contains(e))return;h.data=Object.assign(h.data,t);const n=a(h.data),o=r[f].call(Object.assign(i.view(n),e.___scope___),e,s);g.morph(e,o,M(e)),k(e),l((n=>{Array.from(e.querySelectorAll("[tplid]")).forEach((e=>{const n=Object.assign(e.base.state.getRaw(),t);e.options.onupdate(n),e.base.render(n)}))}))},innerHTML(t,n){const r=n?t:e,o=r.cloneNode(),a=n||t;o.innerHTML=a,l((e=>g.morph(r,o,M)))}};return{base:v,options:i}}(this,{module:e,dependencies:t,templates:n,components:r});this.base=o,this.options=i,this.returns=e.default(o)}connectedCallback(){if(this.base.render(),this.__template&&this.__template.constructor===Promise)this.__template.then((e=>{if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}));else if(this.returns&&this.returns.constructor===Promise)this.returns.then((e=>{if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}));else if(this.base&&this.options.main){const e=this.options.main(this.base);e&&e.length&&e.forEach((e=>e(this.base)))}}disconnectedCallback(){this.options.unmount(this.base),l((()=>{document.body.contains(this)||(this.__events&&(this.__events=null),this.base&&(this.base.elm=null),this.base&&(this.base=null),i(this))}))}attributeChangedCallback(){}}}const $={},w={},H={templateConfig:e=>{Object.assign(c,e)},publish:p,subscribe:b,register(e,t,n={}){w[e]={name:e,module:t,dependencies:n}},start(e=document.body){const t=Object.keys(w),n=t.toString();t.length&&(d(e,n,$,w),C())}},C=()=>{Object.values(w).forEach((e=>{const{name:t,module:n,dependencies:r}=e;if(!customElements.get(t)){const e=T(n,r,$,w);customElements.define(t,e)}}))};e.default=H,e.html=(e,...t)=>{let n=e.raw,r="";return t.forEach(((e,t)=>{let o=n[t];Array.isArray(e)&&(e=e.join("")),r+=o,r+=e})),r+=n[n.length-1],r},Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})); //# sourceMappingURL=jails.js.map diff --git a/dist/jails.js.map b/dist/jails.js.map index d4a8fde..de1a712 100644 --- a/dist/jails.js.map +++ b/dist/jails.js.map @@ -1 +1 @@ -{"version":3,"file":"jails.js","sources":["../src/transpile.ts","../src/utils/index.ts","../src/template-system.ts","../src/utils/pubsub.ts","../src/utils/idiomorph.ts","../src/utils/events.ts","../src/component.ts","../src/element.ts","../src/index.ts"],"sourcesContent":["const parser = new DOMParser()\n\nexport default function Transpile(html, config) {\n\n\tconst regexTags = new RegExp(`\\\\${config.tags[0]}(.+?)\\\\${config.tags[1]}`, 'g')\n\tconst virtual = parser.parseFromString(html.replace(/<\\/?template[^>]*>/g, ''), 'text/html')\n\n\tvirtual.querySelectorAll('[html-for], [html-if], [html-inner], [html-class], [html-model]').forEach((element) => {\n\n\t\tconst htmlForeach = element.getAttribute('html-foreach')\n\t\tconst htmlFor \t= element.getAttribute('html-for')\n\t\tconst htmlIf \t= element.getAttribute('html-if')\n\t\tconst htmlInner = element.getAttribute('html-inner')\n\t\tconst htmlClass = element.getAttribute('html-class')\n\t\tconst forEachInstruction = htmlFor || htmlForeach\n\n\t\tif ( forEachInstruction ) {\n\t\t\tconst selector = htmlFor? 'html-for': 'html-foreach'\n\t\t\tconst split = forEachInstruction.match(/(.*)\\sin\\s(.*)/) || ''\n\t\t\tconst varname = split[1]\n\t\t\tconst object = split[2]\n\n\t\t\telement.removeAttribute(selector)\n\t\t\telement.setAttribute('scope', '')\n\t\t\tconst script = document.createElement('script')\n\n\t\t\tscript.dataset.scope = ''\n\t\t\tscript.type = 'text/html'\n\t\t\tscript.text = `%%_= $scope _%%`\n\n\t\t\telement.appendChild( script )\n\n\t\t\tconst open = document.createTextNode(`%%_(function(){ var $index = 0; for(var $key in safe(function(){ return ${object} }) ){ var ${varname} = ${object}[$key]; var $scope = JSON.stringify({ '${varname}':${varname}, $index: $index, $key:$key }); _%%`)\n\t\t\tconst close = document.createTextNode(`%%_ $index++; } })() _%%`)\n\t\t\twrap(open, element, close)\n\t\t}\n\t\tif (htmlIf) {\n\t\t\telement.removeAttribute('html-if')\n\t\t\tconst open = document.createTextNode(`%%_ if ( safe(function(){ return ${htmlIf} }) ){ _%%`)\n\t\t\tconst close = document.createTextNode(`%%_ } _%%`)\n\t\t\twrap(open, element, close)\n\t\t}\n\t\tif (htmlInner) {\n\t\t\telement.removeAttribute('html-inner')\n\t\t\telement.innerHTML = `%%_=${htmlInner}_%%`\n\t\t}\n\t\tif (htmlClass) {\n\t\t\telement.removeAttribute('html-class')\n\t\t\telement.className = (element.className + ` %%_=${htmlClass}_%%`).trim()\n\t\t}\n\t})\n\n\n\treturn (\n\t\tvirtual.body.innerHTML\n\t\t\t.replace(regexTags, '%%_=$1_%%')\n\t\t\t// Booleans\n\t\t\t// https://meiert.com/en/blog/boolean-attributes-of-html/\n\t\t\t.replace(/html-(allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|formnovalidate|inert|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected)=\\\"(.*?)\\\"/g, `%%_if(safe(function(){ return $2 })){_%%$1%%_}_%%`)\n\t\t\t// The rest\n\t\t\t.replace(/html-(.*?)=\\\"(.*?)\\\"/g, (all, key, value) => {\n\t\t\t\tif (key === 'key' || key === 'model' || key == 'scope') {\n\t\t\t\t\treturn all\n\t\t\t\t}\n\t\t\t\tif (value) {\n\t\t\t\t\tvalue = value.replace(/^{|}$/g, '')\n\t\t\t\t\treturn `${key}=\"%%_=safe(function(){ return ${value} })_%%\"`\n\t\t\t\t} else {\n\t\t\t\t\treturn all\n\t\t\t\t}\n\t\t\t})\n\t)\n}\n\nconst wrap = (open, node, close) => {\n\tnode.parentNode?.insertBefore(open, node)\n\tnode.parentNode?.insertBefore(close, node.nextSibling)\n}\n","const textarea = document.createElement('textarea')\n\nexport const decodeHTML = (text) => {\n\ttextarea.innerHTML = text\n\treturn textarea.value\n}\n\nexport const rAF = (fn) => {\n\tif (requestAnimationFrame)\n\t\treturn requestAnimationFrame(fn)\n\telse\n\t\treturn setTimeout(fn, 1000 / 60)\n}\n\nexport const uuid = () => {\n\treturn 'xxxxxxxx'.replace(/[xy]/g, (c) => {\n\t\tconst r = Math.random() * 8 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)\n\t\treturn v.toString(8)\n\t})\n}\n\n\nexport const dup = (o) => {\n\treturn JSON.parse(JSON.stringify(o))\n}\n\n// http://crockford.com/javascript/memory/leak.html\nexport const purge = (d) => {\n\tvar a = d.attributes, i, l, n\n\tif (a) {\n\t\tfor (i = a.length - 1; i >= 0; i -= 1) {\n\t\t\tn = a[i].name\n\t\t\tif (typeof d[n] === 'function') {\n\t\t\t\td[n] = null\n\t\t\t}\n\t\t}\n\t}\n\ta = d.childNodes\n\tif (a) {\n\t\tl = a.length\n\t\tfor (i = 0; i < l; i += 1) {\n\t\t\tpurge(d.childNodes[i])\n\t\t}\n\t}\n}\n\nexport const safe = (execute, val) => {\n\ttry{return execute()}catch(err){return val || ''}\n}\n\n// From\n// https://2ality.com/2015/01/template-strings-html.html#comment-2078932192\nexport const html = (literalSections, ...substs) => {\n\n\t// Use raw literal sections: we don’t want\n\t// backslashes (\\n etc.) to be interpreted\n\tlet raw = literalSections.raw\n\n\tlet result = ''\n\n\tsubsts.forEach((subst, i) => {\n\t\t// Retrieve the literal section preceding\n\t\t// the current substitution\n\t\tlet lit = raw[i]\n\n\t\t// In the example, map() returns an array:\n\t\t// If substitution is an array (and not a string),\n\t\t// we turn it into a string\n\t\tif (Array.isArray(subst)) {\n\t\t\tsubst = subst.join('')\n\t\t}\n\n\t\tresult += lit\n\t\tresult += subst\n\t})\n\t// Take care of last literal section\n\t// (Never fails, because an empty template string\n\t// produces one literal section, an empty string)\n\tresult += raw[raw.length-1] // (A)\n\n\treturn result\n}\n","import Transpile from './transpile'\nimport { uuid, decodeHTML } from './utils'\n\nconst config = {\n\ttags: ['${', '}']\n}\n\nexport const templateConfig = (newconfig) => {\n\tObject.assign(config, newconfig)\n}\n\nexport default function Template(element) {\n\n\tconst html = Transpile(element.outerHTML, config)\n\tconst decodedHTML = JSON.stringify(html)\n\n\treturn new Function('$element', 'safe',`\n\t\tvar $data = this;\n\t\twith( $data ){\n\t\t\tvar output=${decodedHTML\n\t\t\t\t.replace(/%%_=(.+?)_%%/g, function(_, variable){\n\t\t\t\t\treturn '\"+safe(function(){return '+decodeHTML(variable)+';})+\"'\n\t\t\t\t})\n\t\t\t\t.replace(/%%_(.+?)_%%/g, function(_, variable){\n\t\t\t\t\treturn '\";' + decodeHTML(variable) +'\\noutput+=\"'\n\t\t\t\t})};return output;\n\t\t}\n\t`)\n}\n\nexport const buildtemplates = ( target, selector, templates, components ) => {\n\t[]\n\t\t.concat( target.matches? (target.matches(selector)? target : []) : [] )\n\t\t.concat( Array.from(target.querySelectorAll( selector )) )\n\t\t.reverse()\n\t\t.forEach( (node:HTMLElement) => {\n\t\t\tnode.querySelectorAll('template').forEach( template => buildtemplates(template.content, selector, templates, components ))\n\t\t\tcreateTemplateId(node, templates, components)\n\t\t})\n}\n\nconst createTemplateId = (element, templates, components ) => {\n\n\tconst tplid = element.getAttribute('tplid')\n\n\tif (!tplid) {\n\t\tconst id = uuid()\n\t\telement.setAttribute('tplid', id)\n\t\tconst name = element.localName\n\n\t\tif( name in components && components[name].module.template ) {\n\t\t\tconst html = components[name].module.template()\n\t\t\tif( html.constructor === Promise ) {\n\t\t\t\telement.__template = html\n\t\t\t\thtml.then( htmlstring => {\n\t\t\t\t\telement.innerHTML = htmlstring\n\t\t\t\t\ttemplates[id] = Template(element)\n\t\t\t\t})\n\t\t\t}else {\n\t\t\t\telement.innerHTML = html\n\t\t\t}\n\t\t}\n\t\ttemplates[id] = Template(element)\n\t}\n}\n\n","const topics: any = {}\nconst _async: any = {}\n\nexport const publish = (name, params) => {\n\t_async[name] = Object.assign({}, _async[name], params)\n\tif (topics[name])\n\t\ttopics[name].forEach(topic => topic(params))\n}\n\nexport const subscribe = (name, method) => {\n\ttopics[name] = topics[name] || []\n\ttopics[name].push(method)\n\tif (name in _async) {\n\t\tmethod(_async[name])\n\t}\n\treturn () => {\n\t\ttopics[name] = topics[name].filter( fn => fn != method )\n\t}\n}\n\n","/**\n * BSD 2-Clause License\n * https://github.com/bigskysoftware/idiomorph\n\n\tCopyright (c) 2022, Big Sky Software\n\tAll rights reserved.\n\n\tRedistribution and use in source and binary forms, with or without\n\tmodification, are permitted provided that the following conditions are met:\n\n\t1. Redistributions of source code must retain the above copyright notice, this\n\tlist of conditions and the following disclaimer.\n\n\t2. Redistributions in binary form must reproduce the above copyright notice,\n\tthis list of conditions and the following disclaimer in the documentation\n\tand/or other materials provided with the distribution.\n\n\tTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\tAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\tIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\tDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\tFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\tDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\tSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\tCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\tOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\tOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n// base IIFE to define idiomorph\n\n\nexport const Idiomorph = (function () {\n\t'use strict';\n\n\t//=============================================================================\n\t// AND NOW IT BEGINS...\n\t//=============================================================================\n\tlet EMPTY_SET = new Set();\n\n\t// default configuration values, updatable by users now\n\tlet defaults = {\n\t\tmorphStyle: \"outerHTML\",\n\t\tcallbacks : {\n\t\t\tbeforeNodeAdded: noOp,\n\t\t\tafterNodeAdded: noOp,\n\t\t\tbeforeNodeMorphed: noOp,\n\t\t\tafterNodeMorphed: noOp,\n\t\t\tbeforeNodeRemoved: noOp,\n\t\t\tafterNodeRemoved: noOp,\n\t\t\tbeforeAttributeUpdated: noOp,\n\n\t\t},\n\t\thead: {\n\t\t\tstyle: 'merge',\n\t\t\tshouldPreserve: function (elt) {\n\t\t\t\treturn elt.getAttribute(\"im-preserve\") === \"true\";\n\t\t\t},\n\t\t\tshouldReAppend: function (elt) {\n\t\t\t\treturn elt.getAttribute(\"im-re-append\") === \"true\";\n\t\t\t},\n\t\t\tshouldRemove: noOp,\n\t\t\tafterHeadMorphed: noOp,\n\t\t}\n\t};\n\n\t//=============================================================================\n\t// Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren\n\t//=============================================================================\n\tfunction morph(oldNode, newContent, config = {}) {\n\n\t\tif (oldNode instanceof Document) {\n\t\t\toldNode = oldNode.documentElement;\n\t\t}\n\n\t\tif (typeof newContent === 'string') {\n\t\t\tnewContent = parseContent(newContent);\n\t\t}\n\n\t\tlet normalizedContent = normalizeContent(newContent);\n\n\t\tlet ctx = createMorphContext(oldNode, normalizedContent, config);\n\n\t\treturn morphNormalizedContent(oldNode, normalizedContent, ctx);\n\t}\n\n\tfunction morphNormalizedContent(oldNode, normalizedNewContent, ctx) {\n\t\tif (ctx.head.block) {\n\t\t\tlet oldHead = oldNode.querySelector('head');\n\t\t\tlet newHead = normalizedNewContent.querySelector('head');\n\t\t\tif (oldHead && newHead) {\n\t\t\t\tlet promises = handleHeadElement(newHead, oldHead, ctx);\n\t\t\t\t// when head promises resolve, call morph again, ignoring the head tag\n\t\t\t\tPromise.all(promises).then(function () {\n\t\t\t\t\tmorphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {\n\t\t\t\t\t\thead: {\n\t\t\t\t\t\t\tblock: false,\n\t\t\t\t\t\t\tignore: true\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tif (ctx.morphStyle === \"innerHTML\") {\n\n\t\t\t// innerHTML, so we are only updating the children\n\t\t\tmorphChildren(normalizedNewContent, oldNode, ctx);\n\t\t\treturn oldNode.children;\n\n\t\t} else if (ctx.morphStyle === \"outerHTML\" || ctx.morphStyle == null) {\n\t\t\t// otherwise find the best element match in the new content, morph that, and merge its siblings\n\t\t\t// into either side of the best match\n\t\t\tlet bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);\n\n\t\t\t// stash the siblings that will need to be inserted on either side of the best match\n\t\t\tlet previousSibling = bestMatch?.previousSibling;\n\t\t\tlet nextSibling = bestMatch?.nextSibling;\n\n\t\t\t// morph it\n\t\t\tlet morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);\n\n\t\t\tif (bestMatch) {\n\t\t\t\t// if there was a best match, merge the siblings in too and return the\n\t\t\t\t// whole bunch\n\t\t\t\treturn insertSiblings(previousSibling, morphedNode, nextSibling);\n\t\t\t} else {\n\t\t\t\t// otherwise nothing was added to the DOM\n\t\t\t\treturn []\n\t\t\t}\n\t\t} else {\n\t\t\tthrow \"Do not understand how to morph style \" + ctx.morphStyle;\n\t\t}\n\t}\n\n\n\t/**\n\t * @param possibleActiveElement\n\t * @param ctx\n\t * @returns {boolean}\n\t */\n\tfunction ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n\t\treturn ctx.ignoreActiveValue && possibleActiveElement === document.activeElement;\n\t}\n\n\t/**\n\t * @param oldNode root node to merge content into\n\t * @param newContent new content to merge\n\t * @param ctx the merge context\n\t * @returns {Element} the element that ended up in the DOM\n\t */\n\tfunction morphOldNodeTo(oldNode, newContent, ctx) {\n\t\tif (ctx.ignoreActive && oldNode === document.activeElement) {\n\t\t\t// don't morph focused element\n\t\t} else if (newContent == null) {\n\t\t\tif (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\n\t\t\toldNode.remove();\n\t\t\tctx.callbacks.afterNodeRemoved(oldNode);\n\t\t\treturn null;\n\t\t} else if (!isSoftMatch(oldNode, newContent)) {\n\t\t\tif (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\t\t\tif (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;\n\n\t\t\toldNode.parentElement.replaceChild(newContent, oldNode);\n\t\t\tctx.callbacks.afterNodeAdded(newContent);\n\t\t\tctx.callbacks.afterNodeRemoved(oldNode);\n\t\t\treturn newContent;\n\t\t} else {\n\t\t\tif (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;\n\n\t\t\tif (oldNode instanceof HTMLHeadElement && ctx.head.ignore) {\n\t\t\t\t// ignore the head element\n\t\t\t} else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== \"morph\") {\n\t\t\t\thandleHeadElement(newContent, oldNode, ctx);\n\t\t\t} else {\n\t\t\t\tsyncNodeFrom(newContent, oldNode, ctx);\n\t\t\t\tif (!ignoreValueOfActiveElement(oldNode, ctx)) {\n\t\t\t\t\tmorphChildren(newContent, oldNode, ctx);\n\t\t\t\t}\n\t\t\t}\n\t\t\tctx.callbacks.afterNodeMorphed(oldNode, newContent);\n\t\t\treturn oldNode;\n\t\t}\n\t}\n\n\t/**\n\t * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n\t * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n\t * by using id sets, we are able to better match up with content deeper in the DOM.\n\t *\n\t * Basic algorithm is, for each node in the new content:\n\t *\n\t * - if we have reached the end of the old parent, append the new content\n\t * - if the new content has an id set match with the current insertion point, morph\n\t * - search for an id set match\n\t * - if id set match found, morph\n\t * - otherwise search for a \"soft\" match\n\t * - if a soft match is found, morph\n\t * - otherwise, prepend the new node before the current insertion point\n\t *\n\t * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved\n\t * with the current node. See findIdSetMatch() and findSoftMatch() for details.\n\t *\n\t * @param {Element} newParent the parent element of the new content\n\t * @param {Element } oldParent the old content that we are merging the new content into\n\t * @param ctx the merge context\n\t */\n\tfunction morphChildren(newParent, oldParent, ctx) {\n\n\t\tlet nextNewChild = newParent.firstChild;\n\t\tlet insertionPoint = oldParent.firstChild;\n\t\tlet newChild;\n\n\t\t// run through all the new content\n\t\twhile (nextNewChild) {\n\n\t\t\tnewChild = nextNewChild;\n\t\t\tnextNewChild = newChild.nextSibling;\n\n\t\t\t// if we are at the end of the exiting parent's children, just append\n\t\t\tif (insertionPoint == null) {\n\t\t\t\tif (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n\t\t\t\toldParent.appendChild(newChild);\n\t\t\t\tctx.callbacks.afterNodeAdded(newChild);\n\t\t\t\tremoveIdsFromConsideration(ctx, newChild);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// if the current node has an id set match then morph\n\t\t\tif (isIdSetMatch(newChild, insertionPoint, ctx)) {\n\t\t\t\tmorphOldNodeTo(insertionPoint, newChild, ctx);\n\t\t\t\tinsertionPoint = insertionPoint.nextSibling;\n\t\t\t\tremoveIdsFromConsideration(ctx, newChild);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// otherwise search forward in the existing old children for an id set match\n\t\t\tlet idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n\t\t\t// if we found a potential match, remove the nodes until that point and morph\n\t\t\tif (idSetMatch) {\n\t\t\t\tinsertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);\n\t\t\t\tmorphOldNodeTo(idSetMatch, newChild, ctx);\n\t\t\t\tremoveIdsFromConsideration(ctx, newChild);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// no id set match found, so scan forward for a soft match for the current node\n\t\t\tlet softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n\t\t\t// if we found a soft match for the current node, morph\n\t\t\tif (softMatch) {\n\t\t\t\tinsertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);\n\t\t\t\tmorphOldNodeTo(softMatch, newChild, ctx);\n\t\t\t\tremoveIdsFromConsideration(ctx, newChild);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// abandon all hope of morphing, just insert the new child before the insertion point\n\t\t\t// and move on\n\t\t\tif (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n\t\t\toldParent.insertBefore(newChild, insertionPoint);\n\t\t\tctx.callbacks.afterNodeAdded(newChild);\n\t\t\tremoveIdsFromConsideration(ctx, newChild);\n\t\t}\n\n\t\t// remove any remaining old nodes that didn't match up with new content\n\t\twhile (insertionPoint !== null) {\n\n\t\t\tlet tempNode = insertionPoint;\n\t\t\tinsertionPoint = insertionPoint.nextSibling;\n\t\t\tremoveNode(tempNode, ctx);\n\t\t}\n\t}\n\n\t//=============================================================================\n\t// Attribute Syncing Code\n\t//=============================================================================\n\n\t/**\n\t * @param attr {String} the attribute to be mutated\n\t * @param to {Element} the element that is going to be updated\n\t * @param updateType {(\"update\"|\"remove\")}\n\t * @param ctx the merge context\n\t * @returns {boolean} true if the attribute should be ignored, false otherwise\n\t */\n\tfunction ignoreAttribute(attr, to, updateType, ctx) {\n\t\tif(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){\n\t\t\treturn true;\n\t\t}\n\t\treturn ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;\n\t}\n\n\t/**\n\t * syncs a given node with another node, copying over all attributes and\n\t * inner element state from the 'from' node to the 'to' node\n\t *\n\t * @param {Element} from the element to copy attributes & state from\n\t * @param {Element} to the element to copy attributes & state to\n\t * @param ctx the merge context\n\t */\n\tfunction syncNodeFrom(from, to, ctx) {\n\t\tlet type = from.nodeType\n\n\t\t// if is an element type, sync the attributes from the\n\t\t// new node into the new node\n\t\tif (type === 1 /* element type */) {\n\t\t\tconst fromAttributes = from.attributes;\n\t\t\tconst toAttributes = to.attributes;\n\t\t\tfor (const fromAttribute of fromAttributes) {\n\t\t\t\tif (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {\n\t\t\t\t\tto.setAttribute(fromAttribute.name, fromAttribute.value);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// iterate backwards to avoid skipping over items when a delete occurs\n\t\t\tfor (let i = toAttributes.length - 1; 0 <= i; i--) {\n\t\t\t\tconst toAttribute = toAttributes[i];\n\t\t\t\tif (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!from.hasAttribute(toAttribute.name)) {\n\t\t\t\t\tto.removeAttribute(toAttribute.name);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// sync text nodes\n\t\tif (type === 8 /* comment */ || type === 3 /* text */) {\n\t\t\tif (to.nodeValue !== from.nodeValue) {\n\t\t\t\tto.nodeValue = from.nodeValue;\n\t\t\t}\n\t\t}\n\n\t\tif (!ignoreValueOfActiveElement(to, ctx)) {\n\t\t\t// sync input values\n\t\t\tsyncInputValue(from, to, ctx);\n\t\t}\n\t}\n\n\t/**\n\t * @param from {Element} element to sync the value from\n\t * @param to {Element} element to sync the value to\n\t * @param attributeName {String} the attribute name\n\t * @param ctx the merge context\n\t */\n\tfunction syncBooleanAttribute(from, to, attributeName, ctx) {\n\t\tif (from[attributeName] !== to[attributeName]) {\n\t\t\tlet ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);\n\t\t\tif (!ignoreUpdate) {\n\t\t\t\tto[attributeName] = from[attributeName];\n\t\t\t}\n\t\t\tif (from[attributeName]) {\n\t\t\t\tif (!ignoreUpdate) {\n\t\t\t\t\tto.setAttribute(attributeName, from[attributeName]);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!ignoreAttribute(attributeName, to, 'remove', ctx)) {\n\t\t\t\t\tto.removeAttribute(attributeName);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * NB: many bothans died to bring us information:\n\t *\n\t * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n\t * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n\t *\n\t * @param from {Element} the element to sync the input value from\n\t * @param to {Element} the element to sync the input value to\n\t * @param ctx the merge context\n\t */\n\tfunction syncInputValue(from, to, ctx) {\n\t\tif (from instanceof HTMLInputElement &&\n\t\t\tto instanceof HTMLInputElement &&\n\t\t\tfrom.type !== 'file') {\n\n\t\t\tlet fromValue = from.value;\n\t\t\tlet toValue = to.value;\n\n\t\t\t// sync boolean attributes\n\t\t\tsyncBooleanAttribute(from, to, 'checked', ctx);\n\t\t\tsyncBooleanAttribute(from, to, 'disabled', ctx);\n\n\t\t\tif (!from.hasAttribute('value')) {\n\t\t\t\tif (!ignoreAttribute('value', to, 'remove', ctx)) {\n\t\t\t\t\tto.value = '';\n\t\t\t\t\tto.removeAttribute('value');\n\t\t\t\t}\n\t\t\t} else if (fromValue !== toValue) {\n\t\t\t\tif (!ignoreAttribute('value', to, 'update', ctx)) {\n\t\t\t\t\tto.setAttribute('value', fromValue);\n\t\t\t\t\tto.value = fromValue;\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (from instanceof HTMLOptionElement) {\n\t\t\tsyncBooleanAttribute(from, to, 'selected', ctx)\n\t\t} else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {\n\t\t\tlet fromValue = from.value;\n\t\t\tlet toValue = to.value;\n\t\t\tif (ignoreAttribute('value', to, 'update', ctx)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (fromValue !== toValue) {\n\t\t\t\tto.value = fromValue;\n\t\t\t}\n\t\t\tif (to.firstChild && to.firstChild.nodeValue !== fromValue) {\n\t\t\t\tto.firstChild.nodeValue = fromValue\n\t\t\t}\n\t\t}\n\t}\n\n\t//=============================================================================\n\t// the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n\t//=============================================================================\n\tfunction handleHeadElement(newHeadTag, currentHead, ctx) {\n\n\t\tlet added = []\n\t\tlet removed = []\n\t\tlet preserved = []\n\t\tlet nodesToAppend = []\n\n\t\tlet headMergeStyle = ctx.head.style;\n\n\t\t// put all new head elements into a Map, by their outerHTML\n\t\tlet srcToNewHeadNodes = new Map();\n\t\tfor (const newHeadChild of newHeadTag.children) {\n\t\t\tsrcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n\t\t}\n\n\t\t// for each elt in the current head\n\t\tfor (const currentHeadElt of currentHead.children) {\n\n\t\t\t// If the current head element is in the map\n\t\t\tlet inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n\t\t\tlet isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n\t\t\tlet isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n\t\t\tif (inNewContent || isPreserved) {\n\t\t\t\tif (isReAppended) {\n\t\t\t\t\t// remove the current version and let the new version replace it and re-execute\n\t\t\t\t\tremoved.push(currentHeadElt);\n\t\t\t\t} else {\n\t\t\t\t\t// this element already exists and should not be re-appended, so remove it from\n\t\t\t\t\t// the new content map, preserving it in the DOM\n\t\t\t\t\tsrcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n\t\t\t\t\tpreserved.push(currentHeadElt);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (headMergeStyle === \"append\") {\n\t\t\t\t\t// we are appending and this existing element is not new content\n\t\t\t\t\t// so if and only if it is marked for re-append do we do anything\n\t\t\t\t\tif (isReAppended) {\n\t\t\t\t\t\tremoved.push(currentHeadElt);\n\t\t\t\t\t\tnodesToAppend.push(currentHeadElt);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// if this is a merge, we remove this content since it is not in the new head\n\t\t\t\t\tif (ctx.head.shouldRemove(currentHeadElt) !== false) {\n\t\t\t\t\t\tremoved.push(currentHeadElt);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Push the remaining new head elements in the Map into the\n\t\t// nodes to append to the head tag\n\t\tnodesToAppend.push(...srcToNewHeadNodes.values());\n\t\tlog(\"to append: \", nodesToAppend);\n\n\t\tlet promises = [];\n\t\tfor (const newNode of nodesToAppend) {\n\t\t\tlog(\"adding: \", newNode);\n\t\t\tlet newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;\n\t\t\tlog(newElt);\n\t\t\tif (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n\t\t\t\tif (newElt.href || newElt.src) {\n\t\t\t\t\tlet resolve = null;\n\t\t\t\t\tlet promise = new Promise(function (_resolve) {\n\t\t\t\t\t\tresolve = _resolve;\n\t\t\t\t\t});\n\t\t\t\t\tnewElt.addEventListener('load', function () {\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t});\n\t\t\t\t\tpromises.push(promise);\n\t\t\t\t}\n\t\t\t\tcurrentHead.appendChild(newElt);\n\t\t\t\tctx.callbacks.afterNodeAdded(newElt);\n\t\t\t\tadded.push(newElt);\n\t\t\t}\n\t\t}\n\n\t\t// remove all removed elements, after we have appended the new elements to avoid\n\t\t// additional network requests for things like style sheets\n\t\tfor (const removedElement of removed) {\n\t\t\tif (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n\t\t\t\tcurrentHead.removeChild(removedElement);\n\t\t\t\tctx.callbacks.afterNodeRemoved(removedElement);\n\t\t\t}\n\t\t}\n\n\t\tctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});\n\t\treturn promises;\n\t}\n\n\t//=============================================================================\n\t// Misc\n\t//=============================================================================\n\n\tfunction log() {\n\t\t//console.log(arguments);\n\t}\n\n\tfunction noOp() {\n\t}\n\n\t/*\n\t Deep merges the config object and the Idiomoroph.defaults object to\n\t produce a final configuration object\n\t */\n\tfunction mergeDefaults(config) {\n\t\tlet finalConfig = {};\n\t\t// copy top level stuff into final config\n\t\tObject.assign(finalConfig, defaults);\n\t\tObject.assign(finalConfig, config);\n\n\t\t// copy callbacks into final config (do this to deep merge the callbacks)\n\t\tfinalConfig.callbacks = {};\n\t\tObject.assign(finalConfig.callbacks, defaults.callbacks);\n\t\tObject.assign(finalConfig.callbacks, config.callbacks);\n\n\t\t// copy head config into final config (do this to deep merge the head)\n\t\tfinalConfig.head = {};\n\t\tObject.assign(finalConfig.head, defaults.head);\n\t\tObject.assign(finalConfig.head, config.head);\n\t\treturn finalConfig;\n\t}\n\n\tfunction createMorphContext(oldNode, newContent, config) {\n\t\tconfig = mergeDefaults(config);\n\t\treturn {\n\t\t\ttarget: oldNode,\n\t\t\tnewContent: newContent,\n\t\t\tconfig: config,\n\t\t\tmorphStyle: config.morphStyle,\n\t\t\tignoreActive: config.ignoreActive,\n\t\t\tignoreActiveValue: config.ignoreActiveValue,\n\t\t\tidMap: createIdMap(oldNode, newContent),\n\t\t\tdeadIds: new Set(),\n\t\t\tcallbacks: config.callbacks,\n\t\t\thead: config.head\n\t\t}\n\t}\n\n\tfunction isIdSetMatch(node1, node2, ctx) {\n\t\tif (node1 == null || node2 == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {\n\t\t\tif (node1.id !== \"\" && node1.id === node2.id) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn getIdIntersectionCount(ctx, node1, node2) > 0;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tfunction isSoftMatch(node1, node2) {\n\t\tif (node1 == null || node2 == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn node1.nodeType === node2.nodeType && node1.tagName === node2.tagName\n\t}\n\n\tfunction removeNodesBetween(startInclusive, endExclusive, ctx) {\n\t\twhile (startInclusive !== endExclusive) {\n\t\t\tlet tempNode = startInclusive;\n\t\t\tstartInclusive = startInclusive.nextSibling;\n\t\t\tremoveNode(tempNode, ctx);\n\t\t}\n\t\tremoveIdsFromConsideration(ctx, endExclusive);\n\t\treturn endExclusive.nextSibling;\n\t}\n\n\t//=============================================================================\n\t// Scans forward from the insertionPoint in the old parent looking for a potential id match\n\t// for the newChild. We stop if we find a potential id match for the new child OR\n\t// if the number of potential id matches we are discarding is greater than the\n\t// potential id matches for the new child\n\t//=============================================================================\n\tfunction findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n\t\t// max id matches we are willing to discard in our search\n\t\tlet newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);\n\n\t\tlet potentialMatch = null;\n\n\t\t// only search forward if there is a possibility of an id match\n\t\tif (newChildPotentialIdCount > 0) {\n\t\t\tlet potentialMatch = insertionPoint;\n\t\t\t// if there is a possibility of an id match, scan forward\n\t\t\t// keep track of the potential id match count we are discarding (the\n\t\t\t// newChildPotentialIdCount must be greater than this to make it likely\n\t\t\t// worth it)\n\t\t\tlet otherMatchCount = 0;\n\t\t\twhile (potentialMatch != null) {\n\n\t\t\t\t// If we have an id match, return the current potential match\n\t\t\t\tif (isIdSetMatch(newChild, potentialMatch, ctx)) {\n\t\t\t\t\treturn potentialMatch;\n\t\t\t\t}\n\n\t\t\t\t// computer the other potential matches of this new content\n\t\t\t\totherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);\n\t\t\t\tif (otherMatchCount > newChildPotentialIdCount) {\n\t\t\t\t\t// if we have more potential id matches in _other_ content, we\n\t\t\t\t\t// do not have a good candidate for an id match, so return null\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\n\t\t\t\t// advanced to the next old content child\n\t\t\t\tpotentialMatch = potentialMatch.nextSibling;\n\t\t\t}\n\t\t}\n\t\treturn potentialMatch;\n\t}\n\n\t//=============================================================================\n\t// Scans forward from the insertionPoint in the old parent looking for a potential soft match\n\t// for the newChild. We stop if we find a potential soft match for the new child OR\n\t// if we find a potential id match in the old parents children OR if we find two\n\t// potential soft matches for the next two pieces of new content\n\t//=============================================================================\n\tfunction findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n\t\tlet potentialSoftMatch = insertionPoint;\n\t\tlet nextSibling = newChild.nextSibling;\n\t\tlet siblingSoftMatchCount = 0;\n\n\t\twhile (potentialSoftMatch != null) {\n\n\t\t\tif (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {\n\t\t\t\t// the current potential soft match has a potential id set match with the remaining new\n\t\t\t\t// content so bail out of looking\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\t// if we have a soft match with the current node, return it\n\t\t\tif (isSoftMatch(newChild, potentialSoftMatch)) {\n\t\t\t\treturn potentialSoftMatch;\n\t\t\t}\n\n\t\t\tif (isSoftMatch(nextSibling, potentialSoftMatch)) {\n\t\t\t\t// the next new node has a soft match with this node, so\n\t\t\t\t// increment the count of future soft matches\n\t\t\t\tsiblingSoftMatchCount++;\n\t\t\t\tnextSibling = nextSibling.nextSibling;\n\n\t\t\t\t// If there are two future soft matches, bail to allow the siblings to soft match\n\t\t\t\t// so that we don't consume future soft matches for the sake of the current node\n\t\t\t\tif (siblingSoftMatchCount >= 2) {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// advanced to the next old content child\n\t\t\tpotentialSoftMatch = potentialSoftMatch.nextSibling;\n\t\t}\n\n\t\treturn potentialSoftMatch;\n\t}\n\n\tfunction parseContent(newContent) {\n\t\tlet parser = new DOMParser();\n\n\t\t// remove svgs to avoid false-positive matches on head, etc.\n\t\tlet contentWithSvgsRemoved = newContent.replace(/]*>|>)([\\s\\S]*?)<\\/svg>/gim, '');\n\n\t\t// if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n\t\tif (contentWithSvgsRemoved.match(/<\\/html>/) || contentWithSvgsRemoved.match(/<\\/head>/) || contentWithSvgsRemoved.match(/<\\/body>/)) {\n\t\t\tlet content = parser.parseFromString(newContent, \"text/html\");\n\t\t\t// if it is a full HTML document, return the document itself as the parent container\n\t\t\tif (contentWithSvgsRemoved.match(/<\\/html>/)) {\n\t\t\t\tcontent.generatedByIdiomorph = true;\n\t\t\t\treturn content;\n\t\t\t} else {\n\t\t\t\t// otherwise return the html element as the parent container\n\t\t\t\tlet htmlElement = content.firstChild;\n\t\t\t\tif (htmlElement) {\n\t\t\t\t\thtmlElement.generatedByIdiomorph = true;\n\t\t\t\t\treturn htmlElement;\n\t\t\t\t} else {\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\t// if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n\t\t\t// deal with touchy tags like tr, tbody, etc.\n\t\t\tlet responseDoc = parser.parseFromString(\"\", \"text/html\");\n\t\t\tlet content = responseDoc.body.querySelector('template').content;\n\t\t\tcontent.generatedByIdiomorph = true;\n\t\t\treturn content\n\t\t}\n\t}\n\n\tfunction normalizeContent(newContent) {\n\t\tif (newContent == null) {\n\t\t\t// noinspection UnnecessaryLocalVariableJS\n\t\t\tconst dummyParent = document.createElement('div');\n\t\t\treturn dummyParent;\n\t\t} else if (newContent.generatedByIdiomorph) {\n\t\t\t// the template tag created by idiomorph parsing can serve as a dummy parent\n\t\t\treturn newContent;\n\t\t} else if (newContent instanceof Node) {\n\t\t\t// a single node is added as a child to a dummy parent\n\t\t\tconst dummyParent = document.createElement('div');\n\t\t\tdummyParent.append(newContent);\n\t\t\treturn dummyParent;\n\t\t} else {\n\t\t\t// all nodes in the array or HTMLElement collection are consolidated under\n\t\t\t// a single dummy parent element\n\t\t\tconst dummyParent = document.createElement('div');\n\t\t\tfor (const elt of [...newContent]) {\n\t\t\t\tdummyParent.append(elt);\n\t\t\t}\n\t\t\treturn dummyParent;\n\t\t}\n\t}\n\n\tfunction insertSiblings(previousSibling, morphedNode, nextSibling) {\n\t\tlet stack = []\n\t\tlet added = []\n\t\twhile (previousSibling != null) {\n\t\t\tstack.push(previousSibling);\n\t\t\tpreviousSibling = previousSibling.previousSibling;\n\t\t}\n\t\twhile (stack.length > 0) {\n\t\t\tlet node = stack.pop();\n\t\t\tadded.push(node); // push added preceding siblings on in order and insert\n\t\t\tmorphedNode.parentElement.insertBefore(node, morphedNode);\n\t\t}\n\t\tadded.push(morphedNode);\n\t\twhile (nextSibling != null) {\n\t\t\tstack.push(nextSibling);\n\t\t\tadded.push(nextSibling); // here we are going in order, so push on as we scan, rather than add\n\t\t\tnextSibling = nextSibling.nextSibling;\n\t\t}\n\t\twhile (stack.length > 0) {\n\t\t\tmorphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);\n\t\t}\n\t\treturn added;\n\t}\n\n\tfunction findBestNodeMatch(newContent, oldNode, ctx) {\n\t\tlet currentElement;\n\t\tcurrentElement = newContent.firstChild;\n\t\tlet bestElement = currentElement;\n\t\tlet score = 0;\n\t\twhile (currentElement) {\n\t\t\tlet newScore = scoreElement(currentElement, oldNode, ctx);\n\t\t\tif (newScore > score) {\n\t\t\t\tbestElement = currentElement;\n\t\t\t\tscore = newScore;\n\t\t\t}\n\t\t\tcurrentElement = currentElement.nextSibling;\n\t\t}\n\t\treturn bestElement;\n\t}\n\n\tfunction scoreElement(node1, node2, ctx) {\n\t\tif (isSoftMatch(node1, node2)) {\n\t\t\treturn .5 + getIdIntersectionCount(ctx, node1, node2);\n\t\t}\n\t\treturn 0;\n\t}\n\n\tfunction removeNode(tempNode, ctx) {\n\t\tremoveIdsFromConsideration(ctx, tempNode)\n\t\tif (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;\n\n\t\ttempNode.remove();\n\t\tctx.callbacks.afterNodeRemoved(tempNode);\n\t}\n\n\t//=============================================================================\n\t// ID Set Functions\n\t//=============================================================================\n\n\tfunction isIdInConsideration(ctx, id) {\n\t\treturn !ctx.deadIds.has(id);\n\t}\n\n\tfunction idIsWithinNode(ctx, id, targetNode) {\n\t\tlet idSet = ctx.idMap.get(targetNode) || EMPTY_SET;\n\t\treturn idSet.has(id);\n\t}\n\n\tfunction removeIdsFromConsideration(ctx, node) {\n\t\tlet idSet = ctx.idMap.get(node) || EMPTY_SET;\n\t\tfor (const id of idSet) {\n\t\t\tctx.deadIds.add(id);\n\t\t}\n\t}\n\n\tfunction getIdIntersectionCount(ctx, node1, node2) {\n\t\tlet sourceSet = ctx.idMap.get(node1) || EMPTY_SET;\n\t\tlet matchCount = 0;\n\t\tfor (const id of sourceSet) {\n\t\t\t// a potential match is an id in the source and potentialIdsSet, but\n\t\t\t// that has not already been merged into the DOM\n\t\t\tif (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {\n\t\t\t\t++matchCount;\n\t\t\t}\n\t\t}\n\t\treturn matchCount;\n\t}\n\n\t/**\n\t * A bottom up algorithm that finds all elements with ids inside of the node\n\t * argument and populates id sets for those nodes and all their parents, generating\n\t * a set of ids contained within all nodes for the entire hierarchy in the DOM\n\t *\n\t * @param node {Element}\n\t * @param {Map>} idMap\n\t */\n\tfunction populateIdMapForNode(node, idMap) {\n\t\tlet nodeParent = node.parentElement;\n\t\t// find all elements with an id property\n\t\tlet idElements = node.querySelectorAll('[id]');\n\t\tfor (const elt of idElements) {\n\t\t\tlet current = elt;\n\t\t\t// walk up the parent hierarchy of that element, adding the id\n\t\t\t// of element to the parent's id set\n\t\t\twhile (current !== nodeParent && current != null) {\n\t\t\t\tlet idSet = idMap.get(current);\n\t\t\t\t// if the id set doesn't exist, create it and insert it in the map\n\t\t\t\tif (idSet == null) {\n\t\t\t\t\tidSet = new Set();\n\t\t\t\t\tidMap.set(current, idSet);\n\t\t\t\t}\n\t\t\t\tidSet.add(elt.id);\n\t\t\t\tcurrent = current.parentElement;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This function computes a map of nodes to all ids contained within that node (inclusive of the\n\t * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n\t * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n\t * to contribute to a parent nodes matching.\n\t *\n\t * @param {Element} oldContent the old content that will be morphed\n\t * @param {Element} newContent the new content to morph to\n\t * @returns {Map>} a map of nodes to id sets for the\n\t */\n\tfunction createIdMap(oldContent, newContent) {\n\t\tlet idMap = new Map();\n\t\tpopulateIdMapForNode(oldContent, idMap);\n\t\tpopulateIdMapForNode(newContent, idMap);\n\t\treturn idMap;\n\t}\n\n\t//=============================================================================\n\t// This is what ends up becoming the Idiomorph global object\n\t//=============================================================================\n\treturn {\n\t\tmorph,\n\t\tdefaults\n\t}\n})();\n","const customEvent = (() => {\n\treturn ('CustomEvent' in window && typeof window.CustomEvent === 'function')\n\t\t? (name, data) => new CustomEvent(name, data)\n\t\t: (name, data) => {\n\t\t\tconst newEvent = document.createEvent('CustomEvent')\n\t\t\tnewEvent.initCustomEvent(name, true, true, data)\n\t\t\treturn newEvent\n\t\t}\n})()\n\nconst handler = (node, ev) => {\n\treturn function (e) {\n\t\tconst scope = this\n\t\tconst detail = e.detail || {}\n\t\tnode.__events[ev].forEach(o => {\n\t\t\to.handler.apply(scope, [e].concat(detail.args))\n\t\t})\n\t}\n}\n\nconst removeListener = (node, ev) => {\n\tif (node.__events[ev] && node.__events[ev].listener) {\n\t\tnode.removeEventListener(\n\t\t\tev,\n\t\t\tnode.__events[ev].listener,\n\t\t\t(ev == 'focus' || ev == 'blur' || ev == 'mouseenter' || ev == 'mouseleave'))\n\t\tdelete node.__events[ev]\n\t}\n}\n\nconst delegate = (node, selector, callback) => {\n\treturn function (e) {\n\n\t\tconst element = this\n\t\tconst detail = e.detail || {}\n\n\t\tlet parent = e.target\n\n\t\twhile (parent) {\n\t\t\tif (parent.matches(selector)) {\n\t\t\t\te.delegateTarget = parent\n\t\t\t\tcallback.apply(element, [e].concat(detail.args))\n\t\t\t}\n\t\t\tif (parent === node) break\n\t\t\tparent = parent.parentNode\n\t\t}\n\t}\n}\n\nexport const on = (node, ev, selectorOrCallback, callback) => {\n\n\tnode.__events = node.__events || {}\n\tnode.__events[ev] = (node.__events[ev] || [])\n\n\tif (!node.__events[ev].length) {\n\t\tconst fn = handler(node, ev)\n\t\tnode.addEventListener(\n\t\t\tev,\n\t\t\tfn,\n\t\t\t(ev == 'focus' || ev == 'blur' || ev == 'mouseenter' || ev == 'mouseleave'))\n\t\tnode.__events[ev].listener = fn\n\t}\n\n\tif (selectorOrCallback.call) {\n\t\tnode.__events[ev].push({ handler: selectorOrCallback, callback: selectorOrCallback })\n\t} else {\n\t\tnode.__events[ev].push({ handler: delegate(node, selectorOrCallback, callback), callback })\n\t}\n}\n\nexport const off = (node, ev, fn) => {\n\n\tif (fn && node.__events[ev] && node.__events[ev].length) {\n\t\tvar old = node.__events[ev]\n\t\tnode.__events[ev] = node.__events[ev].filter(function (o) { return o.callback != fn; })\n\t\tnode.__events[ev].listener = old.listener\n\t\tif (!node.__events[ev].length)\n\t\t\tremoveListener(node, ev)\n\t} else {\n\t\tremoveListener(node, ev)\n\t}\n}\n\nexport const trigger = (node, name, args) => {\n\tnode.dispatchEvent(customEvent(name, { bubbles: true, detail: args }))\n}\n","import { type Component } from '..'\nimport { Idiomorph } from './utils/idiomorph'\nimport { rAF, dup, safe } from './utils'\nimport { buildtemplates } from './template-system'\nimport { on, off, trigger } from './utils/events'\nimport { publish, subscribe } from './utils/pubsub'\n\nexport default function Component( elm, { module, dependencies, templates, components }) {\n\n\tconst options = getOptions( module )\n\tconst initialState = (new Function( `return ${elm.getAttribute('html-model') || '{}'}`))()\n\tconst selector = Object.keys(components).toString()\n\n\tbuildtemplates( elm, selector, templates, components )\n\n\tconst tplid = elm.getAttribute('tplid')\n\tconst template = tplid ? templates[tplid] : null\n\tconst state = { data: module.model ? dup(module.model) : {} }\n\tstate.data = Object.assign( state.data, initialState)\n\n\tconst base: Component = {\n\t\ttemplate,\n\t\telm,\n\t\tdependencies,\n\t\tpublish,\n\t\tsubscribe,\n\n\t\tmain(fn) {\n\t\t\toptions.main = fn\n\t\t},\n\n\t\tunmount(fn) {\n\t\t\toptions.unmount = fn\n\t\t},\n\n\t\tonupdate(fn) {\n\t\t\toptions.onupdate = fn\n\t\t},\n\n\t\ton(eventName, selectorOrCallback, callback) {\n\t\t\ton(elm, eventName, selectorOrCallback, callback)\n\t\t},\n\n\t\toff(eventName, callback) {\n\t\t\toff(elm, eventName, callback)\n\t\t},\n\n\t\ttrigger(eventName, target, args) {\n\t\t\tif (target.constructor === String) {\n\t\t\t\tArray\n\t\t\t\t\t.from(elm.querySelectorAll(target))\n\t\t\t\t\t.forEach( children => trigger(children, eventName, { args: args }) )\n\t\t\t}\n\t\t\telse trigger(elm, eventName, { args: target })\n\t\t},\n\n\t\temit: ( ...args ) => {\n\t\t\ttrigger(elm, args.shift(), { args: args })\n\t\t},\n\n\t\tstate: {\n\t\t\tset( data ) {\n\t\t\t\tif (data.constructor === Function) {\n\t\t\t\t\tconst newstate = dup(state.data)\n\t\t\t\t\tdata(newstate)\n\t\t\t\t\tbase.render(newstate)\n\t\t\t\t} else {\n\t\t\t\t\tbase.render(data)\n\t\t\t\t}\n\t\t\t\treturn new Promise((resolve) => rAF(_ => rAF(() => resolve(state.data))))\n\t\t\t},\n\t\t\tget() {\n\t\t\t\treturn dup(state.data)\n\t\t\t},\n\n\t\t\tgetRaw(){\n\t\t\t\treturn state.data\n\t\t\t}\n\t\t},\n\n\t\trender(data = state.data) {\n\n\t\t\tif (!document.body.contains(elm)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstate.data = Object.assign(state.data, data)\n\n\t\t\tconst newdata = dup(state.data)\n\t\t\tconst newhtml = templates[tplid].call(Object.assign(options.view(newdata), elm.___scope___), elm, safe)\n\n\t\t\tIdiomorph.morph(elm, newhtml, IdiomorphOptions(elm))\n\t\t\tupdateScope( elm )\n\n\t\t\trAF(_ => {\n\t\t\t\tArray\n\t\t\t\t\t.from(elm.querySelectorAll('[tplid]'))\n\t\t\t\t\t.forEach((child: any) => {\n\t\t\t\t\t\tconst props = Object.assign( child.base.state.getRaw(), data )\n\t\t\t\t\t\tchild.options.onupdate(props)\n\t\t\t\t\t\tchild.base.render(props)\n\t\t\t\t\t})\n\t\t\t})\n\t\t},\n\n\t\tinnerHTML( target, html_ ) {\n\n\t\t\tconst element = html_? target : elm\n\t\t\tconst clone = element.cloneNode()\n\t\t\tconst html = html_? html_ : target\n\t\t\tclone.innerHTML = html\n\n\t\t\trAF( _ => Idiomorph.morph(element, clone, IdiomorphOptions) )\n\t\t}\n\t}\n\n\treturn { base, options }\n}\n\nconst getOptions = (module) => ({\n\tmain: (a) => a,\n\tunmount: (a) => a,\n\tonupdate: (a) => a,\n\tview: module.view ? module.view : (a) => a\n})\n\nconst updateScope = (node) => {\n\tnode.querySelectorAll('[scope]').forEach( scopeElement => {\n\t\tscopeElement.querySelectorAll('[tplid]').forEach( cp => {\n\t\t\tif( !cp.___scope___ ) {\n\t\t\t\tconst script = scopeElement.lastElementChild\n\t\t\t\tcp.___scope___ = 'scope' in script.dataset? (new Function(`return ${script.text}`))() : {}\n\t\t\t}\n\t\t})\n\t})\n}\n\n\nconst IdiomorphOptions = (parent) => ({\n\n\tcallbacks: {\n\n\t\tbeforeNodeMorphed( node ) {\n\t\t\tif( node.nodeType === 1 ) {\n\t\t\t\tif( 'html-static' in node.attributes ) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif( node.base && node !== parent ) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n})\n","import Component from './component'\nimport { purge, rAF } from './utils'\n\nexport default function Element(module, dependencies, templates, components) {\n\treturn class extends HTMLElement {\n\n\t\tbase: any\n\t\toptions: any\n\t\treturns : any\n\t\t__events: any\n\n\t\tconstructor() {\n\n\t\t\tsuper()\n\t\t\tconst { base, options } = Component(this, { module, dependencies, templates, components })\n\n\t\t\tthis.base = base\n\t\t\tthis.options = options\n\t\t\tthis.returns = module.default(base)\n\t\t}\n\n\t\tconnectedCallback() {\n\n\t\t\tthis.base.render()\n\n\t\t\tif( this.__template && this.__template.constructor === Promise ) {\n\t\t\t\tthis.__template.then( _ => {\n\t\t\t\t\tif( this.base && this.options.main) {\n\t\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\t\tif( array && array.length ){\n\t\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif( this.returns && this.returns.constructor === Promise ) {\n\t\t\t\tthis.returns.then( _ => {\n\t\t\t\t\tif( this.base && this.options.main) {\n\t\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\t\tif( array && array.length ){\n\t\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}else {\n\t\t\t\tif( this.base && this.options.main ){\n\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\tif( array && array.length ) {\n\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdisconnectedCallback() {\n\t\t\tthis.options.unmount(this.base)\n\t\t\trAF(() => {\n\t\t\t\tif(!document.body.contains(this) ) {\n\t\t\t\t\tthis.__events? this.__events = null : null\n\t\t\t\t\tthis.base? this.base.elm = null : null\n\t\t\t\t\tthis.base? this.base = null : null\n\t\t\t\t\tpurge(this)\n\t\t\t\t}\n\t\t\t})\n\n\t\t}\n\n\t\tattributeChangedCallback() {\n\t\t\t//TODO\n\t\t}\n\t}\n}\n","import { templateConfig, buildtemplates } from './template-system'\nimport { publish, subscribe } from './utils/pubsub'\nimport { html } from './utils'\nimport Element from './element'\n\nconst templates = {}\nconst components = {}\n\nexport { html }\n\nexport default {\n\n\ttemplateConfig,\n\n\tpublish,\n\tsubscribe,\n\n\tregister( name, module, dependencies = {} ) {\n\t\tcomponents[name] = { name, module, dependencies }\n\t},\n\n\tstart( target = document.body ) {\n\t\tconst keys = Object.keys(components)\n\t\tconst selector = keys.toString()\n\t\tif( keys.length ) {\n\t\t\tbuildtemplates( target, selector, templates, components )\n\t\t\tregisterComponents()\n\t\t}\n\t}\n}\n\nconst registerComponents = () => {\n\tObject\n\t\t.values( components )\n\t\t.forEach( (component) => {\n\t\t\tconst { name, module, dependencies } = component as any\n\t\t\tif( !customElements.get(name) ){\n\t\t\t\tconst Base = Element(module, dependencies, templates, components)\n\t\t\t\tcustomElements.define(name, Base)\n\t\t\t}\n\t\t})\n}\n"],"names":["parser","DOMParser","wrap","open","node","close","_a","parentNode","insertBefore","_b","nextSibling","textarea","document","createElement","decodeHTML","text","innerHTML","value","rAF","fn","requestAnimationFrame","setTimeout","dup","o","JSON","parse","stringify","purge","d","i","l","n","a","attributes","length","name","childNodes","safe","execute","val","err","config","tags","Template","element","html","regexTags","RegExp","virtual","parseFromString","replace","querySelectorAll","forEach","htmlForeach","getAttribute","htmlFor","htmlIf","htmlInner","htmlClass","forEachInstruction","selector","split","match","varname","object","removeAttribute","setAttribute","script","dataset","scope","type","appendChild","createTextNode","className","trim","body","all","key","Transpile","outerHTML","decodedHTML","Function","_","variable","buildtemplates","target","templates","components","concat","matches","Array","from","reverse","template","content","createTemplateId","id","c","r","Math","random","toString","localName","module","constructor","Promise","__template","then","htmlstring","topics","_async","publish","params","Object","assign","topic","subscribe","method","push","filter","Idiomorph","EMPTY_SET","Set","defaults","morphStyle","callbacks","beforeNodeAdded","noOp","afterNodeAdded","beforeNodeMorphed","afterNodeMorphed","beforeNodeRemoved","afterNodeRemoved","beforeAttributeUpdated","head","style","shouldPreserve","elt","shouldReAppend","shouldRemove","afterHeadMorphed","morphNormalizedContent","oldNode","normalizedNewContent","ctx","block","oldHead","querySelector","newHead","promises","handleHeadElement","ignore","morphChildren","children","bestMatch","newContent","currentElement","firstChild","bestElement","score","newScore","scoreElement","findBestNodeMatch","previousSibling","morphedNode","morphOldNodeTo","stack","added","pop","parentElement","insertSiblings","ignoreValueOfActiveElement","possibleActiveElement","ignoreActiveValue","activeElement","ignoreActive","remove","isSoftMatch","HTMLHeadElement","to","nodeType","fromAttributes","toAttributes","fromAttribute","ignoreAttribute","toAttribute","hasAttribute","nodeValue","HTMLInputElement","fromValue","toValue","syncBooleanAttribute","HTMLOptionElement","HTMLTextAreaElement","syncInputValue","syncNodeFrom","replaceChild","newParent","oldParent","newChild","nextNewChild","insertionPoint","removeIdsFromConsideration","isIdSetMatch","idSetMatch","findIdSetMatch","removeNodesBetween","softMatch","findSoftMatch","tempNode","removeNode","attr","updateType","attributeName","ignoreUpdate","newHeadTag","currentHead","removed","preserved","nodesToAppend","headMergeStyle","srcToNewHeadNodes","Map","newHeadChild","set","currentHeadElt","inNewContent","has","isReAppended","isPreserved","delete","values","newNode","newElt","createRange","createContextualFragment","href","src","resolve","promise","_resolve","addEventListener","removedElement","removeChild","kept","node1","node2","tagName","getIdIntersectionCount","startInclusive","endExclusive","newChildPotentialIdCount","potentialMatch","otherMatchCount","potentialSoftMatch","siblingSoftMatchCount","isIdInConsideration","deadIds","idIsWithinNode","targetNode","idMap","get","idSet","add","sourceSet","matchCount","populateIdMapForNode","nodeParent","idElements","current","createIdMap","oldContent","morph","Document","documentElement","contentWithSvgsRemoved","generatedByIdiomorph","htmlElement","parseContent","normalizedContent","Node","dummyParent","append","normalizeContent","finalConfig","mergeDefaults","createMorphContext","customEvent","window","CustomEvent","data","newEvent","createEvent","initCustomEvent","handler","ev","e","this","detail","__events","apply","args","removeListener","listener","removeEventListener","delegate","callback","parent","delegateTarget","on","selectorOrCallback","call","off","old","trigger","dispatchEvent","bubbles","getOptions","main","unmount","onupdate","view","updateScope","scopeElement","cp","___scope___","lastElementChild","IdiomorphOptions","base","Element","dependencies","HTMLElement","options","elm","initialState","keys","tplid","state","model","eventName","String","emit","shift","newstate","render","getRaw","contains","newdata","newhtml","child","props","html_","clone","cloneNode","Component","returns","default","connectedCallback","array","f","disconnectedCallback","attributeChangedCallback","index","templateConfig","newconfig","register","start","registerComponents","component","customElements","Base","define","literalSections","substs","raw","result","subst","lit","isArray","join"],"mappings":"6OAAM,MAAAA,EAAS,IAAIC,UA0EnB,MAAMC,EAAO,CAACC,EAAMC,EAAMC,aACpB,OAAAC,EAAAF,EAAAG,aAAYD,EAAAE,aAAaL,EAAMC,GACpC,OAAAK,EAAAL,EAAKG,aAALE,EAAiBD,aAAaH,EAAOD,EAAKM,YAAA,EC5ErCC,EAAWC,SAASC,cAAc,YAE3BC,EAAcC,IAC1BJ,EAASK,UAAYD,EACdJ,EAASM,OAGJC,EAAOC,GACfC,sBACIA,sBAAsBD,GAEtBE,WAAWF,EAAI,IAAO,IAWlBG,EAAOC,GACZC,KAAKC,MAAMD,KAAKE,UAAUH,IAIrBI,EAASC,IACrB,IAAsBC,EAAGC,EAAGC,EAAxBC,EAAIJ,EAAEK,WACV,GAAID,EACH,IAAKH,EAAIG,EAAEE,OAAS,EAAGL,GAAK,EAAGA,GAAK,EAEf,mBAATD,EADPG,EAAAC,EAAEH,GAAGM,QAERP,EAAEG,GAAK,MAKV,GADAC,EAAIJ,EAAEQ,WAGL,I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EAAIzV,GAKV6D,MAAMgS,QAAQF,KACTA,EAAAA,EAAMG,KAAK,KAGVJ,GAAAE,EACAF,GAAAC,CAAA,IAKDD,GAAAD,EAAIA,EAAIpV,OAAO,GAElBqV,CAAA"} \ No newline at end of file +{"version":3,"file":"jails.js","sources":["../src/transpile.ts","../src/utils/index.ts","../src/template-system.ts","../src/utils/pubsub.ts","../node_modules/idiomorph/dist/idiomorph.esm.js","../src/utils/events.ts","../src/component.ts","../src/element.ts","../src/index.ts"],"sourcesContent":["const parser = new DOMParser()\n\nexport default function Transpile(html, config) {\n\n\tconst regexTags = new RegExp(`\\\\${config.tags[0]}(.+?)\\\\${config.tags[1]}`, 'g')\n\tconst virtual = parser.parseFromString(html.replace(/<\\/?template[^>]*>/g, ''), 'text/html')\n\n\tvirtual.querySelectorAll('[html-for], [html-if], [html-inner], [html-class], [html-model]').forEach((element) => {\n\n\t\tconst htmlForeach = element.getAttribute('html-foreach')\n\t\tconst htmlFor \t= element.getAttribute('html-for')\n\t\tconst htmlIf \t= element.getAttribute('html-if')\n\t\tconst htmlInner = element.getAttribute('html-inner')\n\t\tconst htmlClass = element.getAttribute('html-class')\n\t\tconst forEachInstruction = htmlFor || htmlForeach\n\n\t\tif ( forEachInstruction ) {\n\t\t\tconst selector = htmlFor? 'html-for': 'html-foreach'\n\t\t\tconst split = forEachInstruction.match(/(.*)\\sin\\s(.*)/) || ''\n\t\t\tconst varname = split[1]\n\t\t\tconst object = split[2]\n\n\t\t\telement.removeAttribute(selector)\n\t\t\telement.setAttribute('scope', '')\n\t\t\tconst script = document.createElement('script')\n\n\t\t\tscript.dataset.scope = ''\n\t\t\tscript.type = 'text/html'\n\t\t\tscript.text = `%%_= $scope _%%`\n\n\t\t\telement.appendChild( script )\n\n\t\t\tconst open = document.createTextNode(`%%_(function(){ var $index = 0; for(var $key in safe(function(){ return ${object} }) ){ var ${varname} = ${object}[$key]; var $scope = JSON.stringify({ '${varname}':${varname}, $index: $index, $key:$key }); _%%`)\n\t\t\tconst close = document.createTextNode(`%%_ $index++; } })() _%%`)\n\t\t\twrap(open, element, close)\n\t\t}\n\t\tif (htmlIf) {\n\t\t\telement.removeAttribute('html-if')\n\t\t\tconst open = document.createTextNode(`%%_ if ( safe(function(){ return ${htmlIf} }) ){ _%%`)\n\t\t\tconst close = document.createTextNode(`%%_ } _%%`)\n\t\t\twrap(open, element, close)\n\t\t}\n\t\tif (htmlInner) {\n\t\t\telement.removeAttribute('html-inner')\n\t\t\telement.innerHTML = `%%_=${htmlInner}_%%`\n\t\t}\n\t\tif (htmlClass) {\n\t\t\telement.removeAttribute('html-class')\n\t\t\telement.className = (element.className + ` %%_=${htmlClass}_%%`).trim()\n\t\t}\n\t})\n\n\n\treturn (\n\t\tvirtual.body.innerHTML\n\t\t\t.replace(regexTags, '%%_=$1_%%')\n\t\t\t// Booleans\n\t\t\t// https://meiert.com/en/blog/boolean-attributes-of-html/\n\t\t\t.replace(/html-(allowfullscreen|async|autofocus|autoplay|checked|controls|default|defer|disabled|formnovalidate|inert|ismap|itemscope|loop|multiple|muted|nomodule|novalidate|open|playsinline|readonly|required|reversed|selected)=\\\"(.*?)\\\"/g, `%%_if(safe(function(){ return $2 })){_%%$1%%_}_%%`)\n\t\t\t// The rest\n\t\t\t.replace(/html-(.*?)=\\\"(.*?)\\\"/g, (all, key, value) => {\n\t\t\t\tif (key === 'key' || key === 'model' || key == 'scope') {\n\t\t\t\t\treturn all\n\t\t\t\t}\n\t\t\t\tif (value) {\n\t\t\t\t\tvalue = value.replace(/^{|}$/g, '')\n\t\t\t\t\treturn `${key}=\"%%_=safe(function(){ return ${value} })_%%\"`\n\t\t\t\t} else {\n\t\t\t\t\treturn all\n\t\t\t\t}\n\t\t\t})\n\t)\n}\n\nconst wrap = (open, node, close) => {\n\tnode.parentNode?.insertBefore(open, node)\n\tnode.parentNode?.insertBefore(close, node.nextSibling)\n}\n","const textarea = document.createElement('textarea')\n\nexport const decodeHTML = (text) => {\n\ttextarea.innerHTML = text\n\treturn textarea.value\n}\n\nexport const rAF = (fn) => {\n\tif (requestAnimationFrame)\n\t\treturn requestAnimationFrame(fn)\n\telse\n\t\treturn setTimeout(fn, 1000 / 60)\n}\n\nexport const uuid = () => {\n\treturn 'xxxxxxxx'.replace(/[xy]/g, (c) => {\n\t\tconst r = Math.random() * 8 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8)\n\t\treturn v.toString(8)\n\t})\n}\n\n\nexport const dup = (o) => {\n\treturn JSON.parse(JSON.stringify(o))\n}\n\n// http://crockford.com/javascript/memory/leak.html\nexport const purge = (d) => {\n\tvar a = d.attributes, i, l, n\n\tif (a) {\n\t\tfor (i = a.length - 1; i >= 0; i -= 1) {\n\t\t\tn = a[i].name\n\t\t\tif (typeof d[n] === 'function') {\n\t\t\t\td[n] = null\n\t\t\t}\n\t\t}\n\t}\n\ta = d.childNodes\n\tif (a) {\n\t\tl = a.length\n\t\tfor (i = 0; i < l; i += 1) {\n\t\t\tpurge(d.childNodes[i])\n\t\t}\n\t}\n}\n\nexport const safe = (execute, val) => {\n\ttry{return execute()}catch(err){return val || ''}\n}\n\n// From\n// https://2ality.com/2015/01/template-strings-html.html#comment-2078932192\nexport const html = (literalSections, ...substs) => {\n\n\t// Use raw literal sections: we don’t want\n\t// backslashes (\\n etc.) to be interpreted\n\tlet raw = literalSections.raw\n\n\tlet result = ''\n\n\tsubsts.forEach((subst, i) => {\n\t\t// Retrieve the literal section preceding\n\t\t// the current substitution\n\t\tlet lit = raw[i]\n\n\t\t// In the example, map() returns an array:\n\t\t// If substitution is an array (and not a string),\n\t\t// we turn it into a string\n\t\tif (Array.isArray(subst)) {\n\t\t\tsubst = subst.join('')\n\t\t}\n\n\t\tresult += lit\n\t\tresult += subst\n\t})\n\t// Take care of last literal section\n\t// (Never fails, because an empty template string\n\t// produces one literal section, an empty string)\n\tresult += raw[raw.length-1] // (A)\n\n\treturn result\n}\n","import Transpile from './transpile'\nimport { uuid, decodeHTML } from './utils'\n\nconst config = {\n\ttags: ['${', '}']\n}\n\nexport const templateConfig = (newconfig) => {\n\tObject.assign(config, newconfig)\n}\n\nexport default function Template(element) {\n\n\tconst html = Transpile(element.outerHTML, config)\n\tconst decodedHTML = JSON.stringify(html)\n\n\treturn new Function('$element', 'safe',`\n\t\tvar $data = this;\n\t\twith( $data ){\n\t\t\tvar output=${decodedHTML\n\t\t\t\t.replace(/%%_=(.+?)_%%/g, function(_, variable){\n\t\t\t\t\treturn '\"+safe(function(){return '+decodeHTML(variable)+';})+\"'\n\t\t\t\t})\n\t\t\t\t.replace(/%%_(.+?)_%%/g, function(_, variable){\n\t\t\t\t\treturn '\";' + decodeHTML(variable) +'\\noutput+=\"'\n\t\t\t\t})};return output;\n\t\t}\n\t`)\n}\n\nexport const buildtemplates = ( target, selector, templates, components ) => {\n\t[]\n\t\t.concat( target.matches? (target.matches(selector)? target : []) : [] )\n\t\t.concat( Array.from(target.querySelectorAll( selector )) )\n\t\t.reverse()\n\t\t.forEach( (node:HTMLElement) => {\n\t\t\tnode.querySelectorAll('template').forEach( template => buildtemplates(template.content, selector, templates, components ))\n\t\t\tcreateTemplateId(node, templates, components)\n\t\t})\n}\n\nconst createTemplateId = (element, templates, components ) => {\n\n\tconst tplid = element.getAttribute('tplid')\n\n\tif (!tplid) {\n\t\tconst id = uuid()\n\t\telement.setAttribute('tplid', id)\n\t\tconst name = element.localName\n\n\t\tif( name in components && components[name].module.template ) {\n\t\t\tconst html = components[name].module.template()\n\t\t\tif( html.constructor === Promise ) {\n\t\t\t\telement.__template = html\n\t\t\t\thtml.then( htmlstring => {\n\t\t\t\t\telement.innerHTML = htmlstring\n\t\t\t\t\ttemplates[id] = Template(element)\n\t\t\t\t})\n\t\t\t}else {\n\t\t\t\telement.innerHTML = html\n\t\t\t}\n\t\t}\n\t\ttemplates[id] = Template(element)\n\t}\n}\n\n","const topics: any = {}\nconst _async: any = {}\n\nexport const publish = (name, params) => {\n\t_async[name] = Object.assign({}, _async[name], params)\n\tif (topics[name])\n\t\ttopics[name].forEach(topic => topic(params))\n}\n\nexport const subscribe = (name, method) => {\n\ttopics[name] = topics[name] || []\n\ttopics[name].push(method)\n\tif (name in _async) {\n\t\tmethod(_async[name])\n\t}\n\treturn () => {\n\t\ttopics[name] = topics[name].filter( fn => fn != method )\n\t}\n}\n\n","// base IIFE to define idiomorph\nvar Idiomorph = (function () {\n 'use strict';\n\n //=============================================================================\n // AND NOW IT BEGINS...\n //=============================================================================\n let EMPTY_SET = new Set();\n\n // default configuration values, updatable by users now\n let defaults = {\n morphStyle: \"outerHTML\",\n callbacks : {\n beforeNodeAdded: noOp,\n afterNodeAdded: noOp,\n beforeNodeMorphed: noOp,\n afterNodeMorphed: noOp,\n beforeNodeRemoved: noOp,\n afterNodeRemoved: noOp,\n beforeAttributeUpdated: noOp,\n\n },\n head: {\n style: 'merge',\n shouldPreserve: function (elt) {\n return elt.getAttribute(\"im-preserve\") === \"true\";\n },\n shouldReAppend: function (elt) {\n return elt.getAttribute(\"im-re-append\") === \"true\";\n },\n shouldRemove: noOp,\n afterHeadMorphed: noOp,\n }\n };\n\n //=============================================================================\n // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren\n //=============================================================================\n function morph(oldNode, newContent, config = {}) {\n\n if (oldNode instanceof Document) {\n oldNode = oldNode.documentElement;\n }\n\n if (typeof newContent === 'string') {\n newContent = parseContent(newContent);\n }\n\n let normalizedContent = normalizeContent(newContent);\n\n let ctx = createMorphContext(oldNode, normalizedContent, config);\n\n return morphNormalizedContent(oldNode, normalizedContent, ctx);\n }\n\n function morphNormalizedContent(oldNode, normalizedNewContent, ctx) {\n if (ctx.head.block) {\n let oldHead = oldNode.querySelector('head');\n let newHead = normalizedNewContent.querySelector('head');\n if (oldHead && newHead) {\n let promises = handleHeadElement(newHead, oldHead, ctx);\n // when head promises resolve, call morph again, ignoring the head tag\n Promise.all(promises).then(function () {\n morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, {\n head: {\n block: false,\n ignore: true\n }\n }));\n });\n return;\n }\n }\n\n if (ctx.morphStyle === \"innerHTML\") {\n\n // innerHTML, so we are only updating the children\n morphChildren(normalizedNewContent, oldNode, ctx);\n return oldNode.children;\n\n } else if (ctx.morphStyle === \"outerHTML\" || ctx.morphStyle == null) {\n // otherwise find the best element match in the new content, morph that, and merge its siblings\n // into either side of the best match\n let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx);\n\n // stash the siblings that will need to be inserted on either side of the best match\n let previousSibling = bestMatch?.previousSibling;\n let nextSibling = bestMatch?.nextSibling;\n\n // morph it\n let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx);\n\n if (bestMatch) {\n // if there was a best match, merge the siblings in too and return the\n // whole bunch\n return insertSiblings(previousSibling, morphedNode, nextSibling);\n } else {\n // otherwise nothing was added to the DOM\n return []\n }\n } else {\n throw \"Do not understand how to morph style \" + ctx.morphStyle;\n }\n }\n\n\n /**\n * @param possibleActiveElement\n * @param ctx\n * @returns {boolean}\n */\n function ignoreValueOfActiveElement(possibleActiveElement, ctx) {\n return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement;\n }\n\n /**\n * @param oldNode root node to merge content into\n * @param newContent new content to merge\n * @param ctx the merge context\n * @returns {Element} the element that ended up in the DOM\n */\n function morphOldNodeTo(oldNode, newContent, ctx) {\n if (ctx.ignoreActive && oldNode === document.activeElement) {\n // don't morph focused element\n } else if (newContent == null) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n\n oldNode.remove();\n ctx.callbacks.afterNodeRemoved(oldNode);\n return null;\n } else if (!isSoftMatch(oldNode, newContent)) {\n if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode;\n if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode;\n\n oldNode.parentElement.replaceChild(newContent, oldNode);\n ctx.callbacks.afterNodeAdded(newContent);\n ctx.callbacks.afterNodeRemoved(oldNode);\n return newContent;\n } else {\n if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode;\n\n if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) {\n // ignore the head element\n } else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== \"morph\") {\n handleHeadElement(newContent, oldNode, ctx);\n } else {\n syncNodeFrom(newContent, oldNode, ctx);\n if (!ignoreValueOfActiveElement(oldNode, ctx)) {\n morphChildren(newContent, oldNode, ctx);\n }\n }\n ctx.callbacks.afterNodeMorphed(oldNode, newContent);\n return oldNode;\n }\n }\n\n /**\n * This is the core algorithm for matching up children. The idea is to use id sets to try to match up\n * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but\n * by using id sets, we are able to better match up with content deeper in the DOM.\n *\n * Basic algorithm is, for each node in the new content:\n *\n * - if we have reached the end of the old parent, append the new content\n * - if the new content has an id set match with the current insertion point, morph\n * - search for an id set match\n * - if id set match found, morph\n * - otherwise search for a \"soft\" match\n * - if a soft match is found, morph\n * - otherwise, prepend the new node before the current insertion point\n *\n * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved\n * with the current node. See findIdSetMatch() and findSoftMatch() for details.\n *\n * @param {Element} newParent the parent element of the new content\n * @param {Element } oldParent the old content that we are merging the new content into\n * @param ctx the merge context\n */\n function morphChildren(newParent, oldParent, ctx) {\n\n let nextNewChild = newParent.firstChild;\n let insertionPoint = oldParent.firstChild;\n let newChild;\n\n // run through all the new content\n while (nextNewChild) {\n\n newChild = nextNewChild;\n nextNewChild = newChild.nextSibling;\n\n // if we are at the end of the exiting parent's children, just append\n if (insertionPoint == null) {\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.appendChild(newChild);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // if the current node has an id set match then morph\n if (isIdSetMatch(newChild, insertionPoint, ctx)) {\n morphOldNodeTo(insertionPoint, newChild, ctx);\n insertionPoint = insertionPoint.nextSibling;\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // otherwise search forward in the existing old children for an id set match\n let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a potential match, remove the nodes until that point and morph\n if (idSetMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx);\n morphOldNodeTo(idSetMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // no id set match found, so scan forward for a soft match for the current node\n let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx);\n\n // if we found a soft match for the current node, morph\n if (softMatch) {\n insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx);\n morphOldNodeTo(softMatch, newChild, ctx);\n removeIdsFromConsideration(ctx, newChild);\n continue;\n }\n\n // abandon all hope of morphing, just insert the new child before the insertion point\n // and move on\n if (ctx.callbacks.beforeNodeAdded(newChild) === false) return;\n\n oldParent.insertBefore(newChild, insertionPoint);\n ctx.callbacks.afterNodeAdded(newChild);\n removeIdsFromConsideration(ctx, newChild);\n }\n\n // remove any remaining old nodes that didn't match up with new content\n while (insertionPoint !== null) {\n\n let tempNode = insertionPoint;\n insertionPoint = insertionPoint.nextSibling;\n removeNode(tempNode, ctx);\n }\n }\n\n //=============================================================================\n // Attribute Syncing Code\n //=============================================================================\n\n /**\n * @param attr {String} the attribute to be mutated\n * @param to {Element} the element that is going to be updated\n * @param updateType {(\"update\"|\"remove\")}\n * @param ctx the merge context\n * @returns {boolean} true if the attribute should be ignored, false otherwise\n */\n function ignoreAttribute(attr, to, updateType, ctx) {\n if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){\n return true;\n }\n return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false;\n }\n\n /**\n * syncs a given node with another node, copying over all attributes and\n * inner element state from the 'from' node to the 'to' node\n *\n * @param {Element} from the element to copy attributes & state from\n * @param {Element} to the element to copy attributes & state to\n * @param ctx the merge context\n */\n function syncNodeFrom(from, to, ctx) {\n let type = from.nodeType\n\n // if is an element type, sync the attributes from the\n // new node into the new node\n if (type === 1 /* element type */) {\n const fromAttributes = from.attributes;\n const toAttributes = to.attributes;\n for (const fromAttribute of fromAttributes) {\n if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) {\n continue;\n }\n if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) {\n to.setAttribute(fromAttribute.name, fromAttribute.value);\n }\n }\n // iterate backwards to avoid skipping over items when a delete occurs\n for (let i = toAttributes.length - 1; 0 <= i; i--) {\n const toAttribute = toAttributes[i];\n if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) {\n continue;\n }\n if (!from.hasAttribute(toAttribute.name)) {\n to.removeAttribute(toAttribute.name);\n }\n }\n }\n\n // sync text nodes\n if (type === 8 /* comment */ || type === 3 /* text */) {\n if (to.nodeValue !== from.nodeValue) {\n to.nodeValue = from.nodeValue;\n }\n }\n\n if (!ignoreValueOfActiveElement(to, ctx)) {\n // sync input values\n syncInputValue(from, to, ctx);\n }\n }\n\n /**\n * @param from {Element} element to sync the value from\n * @param to {Element} element to sync the value to\n * @param attributeName {String} the attribute name\n * @param ctx the merge context\n */\n function syncBooleanAttribute(from, to, attributeName, ctx) {\n if (from[attributeName] !== to[attributeName]) {\n let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx);\n if (!ignoreUpdate) {\n to[attributeName] = from[attributeName];\n }\n if (from[attributeName]) {\n if (!ignoreUpdate) {\n to.setAttribute(attributeName, from[attributeName]);\n }\n } else {\n if (!ignoreAttribute(attributeName, to, 'remove', ctx)) {\n to.removeAttribute(attributeName);\n }\n }\n }\n }\n\n /**\n * NB: many bothans died to bring us information:\n *\n * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js\n * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113\n *\n * @param from {Element} the element to sync the input value from\n * @param to {Element} the element to sync the input value to\n * @param ctx the merge context\n */\n function syncInputValue(from, to, ctx) {\n if (from instanceof HTMLInputElement &&\n to instanceof HTMLInputElement &&\n from.type !== 'file') {\n\n let fromValue = from.value;\n let toValue = to.value;\n\n // sync boolean attributes\n syncBooleanAttribute(from, to, 'checked', ctx);\n syncBooleanAttribute(from, to, 'disabled', ctx);\n\n if (!from.hasAttribute('value')) {\n if (!ignoreAttribute('value', to, 'remove', ctx)) {\n to.value = '';\n to.removeAttribute('value');\n }\n } else if (fromValue !== toValue) {\n if (!ignoreAttribute('value', to, 'update', ctx)) {\n to.setAttribute('value', fromValue);\n to.value = fromValue;\n }\n }\n } else if (from instanceof HTMLOptionElement) {\n syncBooleanAttribute(from, to, 'selected', ctx)\n } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) {\n let fromValue = from.value;\n let toValue = to.value;\n if (ignoreAttribute('value', to, 'update', ctx)) {\n return;\n }\n if (fromValue !== toValue) {\n to.value = fromValue;\n }\n if (to.firstChild && to.firstChild.nodeValue !== fromValue) {\n to.firstChild.nodeValue = fromValue\n }\n }\n }\n\n //=============================================================================\n // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style\n //=============================================================================\n function handleHeadElement(newHeadTag, currentHead, ctx) {\n\n let added = []\n let removed = []\n let preserved = []\n let nodesToAppend = []\n\n let headMergeStyle = ctx.head.style;\n\n // put all new head elements into a Map, by their outerHTML\n let srcToNewHeadNodes = new Map();\n for (const newHeadChild of newHeadTag.children) {\n srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild);\n }\n\n // for each elt in the current head\n for (const currentHeadElt of currentHead.children) {\n\n // If the current head element is in the map\n let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML);\n let isReAppended = ctx.head.shouldReAppend(currentHeadElt);\n let isPreserved = ctx.head.shouldPreserve(currentHeadElt);\n if (inNewContent || isPreserved) {\n if (isReAppended) {\n // remove the current version and let the new version replace it and re-execute\n removed.push(currentHeadElt);\n } else {\n // this element already exists and should not be re-appended, so remove it from\n // the new content map, preserving it in the DOM\n srcToNewHeadNodes.delete(currentHeadElt.outerHTML);\n preserved.push(currentHeadElt);\n }\n } else {\n if (headMergeStyle === \"append\") {\n // we are appending and this existing element is not new content\n // so if and only if it is marked for re-append do we do anything\n if (isReAppended) {\n removed.push(currentHeadElt);\n nodesToAppend.push(currentHeadElt);\n }\n } else {\n // if this is a merge, we remove this content since it is not in the new head\n if (ctx.head.shouldRemove(currentHeadElt) !== false) {\n removed.push(currentHeadElt);\n }\n }\n }\n }\n\n // Push the remaining new head elements in the Map into the\n // nodes to append to the head tag\n nodesToAppend.push(...srcToNewHeadNodes.values());\n log(\"to append: \", nodesToAppend);\n\n let promises = [];\n for (const newNode of nodesToAppend) {\n log(\"adding: \", newNode);\n let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild;\n log(newElt);\n if (ctx.callbacks.beforeNodeAdded(newElt) !== false) {\n if (newElt.href || newElt.src) {\n let resolve = null;\n let promise = new Promise(function (_resolve) {\n resolve = _resolve;\n });\n newElt.addEventListener('load', function () {\n resolve();\n });\n promises.push(promise);\n }\n currentHead.appendChild(newElt);\n ctx.callbacks.afterNodeAdded(newElt);\n added.push(newElt);\n }\n }\n\n // remove all removed elements, after we have appended the new elements to avoid\n // additional network requests for things like style sheets\n for (const removedElement of removed) {\n if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) {\n currentHead.removeChild(removedElement);\n ctx.callbacks.afterNodeRemoved(removedElement);\n }\n }\n\n ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed});\n return promises;\n }\n\n //=============================================================================\n // Misc\n //=============================================================================\n\n function log() {\n //console.log(arguments);\n }\n\n function noOp() {\n }\n\n /*\n Deep merges the config object and the Idiomoroph.defaults object to\n produce a final configuration object\n */\n function mergeDefaults(config) {\n let finalConfig = {};\n // copy top level stuff into final config\n Object.assign(finalConfig, defaults);\n Object.assign(finalConfig, config);\n\n // copy callbacks into final config (do this to deep merge the callbacks)\n finalConfig.callbacks = {};\n Object.assign(finalConfig.callbacks, defaults.callbacks);\n Object.assign(finalConfig.callbacks, config.callbacks);\n\n // copy head config into final config (do this to deep merge the head)\n finalConfig.head = {};\n Object.assign(finalConfig.head, defaults.head);\n Object.assign(finalConfig.head, config.head);\n return finalConfig;\n }\n\n function createMorphContext(oldNode, newContent, config) {\n config = mergeDefaults(config);\n return {\n target: oldNode,\n newContent: newContent,\n config: config,\n morphStyle: config.morphStyle,\n ignoreActive: config.ignoreActive,\n ignoreActiveValue: config.ignoreActiveValue,\n idMap: createIdMap(oldNode, newContent),\n deadIds: new Set(),\n callbacks: config.callbacks,\n head: config.head\n }\n }\n\n function isIdSetMatch(node1, node2, ctx) {\n if (node1 == null || node2 == null) {\n return false;\n }\n if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) {\n if (node1.id !== \"\" && node1.id === node2.id) {\n return true;\n } else {\n return getIdIntersectionCount(ctx, node1, node2) > 0;\n }\n }\n return false;\n }\n\n function isSoftMatch(node1, node2) {\n if (node1 == null || node2 == null) {\n return false;\n }\n return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName\n }\n\n function removeNodesBetween(startInclusive, endExclusive, ctx) {\n while (startInclusive !== endExclusive) {\n let tempNode = startInclusive;\n startInclusive = startInclusive.nextSibling;\n removeNode(tempNode, ctx);\n }\n removeIdsFromConsideration(ctx, endExclusive);\n return endExclusive.nextSibling;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential id match\n // for the newChild. We stop if we find a potential id match for the new child OR\n // if the number of potential id matches we are discarding is greater than the\n // potential id matches for the new child\n //=============================================================================\n function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n // max id matches we are willing to discard in our search\n let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent);\n\n let potentialMatch = null;\n\n // only search forward if there is a possibility of an id match\n if (newChildPotentialIdCount > 0) {\n let potentialMatch = insertionPoint;\n // if there is a possibility of an id match, scan forward\n // keep track of the potential id match count we are discarding (the\n // newChildPotentialIdCount must be greater than this to make it likely\n // worth it)\n let otherMatchCount = 0;\n while (potentialMatch != null) {\n\n // If we have an id match, return the current potential match\n if (isIdSetMatch(newChild, potentialMatch, ctx)) {\n return potentialMatch;\n }\n\n // computer the other potential matches of this new content\n otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent);\n if (otherMatchCount > newChildPotentialIdCount) {\n // if we have more potential id matches in _other_ content, we\n // do not have a good candidate for an id match, so return null\n return null;\n }\n\n // advanced to the next old content child\n potentialMatch = potentialMatch.nextSibling;\n }\n }\n return potentialMatch;\n }\n\n //=============================================================================\n // Scans forward from the insertionPoint in the old parent looking for a potential soft match\n // for the newChild. We stop if we find a potential soft match for the new child OR\n // if we find a potential id match in the old parents children OR if we find two\n // potential soft matches for the next two pieces of new content\n //=============================================================================\n function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) {\n\n let potentialSoftMatch = insertionPoint;\n let nextSibling = newChild.nextSibling;\n let siblingSoftMatchCount = 0;\n\n while (potentialSoftMatch != null) {\n\n if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) {\n // the current potential soft match has a potential id set match with the remaining new\n // content so bail out of looking\n return null;\n }\n\n // if we have a soft match with the current node, return it\n if (isSoftMatch(newChild, potentialSoftMatch)) {\n return potentialSoftMatch;\n }\n\n if (isSoftMatch(nextSibling, potentialSoftMatch)) {\n // the next new node has a soft match with this node, so\n // increment the count of future soft matches\n siblingSoftMatchCount++;\n nextSibling = nextSibling.nextSibling;\n\n // If there are two future soft matches, bail to allow the siblings to soft match\n // so that we don't consume future soft matches for the sake of the current node\n if (siblingSoftMatchCount >= 2) {\n return null;\n }\n }\n\n // advanced to the next old content child\n potentialSoftMatch = potentialSoftMatch.nextSibling;\n }\n\n return potentialSoftMatch;\n }\n\n function parseContent(newContent) {\n let parser = new DOMParser();\n\n // remove svgs to avoid false-positive matches on head, etc.\n let contentWithSvgsRemoved = newContent.replace(/]*>|>)([\\s\\S]*?)<\\/svg>/gim, '');\n\n // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping\n if (contentWithSvgsRemoved.match(/<\\/html>/) || contentWithSvgsRemoved.match(/<\\/head>/) || contentWithSvgsRemoved.match(/<\\/body>/)) {\n let content = parser.parseFromString(newContent, \"text/html\");\n // if it is a full HTML document, return the document itself as the parent container\n if (contentWithSvgsRemoved.match(/<\\/html>/)) {\n content.generatedByIdiomorph = true;\n return content;\n } else {\n // otherwise return the html element as the parent container\n let htmlElement = content.firstChild;\n if (htmlElement) {\n htmlElement.generatedByIdiomorph = true;\n return htmlElement;\n } else {\n return null;\n }\n }\n } else {\n // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help\n // deal with touchy tags like tr, tbody, etc.\n let responseDoc = parser.parseFromString(\"\", \"text/html\");\n let content = responseDoc.body.querySelector('template').content;\n content.generatedByIdiomorph = true;\n return content\n }\n }\n\n function normalizeContent(newContent) {\n if (newContent == null) {\n // noinspection UnnecessaryLocalVariableJS\n const dummyParent = document.createElement('div');\n return dummyParent;\n } else if (newContent.generatedByIdiomorph) {\n // the template tag created by idiomorph parsing can serve as a dummy parent\n return newContent;\n } else if (newContent instanceof Node) {\n // a single node is added as a child to a dummy parent\n const dummyParent = document.createElement('div');\n dummyParent.append(newContent);\n return dummyParent;\n } else {\n // all nodes in the array or HTMLElement collection are consolidated under\n // a single dummy parent element\n const dummyParent = document.createElement('div');\n for (const elt of [...newContent]) {\n dummyParent.append(elt);\n }\n return dummyParent;\n }\n }\n\n function insertSiblings(previousSibling, morphedNode, nextSibling) {\n let stack = []\n let added = []\n while (previousSibling != null) {\n stack.push(previousSibling);\n previousSibling = previousSibling.previousSibling;\n }\n while (stack.length > 0) {\n let node = stack.pop();\n added.push(node); // push added preceding siblings on in order and insert\n morphedNode.parentElement.insertBefore(node, morphedNode);\n }\n added.push(morphedNode);\n while (nextSibling != null) {\n stack.push(nextSibling);\n added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add\n nextSibling = nextSibling.nextSibling;\n }\n while (stack.length > 0) {\n morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling);\n }\n return added;\n }\n\n function findBestNodeMatch(newContent, oldNode, ctx) {\n let currentElement;\n currentElement = newContent.firstChild;\n let bestElement = currentElement;\n let score = 0;\n while (currentElement) {\n let newScore = scoreElement(currentElement, oldNode, ctx);\n if (newScore > score) {\n bestElement = currentElement;\n score = newScore;\n }\n currentElement = currentElement.nextSibling;\n }\n return bestElement;\n }\n\n function scoreElement(node1, node2, ctx) {\n if (isSoftMatch(node1, node2)) {\n return .5 + getIdIntersectionCount(ctx, node1, node2);\n }\n return 0;\n }\n\n function removeNode(tempNode, ctx) {\n removeIdsFromConsideration(ctx, tempNode)\n if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return;\n\n tempNode.remove();\n ctx.callbacks.afterNodeRemoved(tempNode);\n }\n\n //=============================================================================\n // ID Set Functions\n //=============================================================================\n\n function isIdInConsideration(ctx, id) {\n return !ctx.deadIds.has(id);\n }\n\n function idIsWithinNode(ctx, id, targetNode) {\n let idSet = ctx.idMap.get(targetNode) || EMPTY_SET;\n return idSet.has(id);\n }\n\n function removeIdsFromConsideration(ctx, node) {\n let idSet = ctx.idMap.get(node) || EMPTY_SET;\n for (const id of idSet) {\n ctx.deadIds.add(id);\n }\n }\n\n function getIdIntersectionCount(ctx, node1, node2) {\n let sourceSet = ctx.idMap.get(node1) || EMPTY_SET;\n let matchCount = 0;\n for (const id of sourceSet) {\n // a potential match is an id in the source and potentialIdsSet, but\n // that has not already been merged into the DOM\n if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) {\n ++matchCount;\n }\n }\n return matchCount;\n }\n\n /**\n * A bottom up algorithm that finds all elements with ids inside of the node\n * argument and populates id sets for those nodes and all their parents, generating\n * a set of ids contained within all nodes for the entire hierarchy in the DOM\n *\n * @param node {Element}\n * @param {Map>} idMap\n */\n function populateIdMapForNode(node, idMap) {\n let nodeParent = node.parentElement;\n // find all elements with an id property\n let idElements = node.querySelectorAll('[id]');\n for (const elt of idElements) {\n let current = elt;\n // walk up the parent hierarchy of that element, adding the id\n // of element to the parent's id set\n while (current !== nodeParent && current != null) {\n let idSet = idMap.get(current);\n // if the id set doesn't exist, create it and insert it in the map\n if (idSet == null) {\n idSet = new Set();\n idMap.set(current, idSet);\n }\n idSet.add(elt.id);\n current = current.parentElement;\n }\n }\n }\n\n /**\n * This function computes a map of nodes to all ids contained within that node (inclusive of the\n * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows\n * for a looser definition of \"matching\" than tradition id matching, and allows child nodes\n * to contribute to a parent nodes matching.\n *\n * @param {Element} oldContent the old content that will be morphed\n * @param {Element} newContent the new content to morph to\n * @returns {Map>} a map of nodes to id sets for the\n */\n function createIdMap(oldContent, newContent) {\n let idMap = new Map();\n populateIdMapForNode(oldContent, idMap);\n populateIdMapForNode(newContent, idMap);\n return idMap;\n }\n\n //=============================================================================\n // This is what ends up becoming the Idiomorph global object\n //=============================================================================\n return {\n morph,\n defaults\n }\n })();\n\nexport {Idiomorph};\n","const customEvent = (() => {\n\treturn ('CustomEvent' in window && typeof window.CustomEvent === 'function')\n\t\t? (name, data) => new CustomEvent(name, data)\n\t\t: (name, data) => {\n\t\t\tconst newEvent = document.createEvent('CustomEvent')\n\t\t\tnewEvent.initCustomEvent(name, true, true, data)\n\t\t\treturn newEvent\n\t\t}\n})()\n\nconst handler = (node, ev) => {\n\treturn function (e) {\n\t\tconst scope = this\n\t\tconst detail = e.detail || {}\n\t\tnode.__events[ev].forEach(o => {\n\t\t\to.handler.apply(scope, [e].concat(detail.args))\n\t\t})\n\t}\n}\n\nconst removeListener = (node, ev) => {\n\tif (node.__events[ev] && node.__events[ev].listener) {\n\t\tnode.removeEventListener(\n\t\t\tev,\n\t\t\tnode.__events[ev].listener,\n\t\t\t(ev == 'focus' || ev == 'blur' || ev == 'mouseenter' || ev == 'mouseleave'))\n\t\tdelete node.__events[ev]\n\t}\n}\n\nconst delegate = (node, selector, callback) => {\n\treturn function (e) {\n\n\t\tconst element = this\n\t\tconst detail = e.detail || {}\n\n\t\tlet parent = e.target\n\n\t\twhile (parent) {\n\t\t\tif (parent.matches(selector)) {\n\t\t\t\te.delegateTarget = parent\n\t\t\t\tcallback.apply(element, [e].concat(detail.args))\n\t\t\t}\n\t\t\tif (parent === node) break\n\t\t\tparent = parent.parentNode\n\t\t}\n\t}\n}\n\nexport const on = (node, ev, selectorOrCallback, callback) => {\n\n\tnode.__events = node.__events || {}\n\tnode.__events[ev] = (node.__events[ev] || [])\n\n\tif (!node.__events[ev].length) {\n\t\tconst fn = handler(node, ev)\n\t\tnode.addEventListener(\n\t\t\tev,\n\t\t\tfn,\n\t\t\t(ev == 'focus' || ev == 'blur' || ev == 'mouseenter' || ev == 'mouseleave'))\n\t\tnode.__events[ev].listener = fn\n\t}\n\n\tif (selectorOrCallback.call) {\n\t\tnode.__events[ev].push({ handler: selectorOrCallback, callback: selectorOrCallback })\n\t} else {\n\t\tnode.__events[ev].push({ handler: delegate(node, selectorOrCallback, callback), callback })\n\t}\n}\n\nexport const off = (node, ev, fn) => {\n\n\tif (fn && node.__events[ev] && node.__events[ev].length) {\n\t\tvar old = node.__events[ev]\n\t\tnode.__events[ev] = node.__events[ev].filter(function (o) { return o.callback != fn; })\n\t\tnode.__events[ev].listener = old.listener\n\t\tif (!node.__events[ev].length)\n\t\t\tremoveListener(node, ev)\n\t} else {\n\t\tremoveListener(node, ev)\n\t}\n}\n\nexport const trigger = (node, name, args) => {\n\tnode.dispatchEvent(customEvent(name, { bubbles: true, detail: args }))\n}\n","import { type Component } from '..'\nimport { Idiomorph } from 'idiomorph/dist/idiomorph.esm'\nimport { rAF, dup, safe } from './utils'\nimport { buildtemplates } from './template-system'\nimport { on, off, trigger } from './utils/events'\nimport { publish, subscribe } from './utils/pubsub'\n\nexport default function Component( elm, { module, dependencies, templates, components }) {\n\n\tconst options = getOptions( module )\n\tconst initialState = (new Function( `return ${elm.getAttribute('html-model') || '{}'}`))()\n\tconst selector = Object.keys(components).toString()\n\n\tbuildtemplates( elm, selector, templates, components )\n\n\tconst tplid = elm.getAttribute('tplid')\n\tconst template = tplid ? templates[tplid] : null\n\tconst state = { data: module.model ? dup(module.model) : {} }\n\tstate.data = Object.assign( state.data, initialState)\n\n\tconst base: Component = {\n\t\ttemplate,\n\t\telm,\n\t\tdependencies,\n\t\tpublish,\n\t\tsubscribe,\n\n\t\tmain(fn) {\n\t\t\toptions.main = fn\n\t\t},\n\n\t\tunmount(fn) {\n\t\t\toptions.unmount = fn\n\t\t},\n\n\t\tonupdate(fn) {\n\t\t\toptions.onupdate = fn\n\t\t},\n\n\t\ton(eventName, selectorOrCallback, callback) {\n\t\t\ton(elm, eventName, selectorOrCallback, callback)\n\t\t},\n\n\t\toff(eventName, callback) {\n\t\t\toff(elm, eventName, callback)\n\t\t},\n\n\t\ttrigger(eventName, target, args) {\n\t\t\tif (target.constructor === String) {\n\t\t\t\tArray\n\t\t\t\t\t.from(elm.querySelectorAll(target))\n\t\t\t\t\t.forEach( children => trigger(children, eventName, { args: args }) )\n\t\t\t}\n\t\t\telse trigger(elm, eventName, { args: target })\n\t\t},\n\n\t\temit: ( ...args ) => {\n\t\t\ttrigger(elm, args.shift(), { args: args })\n\t\t},\n\n\t\tstate: {\n\t\t\tset( data ) {\n\t\t\t\tif (data.constructor === Function) {\n\t\t\t\t\tconst newstate = dup(state.data)\n\t\t\t\t\tdata(newstate)\n\t\t\t\t\tbase.render(newstate)\n\t\t\t\t} else {\n\t\t\t\t\tbase.render(data)\n\t\t\t\t}\n\t\t\t\treturn new Promise((resolve) => rAF(_ => rAF(() => resolve(state.data))))\n\t\t\t},\n\t\t\tget() {\n\t\t\t\treturn dup(state.data)\n\t\t\t},\n\n\t\t\tgetRaw(){\n\t\t\t\treturn state.data\n\t\t\t}\n\t\t},\n\n\t\trender(data = state.data) {\n\n\t\t\tif (!document.body.contains(elm)) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstate.data = Object.assign(state.data, data)\n\n\t\t\tconst newdata = dup(state.data)\n\t\t\tconst newhtml = templates[tplid].call(Object.assign(options.view(newdata), elm.___scope___), elm, safe)\n\n\t\t\tIdiomorph.morph(elm, newhtml, IdiomorphOptions(elm))\n\t\t\tupdateScope( elm )\n\n\t\t\trAF(_ => {\n\t\t\t\tArray\n\t\t\t\t\t.from(elm.querySelectorAll('[tplid]'))\n\t\t\t\t\t.forEach((child: any) => {\n\t\t\t\t\t\tconst props = Object.assign( child.base.state.getRaw(), data )\n\t\t\t\t\t\tchild.options.onupdate(props)\n\t\t\t\t\t\tchild.base.render(props)\n\t\t\t\t\t})\n\t\t\t})\n\t\t},\n\n\t\tinnerHTML( target, html_ ) {\n\n\t\t\tconst element = html_? target : elm\n\t\t\tconst clone = element.cloneNode()\n\t\t\tconst html = html_? html_ : target\n\t\t\tclone.innerHTML = html\n\n\t\t\trAF( _ => Idiomorph.morph(element, clone, IdiomorphOptions) )\n\t\t}\n\t}\n\n\treturn { base, options }\n}\n\nconst getOptions = (module) => ({\n\tmain: (a) => a,\n\tunmount: (a) => a,\n\tonupdate: (a) => a,\n\tview: module.view ? module.view : (a) => a\n})\n\nconst updateScope = (node) => {\n\tnode.querySelectorAll('[scope]').forEach( scopeElement => {\n\t\tscopeElement.querySelectorAll('[tplid]').forEach( cp => {\n\t\t\tif( !cp.___scope___ ) {\n\t\t\t\tconst script = scopeElement.lastElementChild\n\t\t\t\tcp.___scope___ = 'scope' in script.dataset? (new Function(`return ${script.text}`))() : {}\n\t\t\t}\n\t\t})\n\t})\n}\n\n\nconst IdiomorphOptions = (parent) => ({\n\n\tcallbacks: {\n\n\t\tbeforeNodeMorphed( node ) {\n\t\t\tif( node.nodeType === 1 ) {\n\t\t\t\tif( 'html-static' in node.attributes ) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tif( node.base && node !== parent ) {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n})\n","import Component from './component'\nimport { purge, rAF } from './utils'\n\nexport default function Element(module, dependencies, templates, components) {\n\treturn class extends HTMLElement {\n\n\t\tbase: any\n\t\toptions: any\n\t\treturns : any\n\t\t__events: any\n\n\t\tconstructor() {\n\n\t\t\tsuper()\n\t\t\tconst { base, options } = Component(this, { module, dependencies, templates, components })\n\n\t\t\tthis.base = base\n\t\t\tthis.options = options\n\t\t\tthis.returns = module.default(base)\n\t\t}\n\n\t\tconnectedCallback() {\n\n\t\t\tthis.base.render()\n\n\t\t\tif( this.__template && this.__template.constructor === Promise ) {\n\t\t\t\tthis.__template.then( _ => {\n\t\t\t\t\tif( this.base && this.options.main) {\n\t\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\t\tif( array && array.length ){\n\t\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif( this.returns && this.returns.constructor === Promise ) {\n\t\t\t\tthis.returns.then( _ => {\n\t\t\t\t\tif( this.base && this.options.main) {\n\t\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\t\tif( array && array.length ){\n\t\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}else {\n\t\t\t\tif( this.base && this.options.main ){\n\t\t\t\t\tconst array = this.options.main(this.base)\n\t\t\t\t\tif( array && array.length ) {\n\t\t\t\t\t\tarray.forEach(f => f(this.base))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tdisconnectedCallback() {\n\t\t\tthis.options.unmount(this.base)\n\t\t\trAF(() => {\n\t\t\t\tif(!document.body.contains(this) ) {\n\t\t\t\t\tthis.__events? this.__events = null : null\n\t\t\t\t\tthis.base? this.base.elm = null : null\n\t\t\t\t\tthis.base? this.base = null : null\n\t\t\t\t\tpurge(this)\n\t\t\t\t}\n\t\t\t})\n\n\t\t}\n\n\t\tattributeChangedCallback() {\n\t\t\t//TODO\n\t\t}\n\t}\n}\n","import { templateConfig, buildtemplates } from './template-system'\nimport { publish, subscribe } from './utils/pubsub'\nimport { html } from './utils'\nimport Element from './element'\n\nconst templates = {}\nconst components = {}\n\nexport { html }\n\nexport default {\n\n\ttemplateConfig,\n\n\tpublish,\n\tsubscribe,\n\n\tregister( name, module, dependencies = {} ) {\n\t\tcomponents[name] = { name, module, dependencies }\n\t},\n\n\tstart( target = document.body ) {\n\t\tconst keys = Object.keys(components)\n\t\tconst selector = keys.toString()\n\t\tif( keys.length ) {\n\t\t\tbuildtemplates( target, selector, templates, components )\n\t\t\tregisterComponents()\n\t\t}\n\t}\n}\n\nconst registerComponents = () => {\n\tObject\n\t\t.values( components )\n\t\t.forEach( (component) => {\n\t\t\tconst { name, module, dependencies } = component as any\n\t\t\tif( !customElements.get(name) ){\n\t\t\t\tconst Base = Element(module, dependencies, templates, components)\n\t\t\t\tcustomElements.define(name, Base)\n\t\t\t}\n\t\t})\n}\n"],"names":["parser","DOMParser","wrap","open","node","close","_a","parentNode","insertBefore","_b","nextSibling","textarea","document","createElement","decodeHTML","text","innerHTML","value","rAF","fn","requestAnimationFrame","setTimeout","dup","o","JSON","parse","stringify","purge","d","i","l","n","a","attributes","length","name","childNodes","safe","execute","val","err","config","tags","Template","element","html","regexTags","RegExp","virtual","parseFromString","replace","querySelectorAll","forEach","htmlForeach","getAttribute","htmlFor","htmlIf","htmlInner","htmlClass","forEachInstruction","selector","split","match","varname","object","removeAttribute","setAttribute","script","dataset","scope","type","appendChild","createTextNode","className","trim","body","all","key","Transpile","outerHTML","decodedHTML","Function","_","variable","buildtemplates","target","templates","components","concat","matches","Array","from","reverse","template","content","createTemplateId","id","c","r","Math","random","toString","localName","module","constructor","Promise","__template","then","htmlstring","topics","_async","publish","params","Object","assign","topic","subscribe","method","push","filter","Idiomorph","EMPTY_SET","Set","defaults","morphStyle","callbacks","beforeNodeAdded","noOp","afterNodeAdded","beforeNodeMorphed","afterNodeMorphed","beforeNodeRemoved","afterNodeRemoved","beforeAttributeUpdated","head","style","shouldPreserve","elt","shouldReAppend","shouldRemove","afterHeadMorphed","morphNormalizedContent","oldNode","normalizedNewContent","ctx","block","oldHead","querySelector","newHead","promises","handleHeadElement","ignore","morphChildren","children","bestMatch","newContent","currentElement","firstChild","bestElement","score","newScore","scoreElement","findBestNodeMatch","previousSibling","morphedNode","morphOldNodeTo","stack","added","pop","parentElement","insertSiblings","ignoreValueOfActiveElement","possibleActiveElement","ignoreActiveValue","activeElement","ignoreActive","remove","isSoftMatch","HTMLHeadElement","to","nodeType","fromAttributes","toAttributes","fromAttribute","ignoreAttribute","toAttribute","hasAttribute","nodeValue","HTMLInputElement","fromValue","toValue","syncBooleanAttribute","HTMLOptionElement","HTMLTextAreaElement","syncInputValue","syncNodeFrom","replaceChild","newParent","oldParent","newChild","nextNewChild","insertionPoint","removeIdsFromConsideration","isIdSetMatch","idSetMatch","findIdSetMatch","removeNodesBetween","softMatch","findSoftMatch","tempNode","removeNode","attr","updateType","attributeName","ignoreUpdate","newHeadTag","currentHead","removed","preserved","nodesToAppend","headMergeStyle","srcToNewHeadNodes","Map","newHeadChild","set","currentHeadElt","inNewContent","has","isReAppended","isPreserved","delete","values","newNode","newElt","createRange","createContextualFragment","href","src","resolve","promise","_resolve","addEventListener","removedElement","removeChild","kept","node1","node2","tagName","getIdIntersectionCount","startInclusive","endExclusive","newChildPotentialIdCount","potentialMatch","otherMatchCount","potentialSoftMatch","siblingSoftMatchCount","isIdInConsideration","deadIds","idIsWithinNode","targetNode","idMap","get","idSet","add","sourceSet","matchCount","populateIdMapForNode","nodeParent","idElements","current","createIdMap","oldContent","morph","Document","documentElement","contentWithSvgsRemoved","generatedByIdiomorph","htmlElement","parseContent","normalizedContent","Node","dummyParent","append","normalizeContent","finalConfig","mergeDefaults","createMorphContext","customEvent","window","CustomEvent","data","newEvent","createEvent","initCustomEvent","handler","ev","e","this","detail","__events","apply","args","removeListener","listener","removeEventListener","delegate","callback","parent","delegateTarget","on","selectorOrCallback","call","off","old","trigger","dispatchEvent","bubbles","getOptions","main","unmount","onupdate","view","updateScope","scopeElement","cp","___scope___","lastElementChild","IdiomorphOptions","base","Element","dependencies","HTMLElement","options","elm","initialState","keys","tplid","state","model","eventName","String","emit","shift","newstate","render","getRaw","contains","newdata","newhtml","child","props","html_","clone","cloneNode","Component","returns","default","connectedCallback","array","f","disconnectedCallback","attributeChangedCallback","index","templateConfig","newconfig","register","start","registerComponents","component","customElements","Base","define","literalSections","substs","raw","result","subst","lit","isArray","join"],"mappings":"6OAAM,MAAAA,EAAS,IAAIC,UA0EnB,MAAMC,EAAO,CAACC,EAAMC,EAAMC,aACpB,OAAAC,EAAAF,EAAAG,aAAYD,EAAAE,aAAaL,EAAMC,GACpC,OAAAK,EAAAL,EAAKG,aAALE,EAAiBD,aAAaH,EAAOD,EAAKM,YAAA,EC5ErCC,EAAWC,SAASC,cAAc,YAE3BC,EAAcC,IAC1BJ,EAASK,UAAYD,EACdJ,EAASM,OAGJC,EAAOC,GACfC,sBACIA,sBAAsBD,GAEtBE,WAAWF,EAAI,IAAO,IAWlBG,EAAOC,GACZC,KAAKC,MAAMD,KAAKE,UAAUH,IAIrBI,EAASC,IACrB,IAAsBC,EAAGC,EAAGC,EAAxBC,EAAIJ,EAAEK,WACV,GAAID,EACH,IAAKH,EAAIG,EAAEE,OAAS,EAAGL,GAAK,EAAGA,GAAK,EAEf,mBAATD,EADPG,EAAAC,EAAEH,GAAGM,QAERP,EAAEG,GAAK,MAKV,GADAC,EAAIJ,EAAEQ,WAGL,IADAN,EAAIE,EAAEE,OACDL,EAAI,EAAGA,EAAIC,EAAGD,GAAK,EACjBF,EAAAC,EAAEQ,WAAWP,GAErB,EAGYQ,EAAO,CAACC,EAASC,KAC1B,IAAC,OAAOD,UAAgBE,GAAK,OAAOD,GAAO,EAAE,GC5C3CE,EAAS,CACdC,KAAM,CAAC,KAAM,MAOd,SAAwBC,EAASC,GAEhC,MAAMC,EFXiB,SAAUA,EAAMJ,GAEvC,MAAMK,EAAY,IAAIC,OA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src/component.ts +++ b/src/component.ts @@ -1,5 +1,5 @@ import { type Component } from '..' -import { Idiomorph } from './utils/idiomorph' +import { Idiomorph } from 'idiomorph/dist/idiomorph.esm' import { rAF, dup, safe } from './utils' import { buildtemplates } from './template-system' import { on, off, trigger } from './utils/events' diff --git a/src/utils/idiomorph.ts b/src/utils/idiomorph.ts deleted file mode 100644 index f99c427..0000000 --- a/src/utils/idiomorph.ts +++ /dev/null @@ -1,879 +0,0 @@ -/** - * BSD 2-Clause License - * https://github.com/bigskysoftware/idiomorph - - Copyright (c) 2022, Big Sky Software - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// base IIFE to define idiomorph - - -export const Idiomorph = (function () { - 'use strict'; - - //============================================================================= - // AND NOW IT BEGINS... - //============================================================================= - let EMPTY_SET = new Set(); - - // default configuration values, updatable by users now - let defaults = { - morphStyle: "outerHTML", - callbacks : { - beforeNodeAdded: noOp, - afterNodeAdded: noOp, - beforeNodeMorphed: noOp, - afterNodeMorphed: noOp, - beforeNodeRemoved: noOp, - afterNodeRemoved: noOp, - beforeAttributeUpdated: noOp, - - }, - head: { - style: 'merge', - shouldPreserve: function (elt) { - return elt.getAttribute("im-preserve") === "true"; - }, - shouldReAppend: function (elt) { - return elt.getAttribute("im-re-append") === "true"; - }, - shouldRemove: noOp, - afterHeadMorphed: noOp, - } - }; - - //============================================================================= - // Core Morphing Algorithm - morph, morphNormalizedContent, morphOldNodeTo, morphChildren - //============================================================================= - function morph(oldNode, newContent, config = {}) { - - if (oldNode instanceof Document) { - oldNode = oldNode.documentElement; - } - - if (typeof newContent === 'string') { - newContent = parseContent(newContent); - } - - let normalizedContent = normalizeContent(newContent); - - let ctx = createMorphContext(oldNode, normalizedContent, config); - - return morphNormalizedContent(oldNode, normalizedContent, ctx); - } - - function morphNormalizedContent(oldNode, normalizedNewContent, ctx) { - if (ctx.head.block) { - let oldHead = oldNode.querySelector('head'); - let newHead = normalizedNewContent.querySelector('head'); - if (oldHead && newHead) { - let promises = handleHeadElement(newHead, oldHead, ctx); - // when head promises resolve, call morph again, ignoring the head tag - Promise.all(promises).then(function () { - morphNormalizedContent(oldNode, normalizedNewContent, Object.assign(ctx, { - head: { - block: false, - ignore: true - } - })); - }); - return; - } - } - - if (ctx.morphStyle === "innerHTML") { - - // innerHTML, so we are only updating the children - morphChildren(normalizedNewContent, oldNode, ctx); - return oldNode.children; - - } else if (ctx.morphStyle === "outerHTML" || ctx.morphStyle == null) { - // otherwise find the best element match in the new content, morph that, and merge its siblings - // into either side of the best match - let bestMatch = findBestNodeMatch(normalizedNewContent, oldNode, ctx); - - // stash the siblings that will need to be inserted on either side of the best match - let previousSibling = bestMatch?.previousSibling; - let nextSibling = bestMatch?.nextSibling; - - // morph it - let morphedNode = morphOldNodeTo(oldNode, bestMatch, ctx); - - if (bestMatch) { - // if there was a best match, merge the siblings in too and return the - // whole bunch - return insertSiblings(previousSibling, morphedNode, nextSibling); - } else { - // otherwise nothing was added to the DOM - return [] - } - } else { - throw "Do not understand how to morph style " + ctx.morphStyle; - } - } - - - /** - * @param possibleActiveElement - * @param ctx - * @returns {boolean} - */ - function ignoreValueOfActiveElement(possibleActiveElement, ctx) { - return ctx.ignoreActiveValue && possibleActiveElement === document.activeElement; - } - - /** - * @param oldNode root node to merge content into - * @param newContent new content to merge - * @param ctx the merge context - * @returns {Element} the element that ended up in the DOM - */ - function morphOldNodeTo(oldNode, newContent, ctx) { - if (ctx.ignoreActive && oldNode === document.activeElement) { - // don't morph focused element - } else if (newContent == null) { - if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode; - - oldNode.remove(); - ctx.callbacks.afterNodeRemoved(oldNode); - return null; - } else if (!isSoftMatch(oldNode, newContent)) { - if (ctx.callbacks.beforeNodeRemoved(oldNode) === false) return oldNode; - if (ctx.callbacks.beforeNodeAdded(newContent) === false) return oldNode; - - oldNode.parentElement.replaceChild(newContent, oldNode); - ctx.callbacks.afterNodeAdded(newContent); - ctx.callbacks.afterNodeRemoved(oldNode); - return newContent; - } else { - if (ctx.callbacks.beforeNodeMorphed(oldNode, newContent) === false) return oldNode; - - if (oldNode instanceof HTMLHeadElement && ctx.head.ignore) { - // ignore the head element - } else if (oldNode instanceof HTMLHeadElement && ctx.head.style !== "morph") { - handleHeadElement(newContent, oldNode, ctx); - } else { - syncNodeFrom(newContent, oldNode, ctx); - if (!ignoreValueOfActiveElement(oldNode, ctx)) { - morphChildren(newContent, oldNode, ctx); - } - } - ctx.callbacks.afterNodeMorphed(oldNode, newContent); - return oldNode; - } - } - - /** - * This is the core algorithm for matching up children. The idea is to use id sets to try to match up - * nodes as faithfully as possible. We greedily match, which allows us to keep the algorithm fast, but - * by using id sets, we are able to better match up with content deeper in the DOM. - * - * Basic algorithm is, for each node in the new content: - * - * - if we have reached the end of the old parent, append the new content - * - if the new content has an id set match with the current insertion point, morph - * - search for an id set match - * - if id set match found, morph - * - otherwise search for a "soft" match - * - if a soft match is found, morph - * - otherwise, prepend the new node before the current insertion point - * - * The two search algorithms terminate if competing node matches appear to outweigh what can be achieved - * with the current node. See findIdSetMatch() and findSoftMatch() for details. - * - * @param {Element} newParent the parent element of the new content - * @param {Element } oldParent the old content that we are merging the new content into - * @param ctx the merge context - */ - function morphChildren(newParent, oldParent, ctx) { - - let nextNewChild = newParent.firstChild; - let insertionPoint = oldParent.firstChild; - let newChild; - - // run through all the new content - while (nextNewChild) { - - newChild = nextNewChild; - nextNewChild = newChild.nextSibling; - - // if we are at the end of the exiting parent's children, just append - if (insertionPoint == null) { - if (ctx.callbacks.beforeNodeAdded(newChild) === false) return; - - oldParent.appendChild(newChild); - ctx.callbacks.afterNodeAdded(newChild); - removeIdsFromConsideration(ctx, newChild); - continue; - } - - // if the current node has an id set match then morph - if (isIdSetMatch(newChild, insertionPoint, ctx)) { - morphOldNodeTo(insertionPoint, newChild, ctx); - insertionPoint = insertionPoint.nextSibling; - removeIdsFromConsideration(ctx, newChild); - continue; - } - - // otherwise search forward in the existing old children for an id set match - let idSetMatch = findIdSetMatch(newParent, oldParent, newChild, insertionPoint, ctx); - - // if we found a potential match, remove the nodes until that point and morph - if (idSetMatch) { - insertionPoint = removeNodesBetween(insertionPoint, idSetMatch, ctx); - morphOldNodeTo(idSetMatch, newChild, ctx); - removeIdsFromConsideration(ctx, newChild); - continue; - } - - // no id set match found, so scan forward for a soft match for the current node - let softMatch = findSoftMatch(newParent, oldParent, newChild, insertionPoint, ctx); - - // if we found a soft match for the current node, morph - if (softMatch) { - insertionPoint = removeNodesBetween(insertionPoint, softMatch, ctx); - morphOldNodeTo(softMatch, newChild, ctx); - removeIdsFromConsideration(ctx, newChild); - continue; - } - - // abandon all hope of morphing, just insert the new child before the insertion point - // and move on - if (ctx.callbacks.beforeNodeAdded(newChild) === false) return; - - oldParent.insertBefore(newChild, insertionPoint); - ctx.callbacks.afterNodeAdded(newChild); - removeIdsFromConsideration(ctx, newChild); - } - - // remove any remaining old nodes that didn't match up with new content - while (insertionPoint !== null) { - - let tempNode = insertionPoint; - insertionPoint = insertionPoint.nextSibling; - removeNode(tempNode, ctx); - } - } - - //============================================================================= - // Attribute Syncing Code - //============================================================================= - - /** - * @param attr {String} the attribute to be mutated - * @param to {Element} the element that is going to be updated - * @param updateType {("update"|"remove")} - * @param ctx the merge context - * @returns {boolean} true if the attribute should be ignored, false otherwise - */ - function ignoreAttribute(attr, to, updateType, ctx) { - if(attr === 'value' && ctx.ignoreActiveValue && to === document.activeElement){ - return true; - } - return ctx.callbacks.beforeAttributeUpdated(attr, to, updateType) === false; - } - - /** - * syncs a given node with another node, copying over all attributes and - * inner element state from the 'from' node to the 'to' node - * - * @param {Element} from the element to copy attributes & state from - * @param {Element} to the element to copy attributes & state to - * @param ctx the merge context - */ - function syncNodeFrom(from, to, ctx) { - let type = from.nodeType - - // if is an element type, sync the attributes from the - // new node into the new node - if (type === 1 /* element type */) { - const fromAttributes = from.attributes; - const toAttributes = to.attributes; - for (const fromAttribute of fromAttributes) { - if (ignoreAttribute(fromAttribute.name, to, 'update', ctx)) { - continue; - } - if (to.getAttribute(fromAttribute.name) !== fromAttribute.value) { - to.setAttribute(fromAttribute.name, fromAttribute.value); - } - } - // iterate backwards to avoid skipping over items when a delete occurs - for (let i = toAttributes.length - 1; 0 <= i; i--) { - const toAttribute = toAttributes[i]; - if (ignoreAttribute(toAttribute.name, to, 'remove', ctx)) { - continue; - } - if (!from.hasAttribute(toAttribute.name)) { - to.removeAttribute(toAttribute.name); - } - } - } - - // sync text nodes - if (type === 8 /* comment */ || type === 3 /* text */) { - if (to.nodeValue !== from.nodeValue) { - to.nodeValue = from.nodeValue; - } - } - - if (!ignoreValueOfActiveElement(to, ctx)) { - // sync input values - syncInputValue(from, to, ctx); - } - } - - /** - * @param from {Element} element to sync the value from - * @param to {Element} element to sync the value to - * @param attributeName {String} the attribute name - * @param ctx the merge context - */ - function syncBooleanAttribute(from, to, attributeName, ctx) { - if (from[attributeName] !== to[attributeName]) { - let ignoreUpdate = ignoreAttribute(attributeName, to, 'update', ctx); - if (!ignoreUpdate) { - to[attributeName] = from[attributeName]; - } - if (from[attributeName]) { - if (!ignoreUpdate) { - to.setAttribute(attributeName, from[attributeName]); - } - } else { - if (!ignoreAttribute(attributeName, to, 'remove', ctx)) { - to.removeAttribute(attributeName); - } - } - } - } - - /** - * NB: many bothans died to bring us information: - * - * https://github.com/patrick-steele-idem/morphdom/blob/master/src/specialElHandlers.js - * https://github.com/choojs/nanomorph/blob/master/lib/morph.jsL113 - * - * @param from {Element} the element to sync the input value from - * @param to {Element} the element to sync the input value to - * @param ctx the merge context - */ - function syncInputValue(from, to, ctx) { - if (from instanceof HTMLInputElement && - to instanceof HTMLInputElement && - from.type !== 'file') { - - let fromValue = from.value; - let toValue = to.value; - - // sync boolean attributes - syncBooleanAttribute(from, to, 'checked', ctx); - syncBooleanAttribute(from, to, 'disabled', ctx); - - if (!from.hasAttribute('value')) { - if (!ignoreAttribute('value', to, 'remove', ctx)) { - to.value = ''; - to.removeAttribute('value'); - } - } else if (fromValue !== toValue) { - if (!ignoreAttribute('value', to, 'update', ctx)) { - to.setAttribute('value', fromValue); - to.value = fromValue; - } - } - } else if (from instanceof HTMLOptionElement) { - syncBooleanAttribute(from, to, 'selected', ctx) - } else if (from instanceof HTMLTextAreaElement && to instanceof HTMLTextAreaElement) { - let fromValue = from.value; - let toValue = to.value; - if (ignoreAttribute('value', to, 'update', ctx)) { - return; - } - if (fromValue !== toValue) { - to.value = fromValue; - } - if (to.firstChild && to.firstChild.nodeValue !== fromValue) { - to.firstChild.nodeValue = fromValue - } - } - } - - //============================================================================= - // the HEAD tag can be handled specially, either w/ a 'merge' or 'append' style - //============================================================================= - function handleHeadElement(newHeadTag, currentHead, ctx) { - - let added = [] - let removed = [] - let preserved = [] - let nodesToAppend = [] - - let headMergeStyle = ctx.head.style; - - // put all new head elements into a Map, by their outerHTML - let srcToNewHeadNodes = new Map(); - for (const newHeadChild of newHeadTag.children) { - srcToNewHeadNodes.set(newHeadChild.outerHTML, newHeadChild); - } - - // for each elt in the current head - for (const currentHeadElt of currentHead.children) { - - // If the current head element is in the map - let inNewContent = srcToNewHeadNodes.has(currentHeadElt.outerHTML); - let isReAppended = ctx.head.shouldReAppend(currentHeadElt); - let isPreserved = ctx.head.shouldPreserve(currentHeadElt); - if (inNewContent || isPreserved) { - if (isReAppended) { - // remove the current version and let the new version replace it and re-execute - removed.push(currentHeadElt); - } else { - // this element already exists and should not be re-appended, so remove it from - // the new content map, preserving it in the DOM - srcToNewHeadNodes.delete(currentHeadElt.outerHTML); - preserved.push(currentHeadElt); - } - } else { - if (headMergeStyle === "append") { - // we are appending and this existing element is not new content - // so if and only if it is marked for re-append do we do anything - if (isReAppended) { - removed.push(currentHeadElt); - nodesToAppend.push(currentHeadElt); - } - } else { - // if this is a merge, we remove this content since it is not in the new head - if (ctx.head.shouldRemove(currentHeadElt) !== false) { - removed.push(currentHeadElt); - } - } - } - } - - // Push the remaining new head elements in the Map into the - // nodes to append to the head tag - nodesToAppend.push(...srcToNewHeadNodes.values()); - log("to append: ", nodesToAppend); - - let promises = []; - for (const newNode of nodesToAppend) { - log("adding: ", newNode); - let newElt = document.createRange().createContextualFragment(newNode.outerHTML).firstChild; - log(newElt); - if (ctx.callbacks.beforeNodeAdded(newElt) !== false) { - if (newElt.href || newElt.src) { - let resolve = null; - let promise = new Promise(function (_resolve) { - resolve = _resolve; - }); - newElt.addEventListener('load', function () { - resolve(); - }); - promises.push(promise); - } - currentHead.appendChild(newElt); - ctx.callbacks.afterNodeAdded(newElt); - added.push(newElt); - } - } - - // remove all removed elements, after we have appended the new elements to avoid - // additional network requests for things like style sheets - for (const removedElement of removed) { - if (ctx.callbacks.beforeNodeRemoved(removedElement) !== false) { - currentHead.removeChild(removedElement); - ctx.callbacks.afterNodeRemoved(removedElement); - } - } - - ctx.head.afterHeadMorphed(currentHead, {added: added, kept: preserved, removed: removed}); - return promises; - } - - //============================================================================= - // Misc - //============================================================================= - - function log() { - //console.log(arguments); - } - - function noOp() { - } - - /* - Deep merges the config object and the Idiomoroph.defaults object to - produce a final configuration object - */ - function mergeDefaults(config) { - let finalConfig = {}; - // copy top level stuff into final config - Object.assign(finalConfig, defaults); - Object.assign(finalConfig, config); - - // copy callbacks into final config (do this to deep merge the callbacks) - finalConfig.callbacks = {}; - Object.assign(finalConfig.callbacks, defaults.callbacks); - Object.assign(finalConfig.callbacks, config.callbacks); - - // copy head config into final config (do this to deep merge the head) - finalConfig.head = {}; - Object.assign(finalConfig.head, defaults.head); - Object.assign(finalConfig.head, config.head); - return finalConfig; - } - - function createMorphContext(oldNode, newContent, config) { - config = mergeDefaults(config); - return { - target: oldNode, - newContent: newContent, - config: config, - morphStyle: config.morphStyle, - ignoreActive: config.ignoreActive, - ignoreActiveValue: config.ignoreActiveValue, - idMap: createIdMap(oldNode, newContent), - deadIds: new Set(), - callbacks: config.callbacks, - head: config.head - } - } - - function isIdSetMatch(node1, node2, ctx) { - if (node1 == null || node2 == null) { - return false; - } - if (node1.nodeType === node2.nodeType && node1.tagName === node2.tagName) { - if (node1.id !== "" && node1.id === node2.id) { - return true; - } else { - return getIdIntersectionCount(ctx, node1, node2) > 0; - } - } - return false; - } - - function isSoftMatch(node1, node2) { - if (node1 == null || node2 == null) { - return false; - } - return node1.nodeType === node2.nodeType && node1.tagName === node2.tagName - } - - function removeNodesBetween(startInclusive, endExclusive, ctx) { - while (startInclusive !== endExclusive) { - let tempNode = startInclusive; - startInclusive = startInclusive.nextSibling; - removeNode(tempNode, ctx); - } - removeIdsFromConsideration(ctx, endExclusive); - return endExclusive.nextSibling; - } - - //============================================================================= - // Scans forward from the insertionPoint in the old parent looking for a potential id match - // for the newChild. We stop if we find a potential id match for the new child OR - // if the number of potential id matches we are discarding is greater than the - // potential id matches for the new child - //============================================================================= - function findIdSetMatch(newContent, oldParent, newChild, insertionPoint, ctx) { - - // max id matches we are willing to discard in our search - let newChildPotentialIdCount = getIdIntersectionCount(ctx, newChild, oldParent); - - let potentialMatch = null; - - // only search forward if there is a possibility of an id match - if (newChildPotentialIdCount > 0) { - let potentialMatch = insertionPoint; - // if there is a possibility of an id match, scan forward - // keep track of the potential id match count we are discarding (the - // newChildPotentialIdCount must be greater than this to make it likely - // worth it) - let otherMatchCount = 0; - while (potentialMatch != null) { - - // If we have an id match, return the current potential match - if (isIdSetMatch(newChild, potentialMatch, ctx)) { - return potentialMatch; - } - - // computer the other potential matches of this new content - otherMatchCount += getIdIntersectionCount(ctx, potentialMatch, newContent); - if (otherMatchCount > newChildPotentialIdCount) { - // if we have more potential id matches in _other_ content, we - // do not have a good candidate for an id match, so return null - return null; - } - - // advanced to the next old content child - potentialMatch = potentialMatch.nextSibling; - } - } - return potentialMatch; - } - - //============================================================================= - // Scans forward from the insertionPoint in the old parent looking for a potential soft match - // for the newChild. We stop if we find a potential soft match for the new child OR - // if we find a potential id match in the old parents children OR if we find two - // potential soft matches for the next two pieces of new content - //============================================================================= - function findSoftMatch(newContent, oldParent, newChild, insertionPoint, ctx) { - - let potentialSoftMatch = insertionPoint; - let nextSibling = newChild.nextSibling; - let siblingSoftMatchCount = 0; - - while (potentialSoftMatch != null) { - - if (getIdIntersectionCount(ctx, potentialSoftMatch, newContent) > 0) { - // the current potential soft match has a potential id set match with the remaining new - // content so bail out of looking - return null; - } - - // if we have a soft match with the current node, return it - if (isSoftMatch(newChild, potentialSoftMatch)) { - return potentialSoftMatch; - } - - if (isSoftMatch(nextSibling, potentialSoftMatch)) { - // the next new node has a soft match with this node, so - // increment the count of future soft matches - siblingSoftMatchCount++; - nextSibling = nextSibling.nextSibling; - - // If there are two future soft matches, bail to allow the siblings to soft match - // so that we don't consume future soft matches for the sake of the current node - if (siblingSoftMatchCount >= 2) { - return null; - } - } - - // advanced to the next old content child - potentialSoftMatch = potentialSoftMatch.nextSibling; - } - - return potentialSoftMatch; - } - - function parseContent(newContent) { - let parser = new DOMParser(); - - // remove svgs to avoid false-positive matches on head, etc. - let contentWithSvgsRemoved = newContent.replace(/]*>|>)([\s\S]*?)<\/svg>/gim, ''); - - // if the newContent contains a html, head or body tag, we can simply parse it w/o wrapping - if (contentWithSvgsRemoved.match(/<\/html>/) || contentWithSvgsRemoved.match(/<\/head>/) || contentWithSvgsRemoved.match(/<\/body>/)) { - let content = parser.parseFromString(newContent, "text/html"); - // if it is a full HTML document, return the document itself as the parent container - if (contentWithSvgsRemoved.match(/<\/html>/)) { - content.generatedByIdiomorph = true; - return content; - } else { - // otherwise return the html element as the parent container - let htmlElement = content.firstChild; - if (htmlElement) { - htmlElement.generatedByIdiomorph = true; - return htmlElement; - } else { - return null; - } - } - } else { - // if it is partial HTML, wrap it in a template tag to provide a parent element and also to help - // deal with touchy tags like tr, tbody, etc. - let responseDoc = parser.parseFromString("", "text/html"); - let content = responseDoc.body.querySelector('template').content; - content.generatedByIdiomorph = true; - return content - } - } - - function normalizeContent(newContent) { - if (newContent == null) { - // noinspection UnnecessaryLocalVariableJS - const dummyParent = document.createElement('div'); - return dummyParent; - } else if (newContent.generatedByIdiomorph) { - // the template tag created by idiomorph parsing can serve as a dummy parent - return newContent; - } else if (newContent instanceof Node) { - // a single node is added as a child to a dummy parent - const dummyParent = document.createElement('div'); - dummyParent.append(newContent); - return dummyParent; - } else { - // all nodes in the array or HTMLElement collection are consolidated under - // a single dummy parent element - const dummyParent = document.createElement('div'); - for (const elt of [...newContent]) { - dummyParent.append(elt); - } - return dummyParent; - } - } - - function insertSiblings(previousSibling, morphedNode, nextSibling) { - let stack = [] - let added = [] - while (previousSibling != null) { - stack.push(previousSibling); - previousSibling = previousSibling.previousSibling; - } - while (stack.length > 0) { - let node = stack.pop(); - added.push(node); // push added preceding siblings on in order and insert - morphedNode.parentElement.insertBefore(node, morphedNode); - } - added.push(morphedNode); - while (nextSibling != null) { - stack.push(nextSibling); - added.push(nextSibling); // here we are going in order, so push on as we scan, rather than add - nextSibling = nextSibling.nextSibling; - } - while (stack.length > 0) { - morphedNode.parentElement.insertBefore(stack.pop(), morphedNode.nextSibling); - } - return added; - } - - function findBestNodeMatch(newContent, oldNode, ctx) { - let currentElement; - currentElement = newContent.firstChild; - let bestElement = currentElement; - let score = 0; - while (currentElement) { - let newScore = scoreElement(currentElement, oldNode, ctx); - if (newScore > score) { - bestElement = currentElement; - score = newScore; - } - currentElement = currentElement.nextSibling; - } - return bestElement; - } - - function scoreElement(node1, node2, ctx) { - if (isSoftMatch(node1, node2)) { - return .5 + getIdIntersectionCount(ctx, node1, node2); - } - return 0; - } - - function removeNode(tempNode, ctx) { - removeIdsFromConsideration(ctx, tempNode) - if (ctx.callbacks.beforeNodeRemoved(tempNode) === false) return; - - tempNode.remove(); - ctx.callbacks.afterNodeRemoved(tempNode); - } - - //============================================================================= - // ID Set Functions - //============================================================================= - - function isIdInConsideration(ctx, id) { - return !ctx.deadIds.has(id); - } - - function idIsWithinNode(ctx, id, targetNode) { - let idSet = ctx.idMap.get(targetNode) || EMPTY_SET; - return idSet.has(id); - } - - function removeIdsFromConsideration(ctx, node) { - let idSet = ctx.idMap.get(node) || EMPTY_SET; - for (const id of idSet) { - ctx.deadIds.add(id); - } - } - - function getIdIntersectionCount(ctx, node1, node2) { - let sourceSet = ctx.idMap.get(node1) || EMPTY_SET; - let matchCount = 0; - for (const id of sourceSet) { - // a potential match is an id in the source and potentialIdsSet, but - // that has not already been merged into the DOM - if (isIdInConsideration(ctx, id) && idIsWithinNode(ctx, id, node2)) { - ++matchCount; - } - } - return matchCount; - } - - /** - * A bottom up algorithm that finds all elements with ids inside of the node - * argument and populates id sets for those nodes and all their parents, generating - * a set of ids contained within all nodes for the entire hierarchy in the DOM - * - * @param node {Element} - * @param {Map>} idMap - */ - function populateIdMapForNode(node, idMap) { - let nodeParent = node.parentElement; - // find all elements with an id property - let idElements = node.querySelectorAll('[id]'); - for (const elt of idElements) { - let current = elt; - // walk up the parent hierarchy of that element, adding the id - // of element to the parent's id set - while (current !== nodeParent && current != null) { - let idSet = idMap.get(current); - // if the id set doesn't exist, create it and insert it in the map - if (idSet == null) { - idSet = new Set(); - idMap.set(current, idSet); - } - idSet.add(elt.id); - current = current.parentElement; - } - } - } - - /** - * This function computes a map of nodes to all ids contained within that node (inclusive of the - * node). This map can be used to ask if two nodes have intersecting sets of ids, which allows - * for a looser definition of "matching" than tradition id matching, and allows child nodes - * to contribute to a parent nodes matching. - * - * @param {Element} oldContent the old content that will be morphed - * @param {Element} newContent the new content to morph to - * @returns {Map>} a map of nodes to id sets for the - */ - function createIdMap(oldContent, newContent) { - let idMap = new Map(); - populateIdMapForNode(oldContent, idMap); - populateIdMapForNode(newContent, idMap); - return idMap; - } - - //============================================================================= - // This is what ends up becoming the Idiomorph global object - //============================================================================= - return { - morph, - defaults - } -})();