UNPKG

jails-js

Version:

Jails - Elegant and Minimalistic Javascript Application Library

3 lines (2 loc) 17 kB
!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";var t=Object.defineProperty,n=Object.getOwnPropertySymbols,r=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,i=(e,n,r)=>n in e?t(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r,a=(e,t)=>{for(var a in t||(t={}))r.call(t,a)&&i(e,a,t[a]);if(n)for(var a of n(t))o.call(t,a)&&i(e,a,t[a]);return e};let l;const s={scope:{}},c=e=>(l=l||document.createElement("textarea"),l.innerHTML=e,l.value),u=()=>Math.random().toString(36).substring(2,9),d=(e,t)=>{try{return e()}catch(n){return t||""}};var f=function(){const e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:e=>"true"===e.getAttribute("im-preserve"),shouldReAppend:e=>"true"===e.getAttribute("im-re-append"),shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};const n=function(){function e(e,t,n,o){if(!1===o.callbacks.beforeNodeAdded(t))return null;if(o.idMap.has(t)){const i=document.createElement(t.tagName);return e.insertBefore(i,n),r(i,t,o),o.callbacks.afterNodeAdded(i),i}{const r=document.importNode(t,!0);return e.insertBefore(r,n),o.callbacks.afterNodeAdded(r),r}}const t=function(){function e(e,t,n){let r=e.idMap.get(t),o=e.idMap.get(n);if(!o||!r)return!1;for(const i of r)if(o.has(i))return!0;return!1}function t(e,t){const n=e,r=t;return n.nodeType===r.nodeType&&n.tagName===r.tagName&&(!n.id||n.id===r.id)}return function(n,r,o,i){let a=null,l=r.nextSibling,s=0,c=o;for(;c&&c!=i;){if(t(c,r)){if(e(n,c,r))return c;null===a&&(n.idMap.has(c)||(a=c))}if(null===a&&l&&t(c,l)&&(s++,l=l.nextSibling,s>=2&&(a=void 0)),c.contains(document.activeElement))break;c=c.nextSibling}return a||null}}();function n(e,t){var n;if(e.idMap.has(t))a(e.pantry,t,null);else{if(!1===e.callbacks.beforeNodeRemoved(t))return;null==(n=t.parentNode)||n.removeChild(t),e.callbacks.afterNodeRemoved(t)}}function o(e,t,r){let o=t;for(;o&&o!==r;){let t=o;o=o.nextSibling,n(e,t)}return o}function i(e,t,n,r){const o=r.target.id===t&&r.target||r.target.querySelector(`[id="${t}"]`)||r.pantry.querySelector(`[id="${t}"]`);return function(e,t){const n=e.id;for(;e=e.parentNode;){let r=t.idMap.get(e);r&&(r.delete(n),r.size||t.idMap.delete(e))}}(o,r),a(e,o,n),o}function a(e,t,n){if(e.moveBefore)try{e.moveBefore(t,n)}catch(r){e.insertBefore(t,n)}else e.insertBefore(t,n)}return function(a,l,s,c=null,u=null){l instanceof HTMLTemplateElement&&s instanceof HTMLTemplateElement&&(l=l.content,s=s.content),c||(c=l.firstChild);for(const n of s.childNodes){if(c&&c!=u){const e=t(a,n,c,u);if(e){e!==c&&o(a,c,e),r(e,n,a),c=e.nextSibling;continue}}if(n instanceof Element&&a.persistentIds.has(n.id)){const e=i(l,n.id,c,a);r(e,n,a),c=e.nextSibling;continue}const s=e(l,n,c,a);s&&(c=s.nextSibling)}for(;c&&c!=u;){const e=c;c=c.nextSibling,n(a,e)}}}(),r=function(){function e(e,n,r,o){const i=n[r];if(i!==e[r]){const a=t(r,e,"update",o);a||(e[r]=n[r]),i?a||e.setAttribute(r,""):t(r,e,"remove",o)||e.removeAttribute(r)}}function t(e,t,n,r){return!("value"!==e||!r.ignoreActiveValue||t!==document.activeElement)||!1===r.callbacks.beforeAttributeUpdated(e,t,n)}function r(e,t){return!!t.ignoreActiveValue&&e===document.activeElement&&e!==document.body}return function(i,a,l){return l.ignoreActive&&i===document.activeElement?null:(!1===l.callbacks.beforeNodeMorphed(i,a)||(i instanceof HTMLHeadElement&&l.head.ignore||(i instanceof HTMLHeadElement&&"morph"!==l.head.style?o(i,a,l):(!function(n,o,i){let a=o.nodeType;if(1===a){const a=n,l=o,s=a.attributes,c=l.attributes;for(const e of c)t(e.name,a,"update",i)||a.getAttribute(e.name)!==e.value&&a.setAttribute(e.name,e.value);for(let e=s.length-1;0<=e;e--){const n=s[e];if(n&&!l.hasAttribute(n.name)){if(t(n.name,a,"remove",i))continue;a.removeAttribute(n.name)}}r(a,i)||function(n,r,o){if(n instanceof HTMLInputElement&&r instanceof HTMLInputElement&&"file"!==r.type){let i=r.value,a=n.value;e(n,r,"checked",o),e(n,r,"disabled",o),r.hasAttribute("value")?a!==i&&(t("value",n,"update",o)||(n.setAttribute("value",i),n.value=i)):t("value",n,"remove",o)||(n.value="",n.removeAttribute("value"))}else if(n instanceof HTMLOptionElement&&r instanceof HTMLOptionElement)e(n,r,"selected",o);else if(n instanceof HTMLTextAreaElement&&r instanceof HTMLTextAreaElement){let e=r.value,i=n.value;if(t("value",n,"update",o))return;e!==i&&(n.value=e),n.firstChild&&n.firstChild.nodeValue!==e&&(n.firstChild.nodeValue=e)}}(a,l,i)}8!==a&&3!==a||n.nodeValue!==o.nodeValue&&(n.nodeValue=o.nodeValue)}(i,a,l),r(i,l)||n(l,i,a))),l.callbacks.afterNodeMorphed(i,a)),i)}}();function o(e,t,n){let r=[],o=[],i=[],a=[],l=new Map;for(const c of t.children)l.set(c.outerHTML,c);for(const c of e.children){let e=l.has(c.outerHTML),t=n.head.shouldReAppend(c),r=n.head.shouldPreserve(c);e||r?t?o.push(c):(l.delete(c.outerHTML),i.push(c)):"append"===n.head.style?t&&(o.push(c),a.push(c)):!1!==n.head.shouldRemove(c)&&o.push(c)}a.push(...l.values());let s=[];for(const c of a){let t=document.createRange().createContextualFragment(c.outerHTML).firstChild;if(!1!==n.callbacks.beforeNodeAdded(t)){if("href"in t&&t.href||"src"in t&&t.src){let e,n=new Promise((function(t){e=t}));t.addEventListener("load",(function(){e()})),s.push(n)}e.appendChild(t),n.callbacks.afterNodeAdded(t),r.push(t)}}for(const c of o)!1!==n.callbacks.beforeNodeRemoved(c)&&(e.removeChild(c),n.callbacks.afterNodeRemoved(c));return n.head.afterHeadMorphed(e,{added:r,kept:i,removed:o}),s}const i=function(){function e(){const e=document.createElement("div");return e.hidden=!0,document.body.insertAdjacentElement("afterend",e),e}function n(e){let t=Array.from(e.querySelectorAll("[id]"));return e.id&&t.push(e),t}function r(e,t,n,r){for(const o of r)if(t.has(o.id)){let t=o;for(;t;){let r=e.get(t);if(null==r&&(r=new Set,e.set(t,r)),r.add(o.id),t===n)break;t=t.parentElement}}}return function(o,i,a){const{persistentIds:l,idMap:s}=function(e,t){const o=n(e),i=n(t),a=function(e,t){let n=new Set,r=new Map;for(const{id:i,tagName:a}of e)r.has(i)?n.add(i):r.set(i,a);let o=new Set;for(const{id:i,tagName:a}of t)o.has(i)?n.add(i):r.get(i)===a&&o.add(i);for(const i of n)o.delete(i);return o}(o,i);let l=new Map;r(l,a,e,o);const s=t.__idiomorphRoot||t;return r(l,a,s,i),{persistentIds:a,idMap:l}}(o,i),c=function(e){let n=Object.assign({},t);return Object.assign(n,e),n.callbacks=Object.assign({},t.callbacks,e.callbacks),n.head=Object.assign({},t.head,e.head),n}(a),u=c.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(u))throw`Do not understand how to morph style ${u}`;return{target:o,newContent:i,config:c,morphStyle:u,ignoreActive:c.ignoreActive,ignoreActiveValue:c.ignoreActiveValue,restoreFocus:c.restoreFocus,idMap:s,persistentIds:l,pantry:e(),callbacks:c.callbacks,head:c.head}}}(),{normalizeElement:a,normalizeParent:l}=function(){const e=new WeakSet;class t{constructor(e){this.originalNode=e,this.realParentNode=e.parentNode,this.previousSibling=e.previousSibling,this.nextSibling=e.nextSibling}get childNodes(){const e=[];let t=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;t&&t!=this.nextSibling;)e.push(t),t=t.nextSibling;return e}querySelectorAll(e){return this.childNodes.reduce(((t,n)=>{if(n instanceof Element){n.matches(e)&&t.push(n);const r=n.querySelectorAll(e);for(let e=0;e<r.length;e++)t.push(r[e])}return t}),[])}insertBefore(e,t){return this.realParentNode.insertBefore(e,t)}moveBefore(e,t){return this.realParentNode.moveBefore(e,t)}get __idiomorphRoot(){return this.originalNode}}return{normalizeElement:function(e){return e instanceof Document?e.documentElement:e},normalizeParent:function n(r){if(null==r)return document.createElement("div");if("string"==typeof r)return n(function(t){let n=new DOMParser,r=t.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(r.match(/<\/html>/)||r.match(/<\/head>/)||r.match(/<\/body>/)){let o=n.parseFromString(t,"text/html");if(r.match(/<\/html>/))return e.add(o),o;{let t=o.firstChild;return t&&e.add(t),t}}{let r=n.parseFromString("<body><template>"+t+"</template></body>","text/html").body.querySelector("template").content;return e.add(r),r}}(r));if(e.has(r))return r;if(r instanceof Node){if(r.parentNode)return new t(r);{const e=document.createElement("div");return e.append(r),e}}{const e=document.createElement("div");for(const t of[...r])e.append(t);return e}}}}();return{morph:function(e,t,r={}){e=a(e);const s=l(t),c=i(e,s,r),u=function(e,t){var n;if(!e.config.restoreFocus)return t();let r=document.activeElement;if(!(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement))return t();const{id:o,selectionStart:i,selectionEnd:a}=r,l=t();o&&o!==(null==(n=document.activeElement)?void 0:n.id)&&(r=e.target.querySelector(`[id="${o}"]`),null==r||r.focus());r&&!r.selectionEnd&&a&&r.setSelectionRange(i,a);return l}(c,(()=>function(e,t,n,r){if(e.head.block){const i=t.querySelector("head"),a=n.querySelector("head");if(i&&a){const t=o(i,a,e);return Promise.all(t).then((()=>{const t=Object.assign(e,{head:{block:!1,ignore:!0}});return r(t)}))}}return r(e)}(c,e,s,(t=>"innerHTML"===t.morphStyle?(n(t,e,s),Array.from(e.childNodes)):function(e,t,r){const o=l(t);return n(e,o,r,t,t.nextSibling),Array.from(o.childNodes)}(t,e,s)))));return c.pantry.remove(),u},defaults:t}}();const m={},p={},h=(e,t)=>{p[e]=g(t)?Object.assign({},p[e],t):t,m[e]&&m[e].forEach((e=>e(t)))},b=(e,t)=>(m[e]=m[e]||[],m[e].push(t),e in p&&t(p[e]),()=>{m[e]=m[e].filter((e=>e!=t))}),g=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),v=({name:e,module:t,dependencies:n,node:r,templates:o,signal:i,register:l})=>{var c;let u,m=[],p=null,g=[];const v=t.model||{},A=new Function(`return ${r.getAttribute("html-model")||"{}"}`)(),E=r.getAttribute("tplid"),N=r.getAttribute("html-scopeid"),S=o[E],M=s.scope[N],T=(_=(null==(c=null==t?void 0:t.model)?void 0:c.apply)?v({elm:r,initialState:A}):v,JSON.parse(JSON.stringify(_)));var _;const $=Object.assign({},M,T,A),k=t.view?t.view:e=>e,w={name:e,model:T,elm:r,template:S.template,dependencies:n,publish:h,subscribe:b,main(e){r.addEventListener(":mount",e)},state:{protected(e){if(!e)return m;m=e},save(e){e.constructor===Function?e($):Object.assign($,e)},set(e){if(!document.body.contains(r))return;e.constructor===Function?e($):Object.assign($,e);const t=Object.assign({},$,M);return new Promise((e=>{L(t,(()=>e(t)))}))},get:()=>Object.assign({},$)},dataset(e,t){const n=t||e,o=(t?e:r).dataset[n];if("true"===o)return!0;if("false"===o)return!1;if(!isNaN(o)&&""!==o.trim())return Number(o);try{return new Function("return ("+o+")")()}catch(i){}try{return JSON.parse(o)}catch(i){}return o},on(e,t,n){const o=e.match(/\[(.*)\]/);if(o)return g.push({target:n?t:null,callback:n||t}),void(p||(p=new MutationObserver((e=>{for(const t of e)if("attributes"===t.type){const e=t.attributeName;e===o[1]&&g.forEach((n=>{(n.target?r.querySelectorAll(n.target):[r]).forEach((r=>{r==t.target&&n.callback({target:t.target,attribute:e,value:t.target.getAttribute(e)})}))}))}})),p.observe(r,{attributes:!0,subtree:!0}),r.addEventListener(":unmount",(()=>{g=[],p.disconnect()}))));n?(n.handler=e=>{const o=e.detail||{};let i=e.target;for(;i&&(i.matches(t)&&(e.delegateTarget=i,n.apply(r,[e].concat(o.args))),i!==r);)i=i.parentNode},r.addEventListener(e,n.handler,{signal:i,capture:"focus"==e||"blur"==e||"mouseenter"==e||"mouseleave"==e})):(t.handler=e=>{e.delegateTarget=r,t.apply(r,[e].concat(e.detail.args))},r.addEventListener(e,t.handler,{signal:i}))},off(e,t){t.handler&&r.removeEventListener(e,t.handler)},trigger(e,t,n){t.constructor===String?Array.from(r.querySelectorAll(t)).forEach((t=>{t.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:{args:n}}))})):r.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:{args:n}}))},emit(e,t){r.dispatchEvent(new CustomEvent(e,{bubbles:!0,detail:{args:t}}))},unmount(e){r.addEventListener(":unmount",e)},innerHTML(e,t){const n=t?e:r,o=n.cloneNode(),i=t||e;o.innerHTML=i,f.morph(n,o)}},L=(e,t=()=>{})=>{clearTimeout(u),u=setTimeout((()=>{const n=S.render.call(a(a({},e),k(e)),r,d,s);f.morph(r,n,y(r,l)),Promise.resolve().then((()=>{r.querySelectorAll("[tplid]").forEach((t=>{const n=l.get(t);n&&(n.state.protected().forEach((t=>delete e[t])),n.state.set(e))})),Promise.resolve().then((()=>{s.scope={},t()}))}))}))};return L($),l.set(r,w),t.default(w)},y=(e,t)=>({callbacks:{beforeNodeMorphed(n){if(1===n.nodeType){if("html-static"in n.attributes)return!1;if(t.get(n)&&n!==e)return!1}}}}),A=new WeakMap,E=({component:e,templates:t,start:n})=>{const{name:r,module:o,dependencies:i}=e;return class extends HTMLElement{constructor(){super()}connectedCallback(){this.abortController=new AbortController,this.getAttribute("tplid")||n(this.parentNode);const e=v({node:this,name:r,module:o,dependencies:i,templates:t,signal:this.abortController.signal,register:A});e&&e.constructor===Promise?e.then((()=>{this.dispatchEvent(new CustomEvent(":mount"))})):this.dispatchEvent(new CustomEvent(":mount"))}disconnectedCallback(){this.dispatchEvent(new CustomEvent(":unmount")),this.abortController.abort()}}},N={tags:["{{","}}"]},S={},M=/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,T=/html-([^\s]*?)="(.*?)"/g,_=e=>{const t=JSON.stringify(e);return new Function("$element","safe","$g",`\n\t\tvar $data = this;\n\t\twith( $data ){\n\t\t\tvar output=${t.replace(/%%_=(.+?)_%%/g,(function(e,t){return'"+safe(function(){return '+c(t)+';})+"'})).replace(/%%_(.+?)_%%/g,(function(e,t){return'";'+c(t)+'\noutput+="'}))};return output;\n\t\t}\n\t`)},$=(e,t,n)=>{const r=t.join(",");e.querySelectorAll(r).forEach((e=>{"template"!==e.localName?(e.hasAttribute("html-if")&&!e.id&&(e.id=u()),e.localName in n&&e.setAttribute("tplid",u())):$(e.content,t,n)}))},k=e=>e.replace(/jails___scope-id/g,"%%_=$scopeid_%%").replace(new RegExp(`\\${N.tags[0]}(.+?)\\${N.tags[1]}`,"g"),"%%_=$1_%%").replace(M,"%%_if(safe(function(){ return $2 })){_%%$1%%_}_%%").replace(T,((e,t,n)=>["key","model","scopeid"].includes(t)?e:n?`${t}="%%_=safe(function(){ return ${n=n.replace(/^{|}$/g,"")} })_%%"`:e)),w=e=>{e.querySelectorAll("template, [html-for], [html-if], [html-inner], [html-class]").forEach((e=>{const t=e.getAttribute("html-for"),n=e.getAttribute("html-if"),r=e.getAttribute("html-inner"),o=e.getAttribute("html-class");if(t){e.removeAttribute("html-for");const n=t.match(/(.*)\sin\s(.*)/)||"",r=n[1],o=n[2],i=o.split(/\./).shift(),a=document.createTextNode(`%%_ ;(function(){ var $index = 0; for(var $key in safe(function(){ return ${o} }) ){ var $scopeid = Math.random().toString(36).substring(2, 9); var ${r} = ${o}[$key]; $g.scope[$scopeid] = Object.assign({}, { ${i}: ${i} }, { ${r} :${r}, $index: $index, $key: $key }); _%%`),l=document.createTextNode("%%_ $index++; } })() _%%");H(a,e,l)}if(n){e.removeAttribute("html-if");const t=document.createTextNode(`%%_ if ( safe(function(){ return ${n} }) ){ _%%`),r=document.createTextNode("%%_ } _%%");H(t,e,r)}r&&(e.removeAttribute("html-inner"),e.innerHTML=`%%_=${r}_%%`),o&&(e.removeAttribute("html-class"),e.className=(e.className+` %%_=${o}_%%`).trim()),"template"===e.localName&&w(e.content)}))},L=(e,t)=>{Array.from(e.querySelectorAll("[tplid]")).reverse().forEach((e=>{const n=e.getAttribute("tplid"),r=e.localName;if(e.setAttribute("html-scopeid","jails___scope-id"),r in t&&t[r].module.template){const n=e.innerHTML,o=t[r].module.template({elm:e,children:n});e.innerHTML=o,w(e),x(e)}const o=k(e.outerHTML);S[n]={template:o,render:_(o)}}))},x=e=>{e.querySelectorAll("template").forEach((e=>{if(e.getAttribute("html-if")||e.getAttribute("html-inner"))return;x(e.content);const t=e.parentNode;if(t){const n=e.content;for(;n.firstChild;)t.insertBefore(n.firstChild,e);t.removeChild(e)}}))},H=(e,t,n)=>{var r,o;null==(r=t.parentNode)||r.insertBefore(e,t),null==(o=t.parentNode)||o.insertBefore(n,t.nextSibling)};globalThis.__jails__=globalThis.__jails__||{components:{}};const j=e=>{if("undefined"==typeof window)return;e=e||document.body;const{components:t}=globalThis.__jails__,n=((e,{components:t})=>{$(e,[...Object.keys(t),"[html-if]","template"],t);const n=e.cloneNode(!0);return w(n),x(n),L(n,t),S})(e,{components:t});Object.values(t).forEach((({name:e,module:t,dependencies:r})=>{customElements.get(e)||customElements.define(e,E({component:{name:e,module:t,dependencies:r},templates:n,start:j}))}))};e.publish=h,e.register=(e,t,n)=>{const{components:r}=globalThis.__jails__;r[e]={name:e,module:t,dependencies:n}},e.start=j,e.subscribe=b,e.templateConfig=e=>{var t;t=e,Object.assign(N,t)},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})})); //# sourceMappingURL=jails.js.map