@modulor-js/html
Advanced tools
Comparing version 1.2.0 to 1.2.2
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.MHTML={})}(this,function(e){"use strict";function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document.createTextNode(""),t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document.createTextNode("");return this.childNodes=[],this.firstChild=null,this.lastChild=null,this.startNode=e,this.stopNode=t,e&&t?e.parentNode!==t.parentNode?this:(this.update(),this):this}t.prototype.appendChild=function(e){this.stopNode.parentNode.insertBefore(e,this.stopNode),this.update()},t.prototype.removeChild=function(e){this.stopNode.parentNode.removeChild(e),this.update()},t.prototype.replaceChild=function(e,t){t.parentNode.replaceChild(e,t),this.update()},t.prototype.extractContents=function(){var e=document.createDocumentFragment();return e.appendChild(this.startNode),this.childNodes.reduce(function(e,t){return e.appendChild(t),e},e),e.appendChild(this.stopNode),e},t.prototype.update=function(){this.childNodes=[];for(var e=this.startNode.nextSibling;e&&e!==this.stopNode;e=e.nextSibling)this.childNodes.push(e);this.firstChild=this.childNodes[0],this.lastChild=this.childNodes[this.childNodes.length-1]};var n,r=1,o=3,i=8,u=document.body.namespaceURI,a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function c(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function s(e,t){return e.nodeType===t.nodeType&&(e.tagName&&t.tagName&&e.tagName.toLowerCase()===t.tagName.toLowerCase())}function d(e){return void 0!==e}function l(e){return!!e&&("object"===(void 0===e?"undefined":a(e))||f(e))&&f(e.then)}function f(e){return"function"==typeof e}function p(e){return(void 0===e?"undefined":a(e))===a(!0)}function h(e){return e.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g,"\\$&")}function m(){}var v=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var u,a=e[Symbol.iterator]();!(r=(u=a.next()).done)&&(n.push(u.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&a.return&&a.return()}finally{if(o)throw i}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();function g(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var y,N={},C=new Map,b=new Map,x=new DOMParser,w="{modulor_html_chunk_"+ +new Date+":",j="}",T="modulor_sanitize_node_"+ +new Date+":",k=new RegExp("<([ /])?("+["table","tr","td","style"].join("|")+")([ ][^]>)?","igm"),A="modulor-dynamic-tag-"+ +new Date,D="modulor-chunk-"+ +new Date,R=(y="("+h(w)+"([^ >]+)"+h(j)+")",new RegExp("(<([ /])?)(([^ >]+)?("+y+")([a-zA-Z0-9-_]+)?)(([ ][^])?>)?","igm")),E=/<([^\s]+)([ ].+)?\/([ ]+)?>/gim,O=new RegExp(G(),"ig"),F=new RegExp(G(!0),"ig"),S=new RegExp("^"+G(!0)+"$"),L="preventChildRendering",_="function",$="array",I="element",M="promise",U="undefined",B="text";function P(e){return f(e)?_:e instanceof Array?$:e instanceof Node?I:l(e)?M:d(e)?B:U}function z(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(F,function(e,n,r){var o=t[r];return d(o)?o:""})}function H(e,t,n){var r=t.name,o=t.value;if(l(o))o.then(function(t){return H(e,{name:r,value:t},n)});else if("style"!==r)if(f(r))r(e,o);else{if(!(n&&""===o)&&r in e)try{return void(e[r]=o)}catch(e){}e.setAttribute(r,o)}else!function(e){return e&&"object"===(void 0===e?"undefined":a(e))&&e.constructor===Object}(o)?e.setAttribute(r,o):Object.assign(e.style,o)}function V(e,t){if(d(e)&&""!==e){var n=P(e);return n===M?e.then(function(e){return V(e,t)}):(n===$?e:(""+e).split(" ")).forEach(function(e){return t(e)})}}function Z(e){for(var t={nodeType:e.nodeType,namespaceURI:e.namespaceURI,textContent:e.textContent,attributes:[],childNodes:[]},n=t.attributes,r=t.childNodes,u=e.attributes||[],a=function(t){var r=u[t],o=r.name,i=r.value;if(o===D)return"continue";var a=o.match(O),c=i.match(O),s=o.match(S),d=i.match(S);if("class"===o){var l=i.split(" ").reduce(function(e,t){return e[t.match(O)?0:1].push(t),e},[[],[]]),f=v(l,2),h=f[0],m=f[1];return n.push({name:o,value:m.join(" ")}),h.length&&n.push(function(e){return function(t,n){var r=h.reduce(function(r,o){var i=o.match(S),u=i?t[i[2]]:z(o,t),a=i?n[i[2]]:z(o,n);return a!==u?(a&&V(a,function(t){return e.classList.remove(t)}),u&&V(u,function(t){return e.classList.add(t)}),!0):r},!1);return[{key:"className",value:e.className},r]}}),"continue"}a||c?n.push(function(t){return function(n,r){var u=s?n[s[2]]:z(o,n),a=s?r[s[2]]:z(o,r),c=d?n[d[2]]:z(i,n),l=d?r[d[2]]:z(i,r),f={key:u,value:c};return u===a&&c===l?[f,!1]:(u!==a&&t.removeAttribute(a),u?(f[u]=c,H(t,{name:u,value:c},p(e[u])),[f,!0]):[f,!0])}}):n.push({name:o,value:i,isBoolean:p(e[o])})},c=0;c<u.length;c++)a(c);for(var s=e.childNodes||[],d=function(e){var t=s[e];return t.nodeType===o?(t.textContent.split(O).filter(function(e){return!!e}).forEach(function(e){var t=e.match(S);if(t){var n=t[2];r.push(function(e){return function(t){return J(t[n],e)}})}else r.push({nodeType:o,textContent:e})}),"continue"):t.nodeType===i?(t.textContent.match(O)?r.push(function(e){var n=document.createComment(""),r=t.textContent;return e.appendChild(n),function(e){n.textContent=z(r,e)}}):r.push({nodeType:i,textContent:t.textContent}),"continue"):void r.push(Z(t))},l=0;l<s.length;l++)d(l);var f=e.tagName;if(f===A.toUpperCase()){var h=e.attributes[D].value,y=h.match(S);return function(e){var n=void 0;return function(r,o){var i=y?r[y[2]]:z(h,r),u=y?o[y[2]]:z(h,o);if(n&&i===u)return n(r);var a,c,s,d=P(i),l={childNodes:[Object.assign({},t,{tagName:i})]};if(d===_){var f=W(l,{appendChild:m,replaceChild:m,childNodes:[(a={props:function(t){return J(i(t),e)}},c={},s=Object.assign(g({props:m,tagName:null,setAttribute:function(e,t){"class"===e&&(c=t.split(" ").reduce(function(e,t){return Object.assign(e,g({},t,!0))},{}))},removeAttribute:m,classList:{add:function(e){c[e]=!0,s.className=Object.keys(c).join(" ").trim()},remove:function(e){delete c[e],s.className=Object.keys(c).join(" ").trim()}},className:"",attributes:[],childNodes:[],appendChild:m,isVirtual:!0},L,!0),a),s)]}),p=v(f,1);return(n=p[0])(r)}var N=W(l,e,{useDocFragment:!0}),C=v(N,2),b=C[0],x=C[1];b(r),x(),n=b}}}return f&&(t.tagName=e.tagName.toLowerCase().replace(T,"").toUpperCase()),t}function q(e){var t,n=(t=e,Array.isArray(t)?t:Array.from(t)),r=n[0];return n.slice(1).reduce(function(e,t,n){var r=""+w+n+j;return e.concat(r).concat(t)},r)}function G(e){var t=(e?"(":"")+"\\d+"+(e?")":"");return"("+h(w)+t+h(j)+")"}function J(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document.createDocumentFragment(),n=C.get(t)||{},r=P(e),o=n.lastChunk,i=n.lastRenderedChunkType,u=n.update;if(o===e)return t;if(r===M)return K[M](t,e),t;if(i!==r)c(t);else if(u){var a=u(e);return f(a)&&(n.update=a),n.lastChunk=e,t}return C.set(t,{update:K[r](t,e),lastRenderedChunkType:r,lastChunk:e}),t}var K=(g(n={},$,function e(t,n){var r=W({childNodes:[].concat(n).map(function(e,t){return function(e){return function(n){return J(n[t],e)}}})},t,{useDocFragment:!0}),o=v(r,2),i=o[0],u=o[1];return i(n),u(),function(r){if(r.length!==n.length)return e(t,r);i(r)}}),g(n,U,c),g(n,B,function(e,t){var n=document.createTextNode(t);return e.appendChild(n),function(e){return n.textContent=e}}),g(n,I,function(e,t){return e.appendChild(t),function(t){e.childNodes.length>1&&e.childNodes.slice(1).forEach(function(t){return e.removeChild(t)}),e.replaceChild(t,e.childNodes[0])}}),g(n,M,function(e,t){t.then(function(t){e.update(),J(t,e)})}),g(n,_,function(e,t){var n=t(e);return function(t){n=t(e,n)}}),n);function Q(e,t,n){for(var r=t.attributes,o=e.attributes,i=0;i<o.length;i++)e.removeAttribute(o[i].name);for(var u=[],a={},c=0;c<r.length;c++){var s=r[c];if(f(s))u.push(s(e));else{var d=s.name,l=s.value,p=s.isBoolean;H(e,{name:d,value:l},p),a["class"===d?"className":d]=l}}if(e[L]&&u.push(function(e,n){return[{key:"children",value:function(n,r){if(r)return r(e),r;var o=W(t,n,{useDocFragment:!0}),i=v(o,2),u=i[0],a=i[1];return u(e),a(),u}},!0]}),"props"in e){var h=f(e.props)?e.props:function(t,n){return n&&(e.props=t)};if(u.length)return[function(e,t){var n=u.reduce(function(n,r){var o=v(n,2),i=o[0],u=o[1],a=r(e,t),c=v(a,2),s=c[0],d=s.key,l=s.value,f=c[1],p="string"==typeof d||"number"==typeof d?g({},d,l):{};return[Object.assign({},i,p),u||f]},[a,!1]),r=v(n,2),o=r[0],i=r[1];h(o,i)}];h(a,!0)}return u}function W(e,n){var a=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(n[L])return[m,[]];for(var c,d,l=[],p=a.useDocFragment?document.createDocumentFragment():n,h=e.childNodes,v=function(e){return e?function(t){return n.replaceChild(t,e)}:function(e){return p.appendChild(e)}},g=0,y=0;;g++){var N=h[g],C=n.childNodes[g+y];if(!N&&!C)break;if(N)if(C&&s(N,C))d=C,(o===(c=N).nodeType!==c.nodeType||c.textContent!==d.textContent)&&s(N,C)&&(l=l.concat(W(N,C)[0]).concat(Q(C,N)));else{var x=v(C);if(f(N)){var w=b.get(C);if(!w){var j=(w=new t).startNode;x(w.extractContents()),b.set(j,w)}var T=N(w);T&&l.push(T),w.update(),y+=w.childNodes.length+1;continue}switch(N.nodeType){case o:x(document.createTextNode(N.textContent));break;case i:x(document.createComment(N.textContent));break;case r:var k=N.namespaceURI,A=N.tagName,D=void 0;D=C&&C[L]?C:k===u?document.createElement(A.toLowerCase()):document.createElementNS(k,A.toLowerCase()),l=l.concat(W(N,D)[0]).concat(Q(D,N)),x(D)}}else n.removeChild(C),g--}var R=[];return[function e(t){return l.forEach(function(e){return e(t,R)}),R=t,e},function(){return a.useDocFragment?n.appendChild(p):void 0}]}e.NodesRange=t,e.emptyNode=c,e.render=J,e.morph=W,e.html=function(){for(var e=arguments.length,t=Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(!r.length)return this;var o,i=function(e){for(var t=5381,n=e.length;n;)t=33*t^e.charCodeAt(--n);return t>>>0}(r.join(w+j)),u=N[i],a=void 0;if(d(u))a=u;else{var c=q(r);o=function(e){return e.replace(k,"<$1"+T+"$2")}(function(e){return e.replace(E,"<$1$2></$1>")}(c.replace(R,function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];t[0];var r=t[1],o=t[2],i=t[3],u=(t[4],t[5],t[6],t[7],t[8],t[9]);return o?"</"+A+">":""+r+A+" "+D+'="'+i+'"'+(u||"")}))),a=Z(x.parseFromString(o,"text/html").body),N[i]=a}return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document.createDocumentFragment(),n=arguments[1];if(n&&n.templateId===i)return n(t);var r=W(a,e,{useDocFragment:!0}),o=v(r,2),u=o[0],c=o[1];return u(t),c(),u.templateId=i,u}},e.stopNode=function(){},Object.defineProperty(e,"__esModule",{value:!0})}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.MHTML={})}(this,function(e){"use strict";function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document.createTextNode(""),t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document.createTextNode("");return this.childNodes=[],this.firstChild=null,this.lastChild=null,this.startNode=e,this.stopNode=t,e&&t?e.parentNode!==t.parentNode?this:(this.update(),this):this}t.prototype.appendChild=function(e){this.stopNode.parentNode.insertBefore(e,this.stopNode),this.update()},t.prototype.removeChild=function(e){this.stopNode.parentNode.removeChild(e),this.update()},t.prototype.replaceChild=function(e,t){t.parentNode.replaceChild(e,t),this.update()},t.prototype.extractContents=function(){var e=document.createDocumentFragment();return e.appendChild(this.startNode),this.childNodes.reduce(function(e,t){return e.appendChild(t),e},e),e.appendChild(this.stopNode),e},t.prototype.update=function(){this.childNodes=[];for(var e=this.startNode.nextSibling;e&&e!==this.stopNode;e=e.nextSibling)this.childNodes.push(e);this.firstChild=this.childNodes[0],this.lastChild=this.childNodes[this.childNodes.length-1]};var n,r=1,o=3,i=8,a=document.body.namespaceURI,u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};function c(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function s(e,t){return e.nodeType===t.nodeType&&(e.tagName&&t.tagName&&e.tagName.toLowerCase()===t.tagName.toLowerCase())}function d(e){return void 0!==e}function l(e){return!!e&&("object"===(void 0===e?"undefined":u(e))||f(e))&&f(e.then)}function f(e){return"function"==typeof e}function p(e){return(void 0===e?"undefined":u(e))===u(!0)}function h(e){return e.replace(/[-[\]{}()*+!<=:?.\/\\^$|#\s,]/g,"\\$&")}function m(){}var v=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{!r&&u.return&&u.return()}finally{if(o)throw i}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();function g(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var y={},N=new Map,C=new Map,b=new DOMParser,x="{modulor_html_chunk_"+ +new Date+":",w="}",T=/<([/]?)([^ />]+)((?:\s+[\w}{:-]+(?:([\s])*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)[ ]*>/gim,j=/([-A-Za-z0-9_}{:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/gim,k=["table","tr","td","style"],A="modulor-dynamic-tag-"+ +new Date,D="modulor-chunk-"+ +new Date,O="{modulor_capitalize-"+ +new Date+":",R=new RegExp(h(O)+"([a-z]+)"+h(w),"g"),E=new RegExp(G(),"ig"),F=new RegExp(G(!0),"ig"),S=new RegExp("^"+G(!0)+"$"),L="preventChildRendering",U="function",I="array",_="element",M="promise",$="undefined",z="text";function B(e){return f(e)?U:e instanceof Array?I:e instanceof Node?_:l(e)?M:d(e)?z:$}function P(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];return e.replace(F,function(e,n,r){var o=t[r];return d(o)?o:""})}function Z(e,t,n){var r=t.name,o=t.value;if(l(o))o.then(function(t){return Z(e,{name:r,value:t},n)});else if("style"!==r)if(f(r))r(e,o);else{if(!(n&&""===o)&&r in e)try{return void(e[r]=o)}catch(e){}e.setAttribute(r,o)}else!function(e){return e&&"object"===(void 0===e?"undefined":u(e))&&e.constructor===Object}(o)?e.setAttribute(r,o):Object.assign(e.style,o)}function H(e,t){if(d(e)&&""!==e){var n=B(e);return n===M?e.then(function(e){return H(e,t)}):(n===I?e:(""+e).split(" ")).forEach(function(e){return t(e)})}}function V(e){for(var t={nodeType:e.nodeType,namespaceURI:e.namespaceURI,textContent:e.textContent,attributes:[],childNodes:[]},n=t.attributes,r=t.childNodes,a=e.attributes||[],u=function(t){var r=a[t].value,o=a[t].name.replace(R,function(e,t){return t.toUpperCase()});if(o===D)return"continue";var i=o.match(E),u=r.match(E),c=o.match(S),s=r.match(S);if("class"===o){var d=r.split(" ").reduce(function(e,t){return e[t.match(E)?0:1].push(t),e},[[],[]]),l=v(d,2),f=l[0],h=l[1];return n.push({name:o,value:h.join(" ")}),f.length&&n.push(function(e){return function(t,n){var r=f.reduce(function(r,o){var i=o.match(S),a=i?t[i[2]]:P(o,t),u=i?n[i[2]]:P(o,n);return u!==a?(u&&H(u,function(t){return e.classList.remove(t)}),a&&H(a,function(t){return e.classList.add(t)}),!0):r},!1);return[{key:"className",value:e.className},r]}}),"continue"}i||u?n.push(function(t){return function(n,i){var a=c?n[c[2]]:P(o,n),u=c?i[c[2]]:P(o,i),d=s?n[s[2]]:P(r,n),l=s?i[s[2]]:P(r,i),f={key:a,value:d};return a===u&&d===l?[f,!1]:(a!==u&&t.removeAttribute(u),a?(f[a]=d,Z(t,{name:a,value:d},p(e[a])),[f,!0]):[f,!0])}}):n.push({name:o,value:r,isBoolean:p(e[o])})},c=0;c<a.length;c++)u(c);for(var s=e.childNodes||[],d=function(e){var t=s[e];return t.nodeType===o?(t.textContent.split(E).filter(function(e){return!!e}).forEach(function(e){var t=e.match(S);if(t){var n=t[2];r.push(function(e){return function(t){return J(t[n],e)}})}else r.push({nodeType:o,textContent:e})}),"continue"):t.nodeType===i?(t.textContent.match(E)?r.push(function(e){var n=document.createComment(""),r=t.textContent;return e.appendChild(n),function(e){n.textContent=P(r,e)}}):r.push({nodeType:i,textContent:t.textContent}),"continue"):void r.push(V(t))},l=0;l<s.length;l++)d(l);var f=e.tagName;if(f===A.toUpperCase()){var h=e.attributes[D].value,y=h.match(S);if(h.match(E))return function(e){var n=void 0;return function(r,o){var i=y?r[y[2]]:P(h,r),a=y?o[y[2]]:P(h,o);if(n&&i===a)return n(r);var u,c,s,d=B(i),l={childNodes:[Object.assign({},t,{tagName:i})]};if(d===U){var f=W(l,{appendChild:m,replaceChild:m,childNodes:[(u={props:function(t){return J(i(t),e)}},c={},s=Object.assign(g({props:m,tagName:null,setAttribute:function(e,t){"class"===e&&(c=t.split(" ").reduce(function(e,t){return Object.assign(e,g({},t,!0))},{}))},removeAttribute:m,classList:{add:function(e){c[e]=!0,s.className=Object.keys(c).join(" ").trim()},remove:function(e){delete c[e],s.className=Object.keys(c).join(" ").trim()}},className:"",attributes:[],childNodes:[],appendChild:m,isVirtual:!0},L,!0),u),s)]}),p=v(f,1);return(n=p[0])(r)}var N=W(l,e,{useDocFragment:!0}),C=v(N,2),b=C[0],x=C[1];b(r),x(),n=b}};t.tagName=h.toUpperCase()}else f&&(t.tagName=e.tagName.toUpperCase());return t}function q(e){var t,n=(t=e,Array.isArray(t)?t:Array.from(t)),r=n[0];return n.slice(1).reduce(function(e,t,n){var r=""+x+n+w;return e.concat(r).concat(t)},r)}function G(e){var t=(e?"(":"")+"\\d+"+(e?")":"");return"("+h(x)+t+h(w)+")"}function J(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document.createDocumentFragment(),n=N.get(t)||{},r=B(e),o=n.lastChunk,i=n.lastRenderedChunkType,a=n.update;if(o===e)return t;if(r===M)return K[M](t,e),t;if(i!==r)c(t);else if(a){var u=a(e);return f(u)&&(n.update=u),n.lastChunk=e,t}return N.set(t,{update:K[r](t,e),lastRenderedChunkType:r,lastChunk:e}),t}var K=(g(n={},I,function e(t,n){var r=W({childNodes:[].concat(n).map(function(e,t){return function(e){return function(n){return J(n[t],e)}}})},t,{useDocFragment:!0}),o=v(r,2),i=o[0],a=o[1];return i(n),a(),function(r){if(r.length!==n.length)return e(t,r);i(r)}}),g(n,$,c),g(n,z,function(e,t){var n=document.createTextNode(t);return e.appendChild(n),function(e){return n.textContent=e}}),g(n,_,function(e,t){return e.appendChild(t),function(t){e.childNodes.length>1&&e.childNodes.slice(1).forEach(function(t){return e.removeChild(t)}),e.replaceChild(t,e.childNodes[0])}}),g(n,M,function(e,t){t.then(function(t){e.update(),J(t,e)})}),g(n,U,function(e,t){var n=t(e);return function(t){n=t(e,n)}}),n);function Q(e,t,n){for(var r=t.attributes,o=e.attributes,i=0;i<o.length;i++)e.removeAttribute(o[i].name);for(var a=[],u={},c=0;c<r.length;c++){var s=r[c];if(f(s))a.push(s(e));else{var d=s.name,l=s.value,p=s.isBoolean;Z(e,{name:d,value:l},p),u["class"===d?"className":d]=l}}if(e[L]&&a.push(function(e,n){return[{key:"children",value:function(n,r){if(r)return r(e),r;var o=W(t,n,{useDocFragment:!0}),i=v(o,2),a=i[0],u=i[1];return a(e),u(),a}},!0]}),"props"in e){var h=f(e.props)?e.props:function(t,n){return n&&(e.props=t)};if(a.length)return[function(e,t){var n=a.reduce(function(n,r){var o=v(n,2),i=o[0],a=o[1],u=r(e,t),c=v(u,2),s=c[0],d=s.key,l=s.value,f=c[1],p="string"==typeof d||"number"==typeof d?g({},d,l):{};return[Object.assign({},i,p),a||f]},[u,!1]),r=v(n,2),o=r[0],i=r[1];h(o,i)}];h(u,!0)}return a}function W(e,n){var u=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(n[L])return[m,[]];for(var c,d,l=[],p=u.useDocFragment?document.createDocumentFragment():n,h=e.childNodes,v=function(e){return e?function(t){return n.replaceChild(t,e)}:function(e){return p.appendChild(e)}},g=0,y=0;;g++){var N=h[g],b=n.childNodes[g+y];if(!N&&!b)break;if(N)if(b&&s(N,b))d=b,(o===(c=N).nodeType!==c.nodeType||c.textContent!==d.textContent)&&s(N,b)&&(l=l.concat(W(N,b)[0]).concat(Q(b,N)));else{var x=v(b);if(f(N)){var w=C.get(b);if(!w){var T=(w=new t).startNode;x(w.extractContents()),C.set(T,w)}var j=N(w);j&&l.push(j),w.update(),y+=w.childNodes.length+1;continue}switch(N.nodeType){case o:x(document.createTextNode(N.textContent));break;case i:x(document.createComment(N.textContent));break;case r:var k=N.namespaceURI,A=N.tagName,D=void 0;D=b&&b[L]?b:k===a?document.createElement(A.toLowerCase()):document.createElementNS(k,A.toLowerCase()),l=l.concat(W(N,D)[0]).concat(Q(D,N)),x(D)}}else n.removeChild(b),g--}var O=[];return[function e(t){return l.forEach(function(e){return e(t,O)}),O=t,e},function(){return u.useDocFragment?n.appendChild(p):void 0}]}e.NodesRange=t,e.emptyNode=c,e.render=J,e.morph=W,e.html=function(){for(var e=arguments.length,t=Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if(!r.length)return this;var o,i=function(e){for(var t=5381,n=e.length;n;)t=33*t^e.charCodeAt(--n);return t>>>0}(r.join(x+w)),a=y[i],u=void 0;if(d(a))u=a;else{var c=q(r);o=c.replace(T,function(e,t,n,r,o,i){return r=r.replace(/\/$/,function(){return i="/",""}).replace(j,function(e,t){return e.replace(t,t.replace(/[A-Z]/gm,function(e){return""+O+e+w}))}),(~k.indexOf(n)||n.match(E))&&(r=" "+D+'="'+n.trim()+'"'+r,n=A),i?"<"+n+r+"></"+n+">":t?"</"+n+">":"<"+t+n+r+">"}),u=V(b.parseFromString(o,"text/html").body),y[i]=u}return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document.createDocumentFragment(),n=arguments[1];if(n&&n.templateId===i)return n(t);var r=W(u,e,{useDocFragment:!0}),o=v(r,2),a=o[0],c=o[1];return a(t),c(),a.templateId=i,a}},e.stopNode=function(){},Object.defineProperty(e,"__esModule",{value:!0})}); |
{ | ||
"name": "@modulor-js/html", | ||
"version": "1.2.0", | ||
"version": "1.2.2", | ||
"description": "Template engine based on tagged template literals", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
@@ -54,3 +54,3 @@ # modulor-html [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Missing%20template%20engine%20for%20Web%20Components&url=https://github.com/modulor-js/modulor-html&hashtags=webcomponents,template-engine,js) | ||
- Small size (**4kb** minigzipped) | ||
- Small size (**4.1kb** minigzipped) | ||
@@ -57,0 +57,0 @@ - High performance |
128
src/html.js
@@ -21,11 +21,12 @@ import { NodesRange } from './range'; | ||
let sanitizeNodePrefix = `modulor_sanitize_node_${+(new Date())}:`; | ||
const PREPROCESS_TEMPLATE_REGEX = /<([/]?)([^ />]+)((?:\s+[\w}{:-]+(?:([\s])*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)[ ]*>/igm; | ||
const PREPROCESS_ATTR_REGEX = /([-A-Za-z0-9_}{:]+)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/gim; | ||
const sanitizeTags = ['table', 'tr', 'td', 'style']; | ||
const sanitizeTagsRegex = new RegExp(`<([ /])?(${sanitizeTags.join('|')})([ ][^]>)?`, 'igm'); | ||
let specialTagName = `modulor-dynamic-tag-${+new Date()}`; | ||
let specialAttributeName = `modulor-chunk-${+new Date()}`; | ||
let dynamicTagsRegex = getDynamicTagsRegex(); | ||
const selfClosingRegex = /<([^\s]+)([ ].+)?\/([ ]+)?>/igm; | ||
let capitalisePrefix = `{modulor_capitalize-${+(new Date())}:`; | ||
let capitaliseRegex = new RegExp(`${regExpEscape(capitalisePrefix)}([a-z]+)${regExpEscape(POSTFIX)}`, 'g'); | ||
@@ -155,3 +156,6 @@ let findChunksRegex = new RegExp(getTokenRegExp(), 'ig'); | ||
for(let j = 0; j < childAttributes.length; j++){ | ||
const { name, value } = childAttributes[j]; | ||
const value = childAttributes[j].value; | ||
const name = childAttributes[j].name.replace(capitaliseRegex, (_, letter) => { | ||
return letter.toUpperCase(); | ||
}); | ||
if(name === specialAttributeName){ | ||
@@ -272,39 +276,42 @@ continue; | ||
return (range) => { | ||
let update; | ||
return (values, prevValues) => { | ||
const newValue = matchChunk ? values[matchChunk[2]] : replaceTokens(chunkName, values); | ||
const oldValue = matchChunk ? prevValues[matchChunk[2]] : replaceTokens(chunkName, prevValues); | ||
if(chunkName.match(findChunksRegex)){ | ||
return (range) => { | ||
let update; | ||
return (values, prevValues) => { | ||
const newValue = matchChunk ? values[matchChunk[2]] : replaceTokens(chunkName, values); | ||
const oldValue = matchChunk ? prevValues[matchChunk[2]] : replaceTokens(chunkName, prevValues); | ||
if(update && newValue === oldValue){ | ||
return update(values); | ||
} | ||
const chunkType = getChunkType(newValue); | ||
if(update && newValue === oldValue){ | ||
return update(values); | ||
} | ||
const chunkType = getChunkType(newValue); | ||
const container = { | ||
childNodes: [Object.assign({}, nodeCopy, { | ||
tagName: newValue | ||
})] | ||
}; | ||
if(chunkType === CHUNK_TYPE_FUNCTION){ | ||
const target = { | ||
appendChild: noop, | ||
replaceChild: noop, | ||
childNodes: [createVirtualElement({ | ||
props: (value) => render(newValue(value), range) | ||
const container = { | ||
childNodes: [Object.assign({}, nodeCopy, { | ||
tagName: newValue | ||
})] | ||
}; | ||
[update] = morph(container, target); | ||
return update(values); | ||
} | ||
const [newUpdate, initialRender] = morph(container, range, { useDocFragment: true }); | ||
newUpdate(values); | ||
initialRender(); | ||
update = newUpdate; | ||
if(chunkType === CHUNK_TYPE_FUNCTION){ | ||
const target = { | ||
appendChild: noop, | ||
replaceChild: noop, | ||
childNodes: [createVirtualElement({ | ||
props: (value) => render(newValue(value), range) | ||
})] | ||
}; | ||
[update] = morph(container, target); | ||
return update(values); | ||
} | ||
const [newUpdate, initialRender] = morph(container, range, { useDocFragment: true }); | ||
newUpdate(values); | ||
initialRender(); | ||
update = newUpdate; | ||
}; | ||
}; | ||
}; | ||
} | ||
nodeCopy.tagName = chunkName.toUpperCase(); | ||
} else if(tagName){ | ||
nodeCopy.tagName = $container.tagName.toLowerCase().replace(sanitizeNodePrefix, '').toUpperCase(); | ||
nodeCopy.tagName = $container.tagName.toUpperCase(); | ||
} | ||
@@ -332,24 +339,30 @@ | ||
function sanitize(str){ | ||
return str.replace(sanitizeTagsRegex, `<$1${sanitizeNodePrefix}$2`); | ||
}; | ||
function preprocess(str){ | ||
function getDynamicTagsRegex(groupMatches = false){ | ||
const tokenRegEx = `(${regExpEscape(PREFIX)}([^ >]+)${regExpEscape(POSTFIX)})`; | ||
return new RegExp(`(<([ /])?)(([^ >]+)?(${tokenRegEx})([a-zA-Z0-9-_]+)?)(([ ][^])?>)?`, 'igm'); | ||
} | ||
return str.replace(PREPROCESS_TEMPLATE_REGEX, (input, isClosing, tagName, attrs, _, isSelfClosing) => { | ||
function replaceDynamicTags(str){ | ||
return str.replace(dynamicTagsRegex, (...args) => { | ||
const [_, opening, isClosing, chunkName, __, ___, suffix, ____, _____, closing] = args; | ||
return isClosing | ||
? `</${specialTagName}>` | ||
: `${opening}${specialTagName} ${specialAttributeName}="${chunkName}"${closing || ''}` | ||
//TODO: make this workaround a part of regex, test case: test/html/processing.test.js:300 | ||
attrs = attrs.replace(/\/$/, () => { | ||
isSelfClosing = '/'; | ||
return ''; | ||
}).replace(PREPROCESS_ATTR_REGEX, (attrBlock, attrName) => { | ||
return attrBlock.replace(attrName, attrName.replace(/[A-Z]/gm, letter => `${capitalisePrefix}${letter}${POSTFIX}`)); | ||
}); | ||
if(~sanitizeTags.indexOf(tagName) || tagName.match(findChunksRegex)){ | ||
attrs = ` ${specialAttributeName}="${tagName.trim()}"${attrs}`; | ||
tagName = specialTagName; | ||
} | ||
if(isSelfClosing){ | ||
return `<${tagName}${attrs}></${tagName}>` | ||
} | ||
if(isClosing){ | ||
return `</${tagName}>`; | ||
} | ||
return `<${isClosing}${tagName}${attrs}>`; | ||
}); | ||
}; | ||
function openSelfClosingTags(str){ | ||
return str.replace(selfClosingRegex, '<$1$2></$1>'); | ||
}; | ||
export function render(value, range = document.createDocumentFragment()){ | ||
@@ -626,3 +639,3 @@ const cached = updatesMap.get(range) || {}; | ||
const template = prepareLiterals(chunks); | ||
container = generateContainer(sanitize(openSelfClosingTags(replaceDynamicTags(template)))); | ||
container = generateContainer(preprocess(template)); | ||
templatesCache[templateId] = container; | ||
@@ -660,6 +673,10 @@ } else { | ||
replaceTokens, processNode, generateContainer, | ||
sanitize, copyAttributes, prepareLiterals, openSelfClosingTags, replaceDynamicTags, | ||
copyAttributes, prepareLiterals, | ||
preprocess, | ||
setPrefix: (value) => PREFIX = value, | ||
setPostfix: (value) => POSTFIX = value, | ||
setSanitizeNodePrefix: (value) => sanitizeNodePrefix = value, | ||
setCapitalisePrefix: (value) => { | ||
capitalisePrefix = value; | ||
capitaliseRegex = new RegExp(`${regExpEscape(capitalisePrefix)}([a-z]+)${regExpEscape(POSTFIX)}`, 'g'); | ||
}, | ||
setSpecialTagName: (value) => specialTagName = value, | ||
@@ -671,3 +688,2 @@ setSpecialAttributeName: (value) => specialAttributeName = value, | ||
matchChunkRegex = new RegExp(`^${getTokenRegExp(true)}$`); | ||
dynamicTagsRegex = getDynamicTagsRegex(); | ||
} | ||
@@ -674,0 +690,0 @@ }); |
import { | ||
html, render, r, createHtml, copyAttributes, processNode, setPrefix, setPostfix, updateChunkRegexes | ||
html, render, r, createHtml, copyAttributes, processNode, setPrefix, setPostfix, updateChunkRegexes, setCapitalisePrefix, | ||
} from '../../src/html'; | ||
@@ -7,2 +7,3 @@ | ||
setPostfix('}'); | ||
setCapitalisePrefix('{modulor_capitalize:'); | ||
@@ -179,2 +180,23 @@ updateChunkRegexes(); | ||
}); | ||
it('capitalises attribute names correctly', () => { | ||
const element = document.createElement('div'); | ||
element.innerHTML = ` | ||
<input | ||
foo{modulor_capitalize:B}ar="12" | ||
foo | ||
bar{modulor_capitalize:B}az | ||
bla-{modulor_capitalize:O}k=234 | ||
one{modulor_capitalize:t}wo{modulor_capitalize:F}our=2 /> | ||
`; | ||
const source = processNode(element.querySelector('input')); | ||
expect(source.attributes).toMatchObject([ | ||
{ name: 'fooBar', value: '12', isBoolean: false }, | ||
{ name: 'foo', value: '', isBoolean: false }, | ||
{ name: 'barBaz', value: '', isBoolean: false }, | ||
{ name: 'bla-Ok', value: '234', isBoolean: false }, | ||
{ name: 'oneTwoFour', value: '2', isBoolean: false }, | ||
]); | ||
}); | ||
}); | ||
@@ -181,0 +203,0 @@ |
import { | ||
html, prepareLiterals, replaceTokens, sanitize, openSelfClosingTags, replaceDynamicTags, | ||
setPrefix, setPostfix, setSanitizeNodePrefix, updateChunkRegexes, setSpecialTagName, setSpecialAttributeName | ||
html, prepareLiterals, replaceTokens, | ||
setPrefix, setPostfix, updateChunkRegexes, setSpecialTagName, setSpecialAttributeName, setCapitalisePrefix, preprocess | ||
} from '../../src/html'; | ||
@@ -8,5 +8,5 @@ | ||
setPostfix('}'); | ||
setSanitizeNodePrefix('sanitize:'); | ||
setSpecialTagName('modulor-dynamic-tag'); | ||
setSpecialAttributeName('modulor-chunk'); | ||
setCapitalisePrefix('{modulor_capitalize:'); | ||
updateChunkRegexes(); | ||
@@ -84,3 +84,3 @@ | ||
input: '<table attr-one="1"></table>', | ||
expectation: '<sanitize:table attr-one="1"></sanitize:table>' | ||
expectation: '<modulor-dynamic-tag modulor-chunk="table" attr-one="1"></modulor-dynamic-tag>' | ||
}, | ||
@@ -91,5 +91,4 @@ { | ||
></table>`, | ||
expectation: `<sanitize:table attr-one="1" | ||
foo=bar bla baz="ok" | ||
></sanitize:table>` | ||
expectation: `<modulor-dynamic-tag modulor-chunk="table" attr-one="1" | ||
foo=bar bla baz="ok"></modulor-dynamic-tag>` | ||
}, | ||
@@ -109,11 +108,11 @@ { | ||
expectation: ` | ||
<sanitize:table> | ||
<sanitize:tr> | ||
<sanitize:td>foo</sanitize:td> | ||
<sanitize:td></sanitize:td> | ||
</sanitize:tr> | ||
<sanitize:tr> | ||
<sanitize:td><div></div></sanitize:td> | ||
</sanitize:tr> | ||
</sanitize:table> | ||
<modulor-dynamic-tag modulor-chunk="table"> | ||
<modulor-dynamic-tag modulor-chunk="tr"> | ||
<modulor-dynamic-tag modulor-chunk="td">foo</modulor-dynamic-tag> | ||
<modulor-dynamic-tag modulor-chunk="td"></modulor-dynamic-tag> | ||
</modulor-dynamic-tag> | ||
<modulor-dynamic-tag modulor-chunk="tr"> | ||
<modulor-dynamic-tag modulor-chunk="td"><div></div></modulor-dynamic-tag> | ||
</modulor-dynamic-tag> | ||
</modulor-dynamic-tag> | ||
` | ||
@@ -128,5 +127,5 @@ }, | ||
expectation: ` | ||
<sanitize:style> | ||
<modulor-dynamic-tag modulor-chunk="style"> | ||
.foo > .bar { } | ||
</sanitize:style> | ||
</modulor-dynamic-tag> | ||
` | ||
@@ -137,3 +136,3 @@ }, | ||
it(`set #${index}`, () => { | ||
expect(sanitize(testSet.input)).toBe(testSet.expectation); | ||
expect(preprocess(testSet.input)).toBe(testSet.expectation); | ||
}); | ||
@@ -161,3 +160,3 @@ }) | ||
input: '<input / >', | ||
expectation: '<input ></input>' | ||
expectation: '<input></input>' | ||
}, | ||
@@ -187,3 +186,3 @@ { | ||
it(`set #${index}`, () => { | ||
expect(openSelfClosingTags(testSet.input)).toBe(testSet.expectation); | ||
expect(preprocess(testSet.input)).toBe(testSet.expectation); | ||
}); | ||
@@ -203,7 +202,7 @@ }) | ||
input: '<{modulor_html_chunk:0}/>', | ||
expectation: '<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}"/>' | ||
expectation: '<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}"></modulor-dynamic-tag>' | ||
}, | ||
{ | ||
input: '<{modulor_html_chunk:0} foo="bar"/>', | ||
expectation: '<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}" foo="bar"/>' | ||
expectation: '<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}" foo="bar"></modulor-dynamic-tag>' | ||
}, | ||
@@ -250,4 +249,3 @@ { | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}" foo="{modulor_html_chunk:1}" {modulor_html_chunk:1}="{modulor_html_chunk:2}"> | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:3}" | ||
bla="test"> | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:3}" bla="test"> | ||
</modulor-dynamic-tag> | ||
@@ -267,4 +265,3 @@ </modulor-dynamic-tag> | ||
<modulor-dynamic-tag modulor-chunk="x-{modulor_html_chunk:0}-y" foo="{modulor_html_chunk:1}" {modulor_html_chunk:1}="{modulor_html_chunk:2}"> | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:3}-foo" | ||
bla="test"> | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:3}-foo" bla="test"> | ||
</modulor-dynamic-tag> | ||
@@ -296,6 +293,30 @@ </modulor-dynamic-tag> | ||
}, | ||
{ | ||
input: ` | ||
<span id="component-b"> | ||
<{modulor_html_chunk:0} foo={modulor_html_chunk:1}> | ||
<p>{modulor_html_chunk:2}</p> | ||
</{modulor_html_chunk:2}> | ||
</span> | ||
`, | ||
expectation: ` | ||
<span id="component-b"> | ||
<modulor-dynamic-tag modulor-chunk="{modulor_html_chunk:0}" foo={modulor_html_chunk:1}> | ||
<p>{modulor_html_chunk:2}</p> | ||
</modulor-dynamic-tag> | ||
</span> | ||
` | ||
}, | ||
{ | ||
input: ` | ||
<x-foo value={modulor_html_chunk:0}/> | ||
`, | ||
expectation: ` | ||
<x-foo value={modulor_html_chunk:0}></x-foo> | ||
` | ||
}, | ||
] | ||
testSets.forEach((testSet, index) => { | ||
it(`set #${index}`, () => { | ||
expect(replaceDynamicTags(testSet.input)).toBe(testSet.expectation); | ||
expect(preprocess(testSet.input)).toBe(testSet.expectation); | ||
}); | ||
@@ -305,1 +326,28 @@ }) | ||
describe('capitalize', () => { | ||
const testSets = [ | ||
{ | ||
input: '<div fooBar="12" foo barBaz bla-Ok=234></div>', | ||
expectation: '<div foo{modulor_capitalize:B}ar="12" foo bar{modulor_capitalize:B}az bla-{modulor_capitalize:O}k=234></div>' | ||
}, | ||
{ | ||
input: ` | ||
<svg width="34" height="34" viewBox="0 0 34 34"> | ||
<path d="M29.1 26.3L23.8 22.8C22.7 22.1 21.2 22.4 20.5 23.5 19.3 25 17.8 27.5 12.2 21.8 6.6 16.2 9 14.7 10.5 13.5 11.5 12.7 11.8 11.3 11.1 10.2L7.6 4.9C7.2 4.2 6.6 3.1 5.1 3.3 3.7 3.5 0 5.6 0 10.2 0 14.8 3.6 20.4 8.5 25.4 13.5 30.3 19.1 34 23.8 34 28.4 34 30.5 29.9 30.7 28.9 30.9 27.9 29.8 26.8 29.1 26.3Z" fill="#6A3460" /> | ||
</svg> | ||
`, | ||
expectation: ` | ||
<svg width="34" height="34" view{modulor_capitalize:B}ox="0 0 34 34"> | ||
<path d="M29.1 26.3L23.8 22.8C22.7 22.1 21.2 22.4 20.5 23.5 19.3 25 17.8 27.5 12.2 21.8 6.6 16.2 9 14.7 10.5 13.5 11.5 12.7 11.8 11.3 11.1 10.2L7.6 4.9C7.2 4.2 6.6 3.1 5.1 3.3 3.7 3.5 0 5.6 0 10.2 0 14.8 3.6 20.4 8.5 25.4 13.5 30.3 19.1 34 23.8 34 28.4 34 30.5 29.9 30.7 28.9 30.9 27.9 29.8 26.8 29.1 26.3Z" fill="#6A3460"></path> | ||
</svg> | ||
` | ||
}, | ||
]; | ||
testSets.forEach((testSet, index) => { | ||
it(`set #${index}`, () => { | ||
expect(preprocess(testSet.input)).toBe(testSet.expectation); | ||
}); | ||
}) | ||
}); |
@@ -551,2 +551,28 @@ import 'document-register-element'; | ||
it('camelCase attribute names', () => { | ||
const valueSetterSpyA = jest.fn(); | ||
const valueSetterSpyB = jest.fn(); | ||
customElements.define('my-test-component-j', class extends HTMLElement { | ||
set myValue(value){ | ||
valueSetterSpyA(value); | ||
} | ||
set ['my-Test-Value'](value){ | ||
valueSetterSpyB(value); | ||
} | ||
}); | ||
const tplF = (scope) => html` | ||
<my-test-component-j myValue="test" my-Test-Value="foo"></my-test-component-j> | ||
`; | ||
const container = document.createElement('div'); | ||
render(tplF(), container); | ||
expect(valueSetterSpyA).toHaveBeenCalledWith('test'); | ||
expect(valueSetterSpyB).toHaveBeenCalledWith('foo'); | ||
}); | ||
}); | ||
@@ -553,0 +579,0 @@ |
133651
3084