Comparing version 0.3.7-0 to 0.3.7
@@ -74,4 +74,7 @@ 'use strict'; | ||
var rawDirectiveSplitPattern = /:|\./; | ||
var keyPattern = function (key, hasThis) { | ||
var rawDirectiveSplitRE = function () { return /:|\./; }; | ||
var hasDirectiveRE = function () { | ||
return new RegExp("(" + DIRECTIVE_PREFIX + "|" + Object.keys(DIRECTIVE_SHORTHANDS).join('|') + ")\\w+", 'gim'); | ||
}; | ||
var expressionPropRE = function (key, hasThis) { | ||
if (hasThis === void 0) { hasThis = true; } | ||
@@ -178,20 +181,26 @@ return new RegExp("" + (hasThis ? 'this\\.' : '') + key + "\\b"); | ||
var joinDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ as | by /), 3), array = _b[0], contentType = _b[1], delimiter = _b[2]; | ||
var hydratedArray = compute(array, { $el: el })(app.state); | ||
var accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
var inputCallback = function (el, hydratedValue, data, app) { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
var modelDirective = function (_a) { | ||
@@ -204,25 +213,3 @@ var awaitingTypecastEl = _a.el, data = _a.data, app = _a.app; | ||
} | ||
el.oninput = function () { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
}; | ||
el.oninput = function () { return inputCallback(el, hydratedValue, data, app); }; | ||
}; | ||
@@ -250,5 +237,37 @@ | ||
var forDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ +in +/g), 2), expression = _b[0], target = _b[1]; | ||
var _c = __read(expression.split(','), 2), item = _c[0], index = _c[1]; | ||
var hydratedArray = compute(target, { $el: el })(app.state); | ||
var template = String(el.__l_for); | ||
if (template) { | ||
var accumulator = ''; | ||
for (var i = 0; i < hydratedArray.length; i++) { | ||
var content = template; | ||
if (item) | ||
content = content.replace(new RegExp("this." + item.trim(), 'g'), target + "[" + i + "]"); | ||
if (index) | ||
content = content.replace(new RegExp("this." + index.trim(), 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
var directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
@@ -259,5 +278,6 @@ IF: ifDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
var renderDirective = function (props, directives) { | ||
var name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
var name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
@@ -300,3 +320,10 @@ }; | ||
var _d = _c.value, name_1 = _d.name, value = _d.value; | ||
var directiveData = { compute: compute(value, { $el: el }), value: value }; | ||
var returnable = true; | ||
if (name_1.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name_1)) | ||
returnable = false; | ||
var directiveData = { compute: compute(value, { $el: el }, returnable), value: value }; | ||
if (name_1.startsWith(DIRECTIVE_PREFIX)) { | ||
@@ -330,3 +357,3 @@ directives[name_1.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
var value = _a.value; | ||
return Object.keys(state).some(function (key) { return keyPattern(key, false).test(value); }); | ||
return Object.keys(state).some(function (key) { return expressionPropRE(key, false).test(value); }); | ||
}); | ||
@@ -385,3 +412,3 @@ if (hasDirectives) | ||
} | ||
if (!strip || container.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
var compiledChildren = compile(container, state, components, strip, true); | ||
@@ -405,3 +432,3 @@ try { | ||
else { | ||
if (!strip || child.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
var compiledChildren = compile(child, state, components, strip, true); | ||
@@ -432,28 +459,13 @@ var node = createVNode(child, state, compiledChildren); | ||
var flat = function (vdom) { | ||
var e_4, _a, e_5, _b; | ||
var e_4, _a; | ||
var flattenedVDom = __assign({}, vdom); | ||
flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
flattenedVDom.children = flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
try { | ||
for (var _c = __values(vdom.children), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
var child = _d.value; | ||
for (var _b = __values(vdom.children), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var child = _c.value; | ||
if (typeof child === 'string') | ||
continue; | ||
if (child.children.length > 0) { | ||
try { | ||
for (var _e = (e_5 = void 0, __values(flat(child).children)), _f = _e.next(); !_f.done; _f = _e.next()) { | ||
var nestedChild = _f.value; | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
} | ||
catch (e_5_1) { e_5 = { error: e_5_1 }; } | ||
finally { | ||
try { | ||
if (_f && !_f.done && (_b = _e.return)) _b.call(_e); | ||
} | ||
finally { if (e_5) throw e_5.error; } | ||
} | ||
flattenedVDom.children = __spread(flattenedVDom.children, flat({ children: child.children }).children); | ||
child.children = []; | ||
} | ||
@@ -465,3 +477,3 @@ } | ||
try { | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
@@ -516,3 +528,3 @@ finally { if (e_4) throw e_4.error; } | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
@@ -544,6 +556,8 @@ }, | ||
var needsInit = type === 1; | ||
var hasKey = keys.some(function (key) { return keyPattern(key).test(String(directives_1[name_1].value)); }); | ||
var hasKey = keys.some(function (key) { | ||
return expressionPropRE(key).test(String(directives_1[name_1].value)); | ||
}); | ||
var hasKeyInFunction = Object.keys(state).some(function (key) { | ||
var iterKeysInFunction = keys.some(function (k) { | ||
return keyPattern(k).test(String(state[key])); | ||
return expressionPropRE(k).test(String(state[key])); | ||
}); | ||
@@ -571,3 +585,3 @@ return typeof state[key] === 'function' && iterKeysInFunction; | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
patch(node, app, keys); | ||
}; | ||
@@ -662,12 +676,19 @@ try { | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest("[" + stateDirective + "]")) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
@@ -674,0 +695,0 @@ |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function r(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function n(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t}var i;!function(t){t["@"]="on",t[":"]="bind"}(i||(i={}));var o=/:|\./,a=function(t,e){return void 0===e&&(e=!0),new RegExp((e?"this\\.":"")+t+"\\b")};function s(t){try{var e=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,n([void 0],Object.keys(this.argsKV),[e])))).bind(t).apply(void 0,n(Object.values(this.argsKV)))}catch(t){console.warn('Lucia Error: "'+t+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var l,u=function(t,e,r){return void 0===r&&(r=!0),s.bind({expression:t,argsKV:{$el:e.$el},returnable:r})},c={BIND:function(t){var e=t.el,r=t.name,n=t.data,i=t.app;switch(r.split(":")[1]){case"class":var o=n.compute(i.state);if("string"==typeof o)return e.setAttribute("class",(e.className+" "+o).trim());if(o instanceof Array)return e.setAttribute("class",(e.className+" "+o.join(" ")).trim());var a=[];for(var s in o)o[s]&&a.push(s);return a.length>0?e.setAttribute("class",(e.className+" "+a.join(" ").trim()).trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class");case"style":var l=n.compute(i.state);for(var s in e.removeAttribute("style"),l)e.style[s]=l[s];break;default:var u=n.compute(i.state);if("object"==typeof u&&null!==u)for(var s in u)u[s]?e.setAttribute(s,u[s]):e.removeAttribute(s);else u?e.setAttribute(r.split(":")[1],u):e.removeAttribute(r.split(":")[1])}},JOIN:function(e){var n=e.el,i=e.data,o=e.app,a=r(i.value.split(/ as | by /),3),s=a[0],l=a[1],c=a[2],v=u(s,{$el:n})(o.state);n["text"===l?"innerText":"innerHTML"]=v.join(c||"");var p=g(t({},o.state));Object.entries(o.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];p.directive(n,i)})),Object.entries(o.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];p.component(n,i)})),p.mount(n)},HTML:function(e){var n,i=e.el,o=e.data,a=e.app;i.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var s=g(t({},a.state));Object.entries(a.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.directive(n,i)})),Object.entries(a.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.component(n,i)})),s.mount(i)},IF:function(t){var e=t.el,r=t.data,n=t.app;r.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:function(t){var e=t.el,r=t.data,n=t.app,i=e,o=r.compute(n.state);i.value!==o&&(i.value=o),i.oninput=function(){var t,e="number"==typeof o&&!isNaN(i.value),a="boolean"==typeof o&&("true"===i.value||"false"===i.value),s=null==o&&("null"===i.value||"undefined"===i.value);t=e?"Number('"+i.value+"').toPrecision()":a?"Boolean('"+i.value+"')":s?"null"===i.value?null:void 0:"'"+i.value+"'",u(r.value+" = "+t,{$el:i},!1)(n.state)}},ON:function(t){var e=t.el,n=t.name,i=t.data,o=t.app,a=r(n.split("."),2),s=a[0],l=a[1],u=s.split(":")[1],c=l||null;e["on"+u]=function(t){"prevent"===c&&t.preventDefault(),"stop"===c&&t.stopPropagation(),i.compute(o.state)}},TEXT:function(t){var e,r=t.el,n=t.data,i=t.app;r.textContent=null!==(e=n.compute(i.state))&&void 0!==e?e:n.value}},v=function(t,e){e[t.name.split(o)[0].toUpperCase()](t)};!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(l||(l={}));var p=function(e,r,n){void 0===r&&(r=[]);var i=t({},null==n?void 0:n.attributes),o=t({},null==n?void 0:n.directives);return r=r instanceof Array?r:[r],i.className&&(i.className=i.className.trim()),{tag:e,children:r,props:{attributes:i,directives:o,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},f=function(t){var r,o,a={},s={};if(t.attributes)try{for(var l=e(n(t.attributes)),c=l.next();!c.done;c=l.next()){var v=c.value,p=v.name,f=v.value,d={compute:u(f,{$el:t}),value:f};p.startsWith("l-")?s[p.slice("l-".length)]=d:Object.keys(i).includes(p[0])?s[i[p[0]]+":"+p.slice(1)]=d:a[p]=f}}catch(t){r={error:t}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(r)throw r.error}}return{attributes:a,directives:s}},d=function(t,e,r){var n=f(t),i=n.attributes,o=n.directives,s=l.STATIC,u=Object.keys(o).length>0,c=Object.values(o).some((function(t){var r=t.value;return Object.keys(e).some((function(t){return a(t,!1).test(r)}))}));return u&&(s=l.NEEDS_PATCH),c&&(s=l.DYNAMIC),p(t.tagName.toLowerCase(),r,{attributes:i,directives:o,ref:s===l.STATIC||i.id?void 0:t,type:s})},y=function(t,n,i,o,a){var s,l,u,c,v,p,m;if(void 0===n&&(n={}),void 0===i&&(i={}),void 0===o&&(o=!1),void 0===a&&(a=!1),!t)throw new Error("Please provide a Element");var b=[],x=Array.prototype.slice.call(t.childNodes);try{for(var E=e(x),g=E.next();!g.done;g=E.next()){var A=g.value;switch(A.nodeType){case Node.TEXT_NODE:!o&&A.nodeValue&&b.push(A.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(i).includes(A.tagName)){var N=document.createElement("div"),T=i[A.tagName]({children:A.innerHTML,state:n});N.innerHTML=T;try{for(var O=(u=void 0,e(Object.entries(f(A).directives))),j=O.next();!j.done;j=O.next()){var w=r(j.value,2),C=w[0],S=w[1];null===(m=N.firstElementChild)||void 0===m||m.setAttribute("l-"+C,S.value)}}catch(t){u={error:t}}finally{try{j&&!j.done&&(c=O.return)&&c.call(O)}finally{if(u)throw u.error}}if(!o||N.outerHTML.includes(" l-")){var I=y(N,n,i,o,!0);try{for(var _=(v=void 0,e(I)),D=_.next();!D.done;D=_.next()){var L=D.value;b.push(L)}}catch(t){v={error:t}}finally{try{D&&!D.done&&(p=_.return)&&p.call(_)}finally{if(v)throw v.error}}}t.replaceChild(N.firstElementChild,A)}else if(!o||A.outerHTML.includes(" l-")){I=y(A,n,i,o,!0);var k=d(A,n,I);b.push(k)}}}}catch(t){s={error:t}}finally{try{g&&!g.done&&(l=E.return)&&l.call(E)}finally{if(s)throw s.error}}if(a)return b;var H=d(t,n,b);return o?h(H):H},h=function(r){var n,i,o,a,s=t({},r);s.children.filter((function(t){return"object"==typeof t&&t.props.type>0}));try{for(var l=e(r.children),u=l.next();!u.done;u=l.next()){var c=u.value;if("string"!=typeof c&&c.children.length>0)try{for(var v=(o=void 0,e(h(c).children)),p=v.next();!p.done;p=v.next()){var f=p.value;"string"!=typeof f&&(0!==f.props.type&&s.children.push(f))}}catch(t){o={error:t}}finally{try{p&&!p.done&&(a=v.return)&&a.call(v)}finally{if(o)throw o.error}}}}catch(t){n={error:t}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}return s},m=function(t,e,r,n,i){if(void 0===i&&(i=!1),"length"===e){var o=Object.keys(r).filter((function(e){return r[e]instanceof Array&&(n=t,i=r[e],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every((function(t,e){return t===i[e]})));var n,i}));return 0!==o.length&&n(o),!0}return i&&n([e]),!1},b=function(t,e){var r={get:function(t,e){return"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],r):t[e]},set:function(r,n,i){var o=r[n]!==i;return o&&(r[n]=i),m(r,n,t,e,o),!0},deleteProperty:function(r,n){return delete r[n],m(r,n,t,e),!0}};return new Proxy(t,r)},x=function(r,n,i){var o,s;void 0===n&&(n={});var u=!1,c=n.state||{};if(r){i||(i=Object.keys(c)),"%LUCIA_FIRST_RENDER%"===i[0]&&(u=!0);var p=function(e){if("string"==typeof e)return"continue";if(e.props.type>l.STATIC){var r=e.props,o=r.attributes,s=r.directives,p=r.ref,f=r.type,d=[];if(!u){var y=function(t){var e=1===f,r=i.some((function(e){return a(e).test(String(s[t].value))})),n=Object.keys(c).some((function(t){var e=i.some((function(e){return a(e).test(String(c[t]))}));return"function"==typeof c[t]&&e}));(e||r||n)&&d.push(t)};for(var h in s)y(h)}e.props.type=f===l.NEEDS_PATCH?l.STATIC:f,(u?Object.keys(s):d).map((function(e){var r=s[e],i=o.id?document.getElementById(o.id):p;v({el:i,name:e,data:r,app:n},t({},n.directives))}))}e.children.length>0&&x(e,c,i)};try{for(var f=e(r.children),d=f.next();!d.done;d=f.next()){p(d.value)}}catch(t){o={error:t}}finally{try{d&&!d.done&&(s=f.return)&&s.call(f)}finally{if(o)throw o.error}}}},E=function(){function e(t,e){void 0===t&&(t={}),this.state=t,this.directives={},this.components={},this.mountHook=e}return e.prototype.mount=function(e,r){void 0===r&&(r=!1);var n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),r||(this.state=b(this.state,this.patch.bind(this)),this.directives=t(t({},this.directives),c)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state},e.prototype.component=function(t,e){this.components[t.toUpperCase()]=e},e.prototype.directive=function(t,e){this.directives[t.toUpperCase()]=e},e.prototype.patch=function(t){var e={state:this.state,directives:this.directives,components:this.components};x(this.vdom,e,t)},e.prototype.compile=function(t){return y(t,this.state,this.components,!0)},e}(),g=function(t,e){return new E(t,e)};exports.compile=y,exports.createApp=g,exports.directives=c,exports.h=p,exports.init=function(t){void 0===t&&(t=document),n(t.querySelectorAll("[l-state]")).filter((function(t){return void 0===t.__l})).map((function(t){var e=t.getAttribute("l-state");try{var r=new Function("return "+e)(),n=g(r);n.mount(t),t.__l=n}catch(r){console.warn('Lucia Error: "'+r+'"\n\nExpression: "'+e+'"\nElement:',t)}}))},exports.listen=function(t,e,r){void 0===e&&(e=document);var n=new MutationObserver((function(i){i.map((function(e){e.addedNodes.length>0&&e.addedNodes.forEach((function(e){1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||t(e.parentElement))}))})),n.observe(e,r||{childList:!0,attributes:!0,subtree:!0})}))},exports.patch=x,exports.reactive=b,exports.renderDirective=v; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function r(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function n(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t}var i;!function(t){t["@"]="on",t[":"]="bind"}(i||(i={}));var o=function(){return new RegExp("(l-|"+Object.keys(i).join("|")+")\\w+","gim")},a=function(t,e){return void 0===e&&(e=!0),new RegExp((e?"this\\.":"")+t+"\\b")};function s(t){try{var e=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,n([void 0],Object.keys(this.argsKV),[e])))).bind(t).apply(void 0,n(Object.values(this.argsKV)))}catch(t){console.warn('Lucia Error: "'+t+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var l,u=function(t,e,r){return void 0===r&&(r=!0),s.bind({expression:t,argsKV:{$el:e.$el},returnable:r})},c={BIND:function(t){var e=t.el,r=t.name,n=t.data,i=t.app;switch(r.split(":")[1]){case"class":var o=n.compute(i.state);if("string"==typeof o)return e.setAttribute("class",(e.className+" "+o).trim());if(o instanceof Array)return e.setAttribute("class",(e.className+" "+o.join(" ")).trim());var a=[];for(var s in o)o[s]&&a.push(s);return a.length>0?e.setAttribute("class",(e.className+" "+a.join(" ").trim()).trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class");case"style":var l=n.compute(i.state);for(var s in e.removeAttribute("style"),l)e.style[s]=l[s];break;default:var u=n.compute(i.state);if("object"==typeof u&&null!==u)for(var s in u)u[s]?e.setAttribute(s,u[s]):e.removeAttribute(s);else u?e.setAttribute(r.split(":")[1],u):e.removeAttribute(r.split(":")[1])}},HTML:function(e){var n,i=e.el,o=e.data,a=e.app;i.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var s=x(t({},a.state));Object.entries(a.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.directive(n,i)})),Object.entries(a.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.component(n,i)})),s.mount(i)},IF:function(t){var e=t.el,r=t.data,n=t.app;r.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:function(t){var e=t.el,r=t.data,n=t.app,i=e,o=r.compute(n.state);i.value!==o&&(i.value=o),i.oninput=function(){return function(t,e,r,n){var i,o="number"==typeof e&&!isNaN(t.value),a="boolean"==typeof e&&("true"===t.value||"false"===t.value),s=null==e&&("null"===t.value||"undefined"===t.value);return i=o?"Number('"+t.value+"').toPrecision()":a?"Boolean('"+t.value+"')":s?"null"===t.value?null:void 0:"'"+t.value+"'",u(r.value+" = "+i,{$el:t},!1)(n.state),i}(i,o,r,n)}},ON:function(t){var e=t.el,n=t.name,i=t.data,o=t.app,a=r(n.split("."),2),s=a[0],l=a[1],u=s.split(":")[1],c=l||null;e["on"+u]=function(t){"prevent"===c&&t.preventDefault(),"stop"===c&&t.stopPropagation(),i.compute(o.state)}},TEXT:function(t){var e,r=t.el,n=t.data,i=t.app;r.textContent=null!==(e=n.compute(i.state))&&void 0!==e?e:n.value},FOR:function(e){var n=e.el,i=e.data,o=e.app,a=r(i.value.split(/ +in +/g),2),s=a[0],l=a[1],c=r(s.split(","),2),v=c[0],p=c[1],f=u(l,{$el:n})(o.state),d=String(n.__l_for);if(d){for(var h="",y=0;y<f.length;y++){var m=d;v&&(m=m.replace(new RegExp("this."+v.trim(),"g"),l+"["+y+"]")),p&&(m=m.replace(new RegExp("this."+p.trim(),"g"),String(y))),h+=m}n.innerHTML=h}else n.innerHTML=f.join("");var b=x(t({},o.state));Object.entries(o.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];b.directive(n,i)})),Object.entries(o.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];b.component(n,i)})),b.mount(n)}},v=function(t,e){e[t.name.split(/:|\./)[0].toUpperCase()](t)};!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(l||(l={}));var p=function(e,r,n){void 0===r&&(r=[]);var i=t({},null==n?void 0:n.attributes),o=t({},null==n?void 0:n.directives);return r=r instanceof Array?r:[r],i.className&&(i.className=i.className.trim()),{tag:e,children:r,props:{attributes:i,directives:o,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},f=function(t){var r,o,a={},s={};if(t.attributes)try{for(var l=e(n(t.attributes)),c=l.next();!c.done;c=l.next()){var v=c.value,p=v.name,f=v.value,d=!0;p.includes("for")&&void 0===t.__l_for&&(t.__l_for=String(t.innerHTML).trim(),d=!1),/on|@/.test(p)&&(d=!1);var h={compute:u(f,{$el:t},d),value:f};p.startsWith("l-")?s[p.slice("l-".length)]=h:Object.keys(i).includes(p[0])?s[i[p[0]]+":"+p.slice(1)]=h:a[p]=f}}catch(t){r={error:t}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(r)throw r.error}}return{attributes:a,directives:s}},d=function(t,e,r){var n=f(t),i=n.attributes,o=n.directives,s=l.STATIC,u=Object.keys(o).length>0,c=Object.values(o).some((function(t){var r=t.value;return Object.keys(e).some((function(t){return a(t,!1).test(r)}))}));return u&&(s=l.NEEDS_PATCH),c&&(s=l.DYNAMIC),p(t.tagName.toLowerCase(),r,{attributes:i,directives:o,ref:s===l.STATIC||i.id?void 0:t,type:s})},h=function(t,n,i,a,s){var l,u,c,v,p,m,b;if(void 0===n&&(n={}),void 0===i&&(i={}),void 0===a&&(a=!1),void 0===s&&(s=!1),!t)throw new Error("Please provide a Element");var g=[],E=Array.prototype.slice.call(t.childNodes);try{for(var x=e(E),A=x.next();!A.done;A=x.next()){var T=A.value;switch(T.nodeType){case Node.TEXT_NODE:!a&&T.nodeValue&&g.push(T.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(i).includes(T.tagName)){var N=document.createElement("div"),j=i[T.tagName]({children:T.innerHTML,state:n});N.innerHTML=j;try{for(var w=(c=void 0,e(Object.entries(f(T).directives))),O=w.next();!O.done;O=w.next()){var _=r(O.value,2),S=_[0],C=_[1];null===(b=N.firstElementChild)||void 0===b||b.setAttribute("l-"+S,C.value)}}catch(t){c={error:t}}finally{try{O&&!O.done&&(v=w.return)&&v.call(w)}finally{if(c)throw c.error}}if(!a||o().test(N.outerHTML)){var L=h(N,n,i,a,!0);try{for(var H=(p=void 0,e(L)),I=H.next();!I.done;I=H.next()){var M=I.value;g.push(M)}}catch(t){p={error:t}}finally{try{I&&!I.done&&(m=H.return)&&m.call(H)}finally{if(p)throw p.error}}}t.replaceChild(N.firstElementChild,T)}else if(!a||o().test(T.outerHTML)){L=h(T,n,i,a,!0);var k=d(T,n,L);g.push(k)}}}}catch(t){l={error:t}}finally{try{A&&!A.done&&(u=x.return)&&u.call(x)}finally{if(l)throw l.error}}if(s)return g;var D=d(t,n,g);return a?y(D):D},y=function(r){var i,o,a=t({},r);a.children=a.children.filter((function(t){return"object"==typeof t&&t.props.type>0}));try{for(var s=e(r.children),l=s.next();!l.done;l=s.next()){var u=l.value;"string"!=typeof u&&(u.children.length>0&&(a.children=n(a.children,y({children:u.children}).children),u.children=[]))}}catch(t){i={error:t}}finally{try{l&&!l.done&&(o=s.return)&&o.call(s)}finally{if(i)throw i.error}}return a},m=function(t,e,r,n,i){if(void 0===i&&(i=!1),"length"===e){var o=Object.keys(r).filter((function(e){return r[e]instanceof Array&&(n=t,i=r[e],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every((function(t,e){return t===i[e]})));var n,i}));return 0!==o.length&&n(o),!0}return i&&n([e]),!1},b=function(t,e){var r={get:function(t,e){return"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],r):t[e]},set:function(r,n,i){var o=r[n]!==i;return o&&(r[n]=i),m(r,n,t,e,o),!0},deleteProperty:function(r,n){return delete r[n],m(r,n,t,e,!0),!0}};return new Proxy(t,r)},g=function(r,n,i){var o,s;void 0===n&&(n={});var u=!1,c=n.state||{};if(r){i||(i=Object.keys(c)),"%LUCIA_FIRST_RENDER%"===i[0]&&(u=!0);var p=function(e){if("string"==typeof e)return"continue";if(e.props.type>l.STATIC){var r=e.props,o=r.attributes,s=r.directives,p=r.ref,f=r.type,d=[];if(!u){var h=function(t){var e=1===f,r=i.some((function(e){return a(e).test(String(s[t].value))})),n=Object.keys(c).some((function(t){var e=i.some((function(e){return a(e).test(String(c[t]))}));return"function"==typeof c[t]&&e}));(e||r||n)&&d.push(t)};for(var y in s)h(y)}e.props.type=f===l.NEEDS_PATCH?l.STATIC:f,(u?Object.keys(s):d).map((function(e){var r=s[e],i=o.id?document.getElementById(o.id):p;v({el:i,name:e,data:r,app:n},t({},n.directives))}))}e.children.length>0&&g(e,n,i)};try{for(var f=e(r.children),d=f.next();!d.done;d=f.next()){p(d.value)}}catch(t){o={error:t}}finally{try{d&&!d.done&&(s=f.return)&&s.call(f)}finally{if(o)throw o.error}}}},E=function(){function e(t,e){void 0===t&&(t={}),this.state=t,this.directives={},this.components={},this.mountHook=e}return e.prototype.mount=function(e,r){void 0===r&&(r=!1);var n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),r||(this.state=b(this.state,this.patch.bind(this)),this.directives=t(t({},this.directives),c)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state},e.prototype.component=function(t,e){this.components[t.toUpperCase()]=e},e.prototype.directive=function(t,e){this.directives[t.toUpperCase()]=e},e.prototype.patch=function(t){var e={state:this.state,directives:this.directives,components:this.components};g(this.vdom,e,t)},e.prototype.compile=function(t){return h(t,this.state,this.components,!0)},e}(),x=function(t,e){return new E(t,e)};exports.compile=h,exports.createApp=x,exports.directives=c,exports.h=p,exports.init=function(t){void 0===t&&(t=document),n(t.querySelectorAll("[l-state]")).filter((function(t){return void 0===t.__l})).map((function(t){var e=t.getAttribute("l-state");try{var r=new Function("return "+e)(),n=x(r);n.mount(t),t.__l=n}catch(r){console.warn('Lucia Error: "'+r+'"\n\nExpression: "'+e+'"\nElement:',t)}}))},exports.listen=function(t,e,r){void 0===e&&(e=document),new MutationObserver((function(e){e.map((function(e){if(e.addedNodes.length>0)e.addedNodes.forEach((function(e){1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||e.getAttribute("l-state")&&t(e.parentElement))}));else if("attributes"===e.type){if(e.target.parentElement&&e.target.parentElement.closest("[l-state]"))return;t(e.target.parentElement)}}))})).observe(e,r||{childList:!0,attributes:!0,subtree:!0})},exports.patch=g,exports.reactive=b,exports.renderDirective=v; |
@@ -70,4 +70,7 @@ /*! ***************************************************************************** | ||
var rawDirectiveSplitPattern = /:|\./; | ||
var keyPattern = function (key, hasThis) { | ||
var rawDirectiveSplitRE = function () { return /:|\./; }; | ||
var hasDirectiveRE = function () { | ||
return new RegExp("(" + DIRECTIVE_PREFIX + "|" + Object.keys(DIRECTIVE_SHORTHANDS).join('|') + ")\\w+", 'gim'); | ||
}; | ||
var expressionPropRE = function (key, hasThis) { | ||
if (hasThis === void 0) { hasThis = true; } | ||
@@ -174,20 +177,26 @@ return new RegExp("" + (hasThis ? 'this\\.' : '') + key + "\\b"); | ||
var joinDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ as | by /), 3), array = _b[0], contentType = _b[1], delimiter = _b[2]; | ||
var hydratedArray = compute(array, { $el: el })(app.state); | ||
var accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
var inputCallback = function (el, hydratedValue, data, app) { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
var modelDirective = function (_a) { | ||
@@ -200,25 +209,3 @@ var awaitingTypecastEl = _a.el, data = _a.data, app = _a.app; | ||
} | ||
el.oninput = function () { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
}; | ||
el.oninput = function () { return inputCallback(el, hydratedValue, data, app); }; | ||
}; | ||
@@ -246,5 +233,37 @@ | ||
var forDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ +in +/g), 2), expression = _b[0], target = _b[1]; | ||
var _c = __read(expression.split(','), 2), item = _c[0], index = _c[1]; | ||
var hydratedArray = compute(target, { $el: el })(app.state); | ||
var template = String(el.__l_for); | ||
if (template) { | ||
var accumulator = ''; | ||
for (var i = 0; i < hydratedArray.length; i++) { | ||
var content = template; | ||
if (item) | ||
content = content.replace(new RegExp("this." + item.trim(), 'g'), target + "[" + i + "]"); | ||
if (index) | ||
content = content.replace(new RegExp("this." + index.trim(), 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
var directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
@@ -255,5 +274,6 @@ IF: ifDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
var renderDirective = function (props, directives) { | ||
var name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
var name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
@@ -296,3 +316,10 @@ }; | ||
var _d = _c.value, name_1 = _d.name, value = _d.value; | ||
var directiveData = { compute: compute(value, { $el: el }), value: value }; | ||
var returnable = true; | ||
if (name_1.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name_1)) | ||
returnable = false; | ||
var directiveData = { compute: compute(value, { $el: el }, returnable), value: value }; | ||
if (name_1.startsWith(DIRECTIVE_PREFIX)) { | ||
@@ -326,3 +353,3 @@ directives[name_1.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
var value = _a.value; | ||
return Object.keys(state).some(function (key) { return keyPattern(key, false).test(value); }); | ||
return Object.keys(state).some(function (key) { return expressionPropRE(key, false).test(value); }); | ||
}); | ||
@@ -381,3 +408,3 @@ if (hasDirectives) | ||
} | ||
if (!strip || container.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
var compiledChildren = compile(container, state, components, strip, true); | ||
@@ -401,3 +428,3 @@ try { | ||
else { | ||
if (!strip || child.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
var compiledChildren = compile(child, state, components, strip, true); | ||
@@ -428,28 +455,13 @@ var node = createVNode(child, state, compiledChildren); | ||
var flat = function (vdom) { | ||
var e_4, _a, e_5, _b; | ||
var e_4, _a; | ||
var flattenedVDom = __assign({}, vdom); | ||
flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
flattenedVDom.children = flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
try { | ||
for (var _c = __values(vdom.children), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
var child = _d.value; | ||
for (var _b = __values(vdom.children), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var child = _c.value; | ||
if (typeof child === 'string') | ||
continue; | ||
if (child.children.length > 0) { | ||
try { | ||
for (var _e = (e_5 = void 0, __values(flat(child).children)), _f = _e.next(); !_f.done; _f = _e.next()) { | ||
var nestedChild = _f.value; | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
} | ||
catch (e_5_1) { e_5 = { error: e_5_1 }; } | ||
finally { | ||
try { | ||
if (_f && !_f.done && (_b = _e.return)) _b.call(_e); | ||
} | ||
finally { if (e_5) throw e_5.error; } | ||
} | ||
flattenedVDom.children = __spread(flattenedVDom.children, flat({ children: child.children }).children); | ||
child.children = []; | ||
} | ||
@@ -461,3 +473,3 @@ } | ||
try { | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
@@ -512,3 +524,3 @@ finally { if (e_4) throw e_4.error; } | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
@@ -540,6 +552,8 @@ }, | ||
var needsInit = type === 1; | ||
var hasKey = keys.some(function (key) { return keyPattern(key).test(String(directives_1[name_1].value)); }); | ||
var hasKey = keys.some(function (key) { | ||
return expressionPropRE(key).test(String(directives_1[name_1].value)); | ||
}); | ||
var hasKeyInFunction = Object.keys(state).some(function (key) { | ||
var iterKeysInFunction = keys.some(function (k) { | ||
return keyPattern(k).test(String(state[key])); | ||
return expressionPropRE(k).test(String(state[key])); | ||
}); | ||
@@ -567,3 +581,3 @@ return typeof state[key] === 'function' && iterKeysInFunction; | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
patch(node, app, keys); | ||
}; | ||
@@ -658,14 +672,21 @@ try { | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest("[" + stateDirective + "]")) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
export { compile, createApp, directives, h, init, listen, patch, reactive, renderDirective }; |
@@ -1,1 +0,1 @@ | ||
var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function r(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function n(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t}var i;!function(t){t["@"]="on",t[":"]="bind"}(i||(i={}));var o=/:|\./,a=function(t,e){return void 0===e&&(e=!0),new RegExp((e?"this\\.":"")+t+"\\b")};function s(t){try{var e=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,n([void 0],Object.keys(this.argsKV),[e])))).bind(t).apply(void 0,n(Object.values(this.argsKV)))}catch(t){console.warn('Lucia Error: "'+t+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var l,u=function(t,e,r){return void 0===r&&(r=!0),s.bind({expression:t,argsKV:{$el:e.$el},returnable:r})},c={BIND:function(t){var e=t.el,r=t.name,n=t.data,i=t.app;switch(r.split(":")[1]){case"class":var o=n.compute(i.state);if("string"==typeof o)return e.setAttribute("class",(e.className+" "+o).trim());if(o instanceof Array)return e.setAttribute("class",(e.className+" "+o.join(" ")).trim());var a=[];for(var s in o)o[s]&&a.push(s);return a.length>0?e.setAttribute("class",(e.className+" "+a.join(" ").trim()).trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class");case"style":var l=n.compute(i.state);for(var s in e.removeAttribute("style"),l)e.style[s]=l[s];break;default:var u=n.compute(i.state);if("object"==typeof u&&null!==u)for(var s in u)u[s]?e.setAttribute(s,u[s]):e.removeAttribute(s);else u?e.setAttribute(r.split(":")[1],u):e.removeAttribute(r.split(":")[1])}},JOIN:function(e){var n=e.el,i=e.data,o=e.app,a=r(i.value.split(/ as | by /),3),s=a[0],l=a[1],c=a[2],v=u(s,{$el:n})(o.state);n["text"===l?"innerText":"innerHTML"]=v.join(c||"");var f=A(t({},o.state));Object.entries(o.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];f.directive(n,i)})),Object.entries(o.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];f.component(n,i)})),f.mount(n)},HTML:function(e){var n,i=e.el,o=e.data,a=e.app;i.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var s=A(t({},a.state));Object.entries(a.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.directive(n,i)})),Object.entries(a.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.component(n,i)})),s.mount(i)},IF:function(t){var e=t.el,r=t.data,n=t.app;r.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:function(t){var e=t.el,r=t.data,n=t.app,i=e,o=r.compute(n.state);i.value!==o&&(i.value=o),i.oninput=function(){var t,e="number"==typeof o&&!isNaN(i.value),a="boolean"==typeof o&&("true"===i.value||"false"===i.value),s=null==o&&("null"===i.value||"undefined"===i.value);t=e?"Number('"+i.value+"').toPrecision()":a?"Boolean('"+i.value+"')":s?"null"===i.value?null:void 0:"'"+i.value+"'",u(r.value+" = "+t,{$el:i},!1)(n.state)}},ON:function(t){var e=t.el,n=t.name,i=t.data,o=t.app,a=r(n.split("."),2),s=a[0],l=a[1],u=s.split(":")[1],c=l||null;e["on"+u]=function(t){"prevent"===c&&t.preventDefault(),"stop"===c&&t.stopPropagation(),i.compute(o.state)}},TEXT:function(t){var e,r=t.el,n=t.data,i=t.app;r.textContent=null!==(e=n.compute(i.state))&&void 0!==e?e:n.value}},v=function(t,e){e[t.name.split(o)[0].toUpperCase()](t)};!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(l||(l={}));var f=function(e,r,n){void 0===r&&(r=[]);var i=t({},null==n?void 0:n.attributes),o=t({},null==n?void 0:n.directives);return r=r instanceof Array?r:[r],i.className&&(i.className=i.className.trim()),{tag:e,children:r,props:{attributes:i,directives:o,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},p=function(t){var r,o,a={},s={};if(t.attributes)try{for(var l=e(n(t.attributes)),c=l.next();!c.done;c=l.next()){var v=c.value,f=v.name,p=v.value,d={compute:u(p,{$el:t}),value:p};f.startsWith("l-")?s[f.slice("l-".length)]=d:Object.keys(i).includes(f[0])?s[i[f[0]]+":"+f.slice(1)]=d:a[f]=p}}catch(t){r={error:t}}finally{try{c&&!c.done&&(o=l.return)&&o.call(l)}finally{if(r)throw r.error}}return{attributes:a,directives:s}},d=function(t,e,r){var n=p(t),i=n.attributes,o=n.directives,s=l.STATIC,u=Object.keys(o).length>0,c=Object.values(o).some((function(t){var r=t.value;return Object.keys(e).some((function(t){return a(t,!1).test(r)}))}));return u&&(s=l.NEEDS_PATCH),c&&(s=l.DYNAMIC),f(t.tagName.toLowerCase(),r,{attributes:i,directives:o,ref:s===l.STATIC||i.id?void 0:t,type:s})},y=function(t,n,i,o,a){var s,l,u,c,v,f,m;if(void 0===n&&(n={}),void 0===i&&(i={}),void 0===o&&(o=!1),void 0===a&&(a=!1),!t)throw new Error("Please provide a Element");var b=[],E=Array.prototype.slice.call(t.childNodes);try{for(var g=e(E),A=g.next();!A.done;A=g.next()){var N=A.value;switch(N.nodeType){case Node.TEXT_NODE:!o&&N.nodeValue&&b.push(N.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(i).includes(N.tagName)){var T=document.createElement("div"),x=i[N.tagName]({children:N.innerHTML,state:n});T.innerHTML=x;try{for(var O=(u=void 0,e(Object.entries(p(N).directives))),j=O.next();!j.done;j=O.next()){var w=r(j.value,2),C=w[0],S=w[1];null===(m=T.firstElementChild)||void 0===m||m.setAttribute("l-"+C,S.value)}}catch(t){u={error:t}}finally{try{j&&!j.done&&(c=O.return)&&c.call(O)}finally{if(u)throw u.error}}if(!o||T.outerHTML.includes(" l-")){var I=y(T,n,i,o,!0);try{for(var L=(v=void 0,e(I)),k=L.next();!k.done;k=L.next()){var D=k.value;b.push(D)}}catch(t){v={error:t}}finally{try{k&&!k.done&&(f=L.return)&&f.call(L)}finally{if(v)throw v.error}}}t.replaceChild(T.firstElementChild,N)}else if(!o||N.outerHTML.includes(" l-")){I=y(N,n,i,o,!0);var H=d(N,n,I);b.push(H)}}}}catch(t){s={error:t}}finally{try{A&&!A.done&&(l=g.return)&&l.call(g)}finally{if(s)throw s.error}}if(a)return b;var _=d(t,n,b);return o?h(_):_},h=function(r){var n,i,o,a,s=t({},r);s.children.filter((function(t){return"object"==typeof t&&t.props.type>0}));try{for(var l=e(r.children),u=l.next();!u.done;u=l.next()){var c=u.value;if("string"!=typeof c&&c.children.length>0)try{for(var v=(o=void 0,e(h(c).children)),f=v.next();!f.done;f=v.next()){var p=f.value;"string"!=typeof p&&(0!==p.props.type&&s.children.push(p))}}catch(t){o={error:t}}finally{try{f&&!f.done&&(a=v.return)&&a.call(v)}finally{if(o)throw o.error}}}}catch(t){n={error:t}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}return s},m=function(t,e,r,n,i){if(void 0===i&&(i=!1),"length"===e){var o=Object.keys(r).filter((function(e){return r[e]instanceof Array&&(n=t,i=r[e],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every((function(t,e){return t===i[e]})));var n,i}));return 0!==o.length&&n(o),!0}return i&&n([e]),!1},b=function(t,e){var r={get:function(t,e){return"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],r):t[e]},set:function(r,n,i){var o=r[n]!==i;return o&&(r[n]=i),m(r,n,t,e,o),!0},deleteProperty:function(r,n){return delete r[n],m(r,n,t,e),!0}};return new Proxy(t,r)},E=function(r,n,i){var o,s;void 0===n&&(n={});var u=!1,c=n.state||{};if(r){i||(i=Object.keys(c)),"%LUCIA_FIRST_RENDER%"===i[0]&&(u=!0);var f=function(e){if("string"==typeof e)return"continue";if(e.props.type>l.STATIC){var r=e.props,o=r.attributes,s=r.directives,f=r.ref,p=r.type,d=[];if(!u){var y=function(t){var e=1===p,r=i.some((function(e){return a(e).test(String(s[t].value))})),n=Object.keys(c).some((function(t){var e=i.some((function(e){return a(e).test(String(c[t]))}));return"function"==typeof c[t]&&e}));(e||r||n)&&d.push(t)};for(var h in s)y(h)}e.props.type=p===l.NEEDS_PATCH?l.STATIC:p,(u?Object.keys(s):d).map((function(e){var r=s[e],i=o.id?document.getElementById(o.id):f;v({el:i,name:e,data:r,app:n},t({},n.directives))}))}e.children.length>0&&E(e,c,i)};try{for(var p=e(r.children),d=p.next();!d.done;d=p.next()){f(d.value)}}catch(t){o={error:t}}finally{try{d&&!d.done&&(s=p.return)&&s.call(p)}finally{if(o)throw o.error}}}},g=function(){function e(t,e){void 0===t&&(t={}),this.state=t,this.directives={},this.components={},this.mountHook=e}return e.prototype.mount=function(e,r){void 0===r&&(r=!1);var n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),r||(this.state=b(this.state,this.patch.bind(this)),this.directives=t(t({},this.directives),c)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state},e.prototype.component=function(t,e){this.components[t.toUpperCase()]=e},e.prototype.directive=function(t,e){this.directives[t.toUpperCase()]=e},e.prototype.patch=function(t){var e={state:this.state,directives:this.directives,components:this.components};E(this.vdom,e,t)},e.prototype.compile=function(t){return y(t,this.state,this.components,!0)},e}(),A=function(t,e){return new g(t,e)},N=function(t){void 0===t&&(t=document),n(t.querySelectorAll("[l-state]")).filter((function(t){return void 0===t.__l})).map((function(t){var e=t.getAttribute("l-state");try{var r=new Function("return "+e)(),n=A(r);n.mount(t),t.__l=n}catch(r){console.warn('Lucia Error: "'+r+'"\n\nExpression: "'+e+'"\nElement:',t)}}))},T=function(t,e,r){void 0===e&&(e=document);var n=new MutationObserver((function(i){i.map((function(e){e.addedNodes.length>0&&e.addedNodes.forEach((function(e){1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||t(e.parentElement))}))})),n.observe(e,r||{childList:!0,attributes:!0,subtree:!0})}))};export{y as compile,A as createApp,c as directives,f as h,N as init,T as listen,E as patch,b as reactive,v as renderDirective}; | ||
var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function r(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function n(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t}var i;!function(t){t["@"]="on",t[":"]="bind"}(i||(i={}));var o=function(){return new RegExp("(l-|"+Object.keys(i).join("|")+")\\w+","gim")},a=function(t,e){return void 0===e&&(e=!0),new RegExp((e?"this\\.":"")+t+"\\b")};function l(t){try{var e=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,n([void 0],Object.keys(this.argsKV),[e])))).bind(t).apply(void 0,n(Object.values(this.argsKV)))}catch(t){console.warn('Lucia Error: "'+t+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var s,u=function(t,e,r){return void 0===r&&(r=!0),l.bind({expression:t,argsKV:{$el:e.$el},returnable:r})},c={BIND:function(t){var e=t.el,r=t.name,n=t.data,i=t.app;switch(r.split(":")[1]){case"class":var o=n.compute(i.state);if("string"==typeof o)return e.setAttribute("class",(e.className+" "+o).trim());if(o instanceof Array)return e.setAttribute("class",(e.className+" "+o.join(" ")).trim());var a=[];for(var l in o)o[l]&&a.push(l);return a.length>0?e.setAttribute("class",(e.className+" "+a.join(" ").trim()).trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class");case"style":var s=n.compute(i.state);for(var l in e.removeAttribute("style"),s)e.style[l]=s[l];break;default:var u=n.compute(i.state);if("object"==typeof u&&null!==u)for(var l in u)u[l]?e.setAttribute(l,u[l]):e.removeAttribute(l);else u?e.setAttribute(r.split(":")[1],u):e.removeAttribute(r.split(":")[1])}},HTML:function(e){var n,i=e.el,o=e.data,a=e.app;i.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var l=A(t({},a.state));Object.entries(a.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];l.directive(n,i)})),Object.entries(a.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];l.component(n,i)})),l.mount(i)},IF:function(t){var e=t.el,r=t.data,n=t.app;r.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:function(t){var e=t.el,r=t.data,n=t.app,i=e,o=r.compute(n.state);i.value!==o&&(i.value=o),i.oninput=function(){return function(t,e,r,n){var i,o="number"==typeof e&&!isNaN(t.value),a="boolean"==typeof e&&("true"===t.value||"false"===t.value),l=null==e&&("null"===t.value||"undefined"===t.value);return i=o?"Number('"+t.value+"').toPrecision()":a?"Boolean('"+t.value+"')":l?"null"===t.value?null:void 0:"'"+t.value+"'",u(r.value+" = "+i,{$el:t},!1)(n.state),i}(i,o,r,n)}},ON:function(t){var e=t.el,n=t.name,i=t.data,o=t.app,a=r(n.split("."),2),l=a[0],s=a[1],u=l.split(":")[1],c=s||null;e["on"+u]=function(t){"prevent"===c&&t.preventDefault(),"stop"===c&&t.stopPropagation(),i.compute(o.state)}},TEXT:function(t){var e,r=t.el,n=t.data,i=t.app;r.textContent=null!==(e=n.compute(i.state))&&void 0!==e?e:n.value},FOR:function(e){var n=e.el,i=e.data,o=e.app,a=r(i.value.split(/ +in +/g),2),l=a[0],s=a[1],c=r(l.split(","),2),v=c[0],f=c[1],p=u(s,{$el:n})(o.state),d=String(n.__l_for);if(d){for(var h="",y=0;y<p.length;y++){var m=d;v&&(m=m.replace(new RegExp("this."+v.trim(),"g"),s+"["+y+"]")),f&&(m=m.replace(new RegExp("this."+f.trim(),"g"),String(y))),h+=m}n.innerHTML=h}else n.innerHTML=p.join("");var b=A(t({},o.state));Object.entries(o.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];b.directive(n,i)})),Object.entries(o.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];b.component(n,i)})),b.mount(n)}},v=function(t,e){e[t.name.split(/:|\./)[0].toUpperCase()](t)};!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(s||(s={}));var f=function(e,r,n){void 0===r&&(r=[]);var i=t({},null==n?void 0:n.attributes),o=t({},null==n?void 0:n.directives);return r=r instanceof Array?r:[r],i.className&&(i.className=i.className.trim()),{tag:e,children:r,props:{attributes:i,directives:o,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},p=function(t){var r,o,a={},l={};if(t.attributes)try{for(var s=e(n(t.attributes)),c=s.next();!c.done;c=s.next()){var v=c.value,f=v.name,p=v.value,d=!0;f.includes("for")&&void 0===t.__l_for&&(t.__l_for=String(t.innerHTML).trim(),d=!1),/on|@/.test(f)&&(d=!1);var h={compute:u(p,{$el:t},d),value:p};f.startsWith("l-")?l[f.slice("l-".length)]=h:Object.keys(i).includes(f[0])?l[i[f[0]]+":"+f.slice(1)]=h:a[f]=p}}catch(t){r={error:t}}finally{try{c&&!c.done&&(o=s.return)&&o.call(s)}finally{if(r)throw r.error}}return{attributes:a,directives:l}},d=function(t,e,r){var n=p(t),i=n.attributes,o=n.directives,l=s.STATIC,u=Object.keys(o).length>0,c=Object.values(o).some((function(t){var r=t.value;return Object.keys(e).some((function(t){return a(t,!1).test(r)}))}));return u&&(l=s.NEEDS_PATCH),c&&(l=s.DYNAMIC),f(t.tagName.toLowerCase(),r,{attributes:i,directives:o,ref:l===s.STATIC||i.id?void 0:t,type:l})},h=function(t,n,i,a,l){var s,u,c,v,f,m,b;if(void 0===n&&(n={}),void 0===i&&(i={}),void 0===a&&(a=!1),void 0===l&&(l=!1),!t)throw new Error("Please provide a Element");var g=[],E=Array.prototype.slice.call(t.childNodes);try{for(var A=e(E),T=A.next();!T.done;T=A.next()){var N=T.value;switch(N.nodeType){case Node.TEXT_NODE:!a&&N.nodeValue&&g.push(N.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(i).includes(N.tagName)){var w=document.createElement("div"),x=i[N.tagName]({children:N.innerHTML,state:n});w.innerHTML=x;try{for(var j=(c=void 0,e(Object.entries(p(N).directives))),O=j.next();!O.done;O=j.next()){var S=r(O.value,2),C=S[0],_=S[1];null===(b=w.firstElementChild)||void 0===b||b.setAttribute("l-"+C,_.value)}}catch(t){c={error:t}}finally{try{O&&!O.done&&(v=j.return)&&v.call(j)}finally{if(c)throw c.error}}if(!a||o().test(w.outerHTML)){var L=h(w,n,i,a,!0);try{for(var H=(f=void 0,e(L)),I=H.next();!I.done;I=H.next()){var k=I.value;g.push(k)}}catch(t){f={error:t}}finally{try{I&&!I.done&&(m=H.return)&&m.call(H)}finally{if(f)throw f.error}}}t.replaceChild(w.firstElementChild,N)}else if(!a||o().test(N.outerHTML)){L=h(N,n,i,a,!0);var M=d(N,n,L);g.push(M)}}}}catch(t){s={error:t}}finally{try{T&&!T.done&&(u=A.return)&&u.call(A)}finally{if(s)throw s.error}}if(l)return g;var D=d(t,n,g);return a?y(D):D},y=function(r){var i,o,a=t({},r);a.children=a.children.filter((function(t){return"object"==typeof t&&t.props.type>0}));try{for(var l=e(r.children),s=l.next();!s.done;s=l.next()){var u=s.value;"string"!=typeof u&&(u.children.length>0&&(a.children=n(a.children,y({children:u.children}).children),u.children=[]))}}catch(t){i={error:t}}finally{try{s&&!s.done&&(o=l.return)&&o.call(l)}finally{if(i)throw i.error}}return a},m=function(t,e,r,n,i){if(void 0===i&&(i=!1),"length"===e){var o=Object.keys(r).filter((function(e){return r[e]instanceof Array&&(n=t,i=r[e],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every((function(t,e){return t===i[e]})));var n,i}));return 0!==o.length&&n(o),!0}return i&&n([e]),!1},b=function(t,e){var r={get:function(t,e){return"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],r):t[e]},set:function(r,n,i){var o=r[n]!==i;return o&&(r[n]=i),m(r,n,t,e,o),!0},deleteProperty:function(r,n){return delete r[n],m(r,n,t,e,!0),!0}};return new Proxy(t,r)},g=function(r,n,i){var o,l;void 0===n&&(n={});var u=!1,c=n.state||{};if(r){i||(i=Object.keys(c)),"%LUCIA_FIRST_RENDER%"===i[0]&&(u=!0);var f=function(e){if("string"==typeof e)return"continue";if(e.props.type>s.STATIC){var r=e.props,o=r.attributes,l=r.directives,f=r.ref,p=r.type,d=[];if(!u){var h=function(t){var e=1===p,r=i.some((function(e){return a(e).test(String(l[t].value))})),n=Object.keys(c).some((function(t){var e=i.some((function(e){return a(e).test(String(c[t]))}));return"function"==typeof c[t]&&e}));(e||r||n)&&d.push(t)};for(var y in l)h(y)}e.props.type=p===s.NEEDS_PATCH?s.STATIC:p,(u?Object.keys(l):d).map((function(e){var r=l[e],i=o.id?document.getElementById(o.id):f;v({el:i,name:e,data:r,app:n},t({},n.directives))}))}e.children.length>0&&g(e,n,i)};try{for(var p=e(r.children),d=p.next();!d.done;d=p.next()){f(d.value)}}catch(t){o={error:t}}finally{try{d&&!d.done&&(l=p.return)&&l.call(p)}finally{if(o)throw o.error}}}},E=function(){function e(t,e){void 0===t&&(t={}),this.state=t,this.directives={},this.components={},this.mountHook=e}return e.prototype.mount=function(e,r){void 0===r&&(r=!1);var n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),r||(this.state=b(this.state,this.patch.bind(this)),this.directives=t(t({},this.directives),c)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state},e.prototype.component=function(t,e){this.components[t.toUpperCase()]=e},e.prototype.directive=function(t,e){this.directives[t.toUpperCase()]=e},e.prototype.patch=function(t){var e={state:this.state,directives:this.directives,components:this.components};g(this.vdom,e,t)},e.prototype.compile=function(t){return h(t,this.state,this.components,!0)},e}(),A=function(t,e){return new E(t,e)},T=function(t){void 0===t&&(t=document),n(t.querySelectorAll("[l-state]")).filter((function(t){return void 0===t.__l})).map((function(t){var e=t.getAttribute("l-state");try{var r=new Function("return "+e)(),n=A(r);n.mount(t),t.__l=n}catch(r){console.warn('Lucia Error: "'+r+'"\n\nExpression: "'+e+'"\nElement:',t)}}))},N=function(t,e,r){void 0===e&&(e=document),new MutationObserver((function(e){e.map((function(e){if(e.addedNodes.length>0)e.addedNodes.forEach((function(e){1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||e.getAttribute("l-state")&&t(e.parentElement))}));else if("attributes"===e.type){if(e.target.parentElement&&e.target.parentElement.closest("[l-state]"))return;t(e.target.parentElement)}}))})).observe(e,r||{childList:!0,attributes:!0,subtree:!0})};export{h as compile,A as createApp,c as directives,f as h,T as init,N as listen,g as patch,b as reactive,v as renderDirective}; |
@@ -33,2 +33,40 @@ (function (global, factory) { | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
function __generator(thisArg, body) { | ||
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; | ||
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; | ||
function verb(n) { return function (v) { return step([n, v]); }; } | ||
function step(op) { | ||
if (f) throw new TypeError("Generator is already executing."); | ||
while (_) try { | ||
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; | ||
if (y = 0, t) op = [op[0] & 2, t.value]; | ||
switch (op[0]) { | ||
case 0: case 1: t = op; break; | ||
case 4: _.label++; return { value: op[1], done: false }; | ||
case 5: _.label++; y = op[1]; op = [0]; continue; | ||
case 7: op = _.ops.pop(); _.trys.pop(); continue; | ||
default: | ||
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } | ||
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } | ||
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } | ||
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } | ||
if (t[2]) _.ops.pop(); | ||
_.trys.pop(); continue; | ||
} | ||
op = body.call(thisArg, _); | ||
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } | ||
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; | ||
} | ||
} | ||
function __values(o) { | ||
@@ -77,4 +115,7 @@ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; | ||
var rawDirectiveSplitPattern = /:|\./; | ||
var keyPattern = function (key, hasThis) { | ||
var rawDirectiveSplitRE = function () { return /:|\./; }; | ||
var hasDirectiveRE = function () { | ||
return new RegExp("(" + DIRECTIVE_PREFIX + "|" + Object.keys(DIRECTIVE_SHORTHANDS).join('|') + ")\\w+", 'gim'); | ||
}; | ||
var expressionPropRE = function (key, hasThis) { | ||
if (hasThis === void 0) { hasThis = true; } | ||
@@ -181,20 +222,26 @@ return new RegExp("" + (hasThis ? 'this\\.' : '') + key + "\\b"); | ||
var joinDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ as | by /), 3), array = _b[0], contentType = _b[1], delimiter = _b[2]; | ||
var hydratedArray = compute(array, { $el: el })(app.state); | ||
var accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
var inputCallback = function (el, hydratedValue, data, app) { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
var modelDirective = function (_a) { | ||
@@ -207,25 +254,3 @@ var awaitingTypecastEl = _a.el, data = _a.data, app = _a.app; | ||
} | ||
el.oninput = function () { | ||
var isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
var isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
var isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
var payload; | ||
if (isNumber) { | ||
payload = "Number('" + el.value + "').toPrecision()"; | ||
} | ||
else if (isBoolean) { | ||
payload = "Boolean('" + el.value + "')"; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = "'" + el.value + "'"; | ||
} | ||
compute(data.value + " = " + payload, { $el: el }, false)(app.state); | ||
}; | ||
el.oninput = function () { return inputCallback(el, hydratedValue, data, app); }; | ||
}; | ||
@@ -253,5 +278,37 @@ | ||
var forDirective = function (_a) { | ||
var el = _a.el, data = _a.data, app = _a.app; | ||
var _b = __read(data.value.split(/ +in +/g), 2), expression = _b[0], target = _b[1]; | ||
var _c = __read(expression.split(','), 2), item = _c[0], index = _c[1]; | ||
var hydratedArray = compute(target, { $el: el })(app.state); | ||
var template = String(el.__l_for); | ||
if (template) { | ||
var accumulator = ''; | ||
for (var i = 0; i < hydratedArray.length; i++) { | ||
var content = template; | ||
if (item) | ||
content = content.replace(new RegExp("this." + item.trim(), 'g'), target + "[" + i + "]"); | ||
if (index) | ||
content = content.replace(new RegExp("this." + index.trim(), 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
var scope = createApp(__assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], evaluationCallback = _b[1]; | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(function (_a) { | ||
var _b = __read(_a, 2), name = _b[0], templateCallback = _b[1]; | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
var directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
@@ -262,5 +319,6 @@ IF: ifDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
var renderDirective = function (props, directives) { | ||
var name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
var name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
@@ -303,3 +361,10 @@ }; | ||
var _d = _c.value, name_1 = _d.name, value = _d.value; | ||
var directiveData = { compute: compute(value, { $el: el }), value: value }; | ||
var returnable = true; | ||
if (name_1.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name_1)) | ||
returnable = false; | ||
var directiveData = { compute: compute(value, { $el: el }, returnable), value: value }; | ||
if (name_1.startsWith(DIRECTIVE_PREFIX)) { | ||
@@ -333,3 +398,3 @@ directives[name_1.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
var value = _a.value; | ||
return Object.keys(state).some(function (key) { return keyPattern(key, false).test(value); }); | ||
return Object.keys(state).some(function (key) { return expressionPropRE(key, false).test(value); }); | ||
}); | ||
@@ -388,3 +453,3 @@ if (hasDirectives) | ||
} | ||
if (!strip || container.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
var compiledChildren = compile(container, state, components, strip, true); | ||
@@ -408,3 +473,3 @@ try { | ||
else { | ||
if (!strip || child.outerHTML.includes(" " + DIRECTIVE_PREFIX)) { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
var compiledChildren = compile(child, state, components, strip, true); | ||
@@ -435,28 +500,13 @@ var node = createVNode(child, state, compiledChildren); | ||
var flat = function (vdom) { | ||
var e_4, _a, e_5, _b; | ||
var e_4, _a; | ||
var flattenedVDom = __assign({}, vdom); | ||
flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
flattenedVDom.children = flattenedVDom.children.filter(function (child) { return typeof child === 'object' && child.props.type > 0; }); | ||
try { | ||
for (var _c = __values(vdom.children), _d = _c.next(); !_d.done; _d = _c.next()) { | ||
var child = _d.value; | ||
for (var _b = __values(vdom.children), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var child = _c.value; | ||
if (typeof child === 'string') | ||
continue; | ||
if (child.children.length > 0) { | ||
try { | ||
for (var _e = (e_5 = void 0, __values(flat(child).children)), _f = _e.next(); !_f.done; _f = _e.next()) { | ||
var nestedChild = _f.value; | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
} | ||
catch (e_5_1) { e_5 = { error: e_5_1 }; } | ||
finally { | ||
try { | ||
if (_f && !_f.done && (_b = _e.return)) _b.call(_e); | ||
} | ||
finally { if (e_5) throw e_5.error; } | ||
} | ||
flattenedVDom.children = __spread(flattenedVDom.children, flat({ children: child.children }).children); | ||
child.children = []; | ||
} | ||
@@ -468,3 +518,3 @@ } | ||
try { | ||
if (_d && !_d.done && (_a = _c.return)) _a.call(_c); | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
} | ||
@@ -519,3 +569,3 @@ finally { if (e_4) throw e_4.error; } | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
@@ -547,6 +597,8 @@ }, | ||
var needsInit = type === 1; | ||
var hasKey = keys.some(function (key) { return keyPattern(key).test(String(directives_1[name_1].value)); }); | ||
var hasKey = keys.some(function (key) { | ||
return expressionPropRE(key).test(String(directives_1[name_1].value)); | ||
}); | ||
var hasKeyInFunction = Object.keys(state).some(function (key) { | ||
var iterKeysInFunction = keys.some(function (k) { | ||
return keyPattern(k).test(String(state[key])); | ||
return expressionPropRE(k).test(String(state[key])); | ||
}); | ||
@@ -574,3 +626,3 @@ return typeof state[key] === 'function' && iterKeysInFunction; | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
patch(node, app, keys); | ||
}; | ||
@@ -665,12 +717,19 @@ try { | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest("[" + stateDirective + "]")) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
@@ -691,5 +750,31 @@ | ||
document.addEventListener('DOMContentLoaded', function () { return init(); }); | ||
document.addEventListener('turbolinks:load', function () { return init(); }); | ||
listen(function (el) { return init(el); }); | ||
var DOMReady = function () { | ||
return new Promise(function (resolve) { | ||
if (document.readyState === 'loading') { | ||
document.addEventListener('DOMContentLoaded', resolve); | ||
} | ||
else { | ||
resolve(); | ||
} | ||
}); | ||
}; | ||
var start = function () { return __awaiter(void 0, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
switch (_a.label) { | ||
case 0: return [4, DOMReady()]; | ||
case 1: | ||
_a.sent(); | ||
init(); | ||
document.addEventListener('turbolinks:load', function () { return init(); }); | ||
listen(function (el) { return init(el); }); | ||
return [2]; | ||
} | ||
}); | ||
}); }; | ||
if (window.__l) { | ||
window.__l(function () { return start(); }); | ||
} | ||
else { | ||
start(); | ||
} | ||
@@ -696,0 +781,0 @@ return Lucia; |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Lucia=e()}(this,(function(){"use strict";var t=function(){return(t=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var i in e=arguments[r])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function e(t){var e="function"==typeof Symbol&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function r(t,e){var r="function"==typeof Symbol&&t[Symbol.iterator];if(!r)return t;var n,i,o=r.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(t){i={error:t}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function n(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(r(arguments[e]));return t}var i,o="l-",a="%LUCIA_FIRST_RENDER%";!function(t){t["@"]="on",t[":"]="bind"}(i||(i={}));var s=/:|\./,l=function(t,e){return void 0===e&&(e=!0),new RegExp((e?"this\\.":"")+t+"\\b")};function u(t){try{var e=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,n([void 0],Object.keys(this.argsKV),[e])))).bind(t).apply(void 0,n(Object.values(this.argsKV)))}catch(t){console.warn('Lucia Error: "'+t+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var c,v=function(t,e,r){return void 0===r&&(r=!0),u.bind({expression:t,argsKV:{$el:e.$el},returnable:r})},f={BIND:function(t){var e=t.el,r=t.name,n=t.data,i=t.app;switch(r.split(":")[1]){case"class":var o=n.compute(i.state);if("string"==typeof o)return e.setAttribute("class",(e.className+" "+o).trim());if(o instanceof Array)return e.setAttribute("class",(e.className+" "+o.join(" ")).trim());var a=[];for(var s in o)o[s]&&a.push(s);return a.length>0?e.setAttribute("class",(e.className+" "+a.join(" ").trim()).trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class");case"style":var l=n.compute(i.state);for(var s in e.removeAttribute("style"),l)e.style[s]=l[s];break;default:var u=n.compute(i.state);if("object"==typeof u&&null!==u)for(var s in u)u[s]?e.setAttribute(s,u[s]):e.removeAttribute(s);else u?e.setAttribute(r.split(":")[1],u):e.removeAttribute(r.split(":")[1])}},JOIN:function(e){var n=e.el,i=e.data,o=e.app,a=r(i.value.split(/ as | by /),3),s=a[0],l=a[1],u=a[2],c=v(s,{$el:n})(o.state);n["text"===l?"innerText":"innerHTML"]=c.join(u||"");var f=N(t({},o.state));Object.entries(o.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];f.directive(n,i)})),Object.entries(o.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];f.component(n,i)})),f.mount(n)},HTML:function(e){var n,i=e.el,o=e.data,a=e.app;i.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var s=N(t({},a.state));Object.entries(a.directives||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.directive(n,i)})),Object.entries(a.components||{}).map((function(t){var e=r(t,2),n=e[0],i=e[1];s.component(n,i)})),s.mount(i)},IF:function(t){var e=t.el,r=t.data,n=t.app;r.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:function(t){var e=t.el,r=t.data,n=t.app,i=e,o=r.compute(n.state);i.value!==o&&(i.value=o),i.oninput=function(){var t,e="number"==typeof o&&!isNaN(i.value),a="boolean"==typeof o&&("true"===i.value||"false"===i.value),s=null==o&&("null"===i.value||"undefined"===i.value);t=e?"Number('"+i.value+"').toPrecision()":a?"Boolean('"+i.value+"')":s?"null"===i.value?null:void 0:"'"+i.value+"'",v(r.value+" = "+t,{$el:i},!1)(n.state)}},ON:function(t){var e=t.el,n=t.name,i=t.data,o=t.app,a=r(n.split("."),2),s=a[0],l=a[1],u=s.split(":")[1],c=l||null;e["on"+u]=function(t){"prevent"===c&&t.preventDefault(),"stop"===c&&t.stopPropagation(),i.compute(o.state)}},TEXT:function(t){var e,r=t.el,n=t.data,i=t.app;r.textContent=null!==(e=n.compute(i.state))&&void 0!==e?e:n.value}},p=function(t,e){e[t.name.split(s)[0].toUpperCase()](t)};!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(c||(c={}));var d=function(e,r,n){void 0===r&&(r=[]);var i=t({},null==n?void 0:n.attributes),o=t({},null==n?void 0:n.directives);return r=r instanceof Array?r:[r],i.className&&(i.className=i.className.trim()),{tag:e,children:r,props:{attributes:i,directives:o,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},y=function(t){var r,a,s={},l={};if(t.attributes)try{for(var u=e(n(t.attributes)),c=u.next();!c.done;c=u.next()){var f=c.value,p=f.name,d=f.value,y={compute:v(d,{$el:t}),value:d};p.startsWith(o)?l[p.slice(o.length)]=y:Object.keys(i).includes(p[0])?l[i[p[0]]+":"+p.slice(1)]=y:s[p]=d}}catch(t){r={error:t}}finally{try{c&&!c.done&&(a=u.return)&&a.call(u)}finally{if(r)throw r.error}}return{attributes:s,directives:l}},h=function(t,e,r){var n=y(t),i=n.attributes,o=n.directives,a=c.STATIC,s=Object.keys(o).length>0,u=Object.values(o).some((function(t){var r=t.value;return Object.keys(e).some((function(t){return l(t,!1).test(r)}))}));return s&&(a=c.NEEDS_PATCH),u&&(a=c.DYNAMIC),d(t.tagName.toLowerCase(),r,{attributes:i,directives:o,ref:a===c.STATIC||i.id?void 0:t,type:a})},m=function(t,n,i,o,a){var s,l,u,c,v,f,p;if(void 0===n&&(n={}),void 0===i&&(i={}),void 0===o&&(o=!1),void 0===a&&(a=!1),!t)throw new Error("Please provide a Element");var d=[],g=Array.prototype.slice.call(t.childNodes);try{for(var E=e(g),T=E.next();!T.done;T=E.next()){var A=T.value;switch(A.nodeType){case Node.TEXT_NODE:!o&&A.nodeValue&&d.push(A.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(i).includes(A.tagName)){var N=document.createElement("div"),x=i[A.tagName]({children:A.innerHTML,state:n});N.innerHTML=x;try{for(var O=(u=void 0,e(Object.entries(y(A).directives))),j=O.next();!j.done;j=O.next()){var w=r(j.value,2),C=w[0],S=w[1];null===(p=N.firstElementChild)||void 0===p||p.setAttribute("l-"+C,S.value)}}catch(t){u={error:t}}finally{try{j&&!j.done&&(c=O.return)&&c.call(O)}finally{if(u)throw u.error}}if(!o||N.outerHTML.includes(" l-")){var L=m(N,n,i,o,!0);try{for(var _=(v=void 0,e(L)),k=_.next();!k.done;k=_.next()){var D=k.value;d.push(D)}}catch(t){v={error:t}}finally{try{k&&!k.done&&(f=_.return)&&f.call(_)}finally{if(v)throw v.error}}}t.replaceChild(N.firstElementChild,A)}else if(!o||A.outerHTML.includes(" l-")){L=m(A,n,i,o,!0);var I=h(A,n,L);d.push(I)}}}}catch(t){s={error:t}}finally{try{T&&!T.done&&(l=E.return)&&l.call(E)}finally{if(s)throw s.error}}if(a)return d;var H=h(t,n,d);return o?b(H):H},b=function(r){var n,i,o,a,s=t({},r);s.children.filter((function(t){return"object"==typeof t&&t.props.type>0}));try{for(var l=e(r.children),u=l.next();!u.done;u=l.next()){var c=u.value;if("string"!=typeof c&&c.children.length>0)try{for(var v=(o=void 0,e(b(c).children)),f=v.next();!f.done;f=v.next()){var p=f.value;"string"!=typeof p&&(0!==p.props.type&&s.children.push(p))}}catch(t){o={error:t}}finally{try{f&&!f.done&&(a=v.return)&&a.call(v)}finally{if(o)throw o.error}}}}catch(t){n={error:t}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}return s},g=function(t,e,r,n,i){if(void 0===i&&(i=!1),"length"===e){var o=Object.keys(r).filter((function(e){return r[e]instanceof Array&&(n=t,i=r[e],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every((function(t,e){return t===i[e]})));var n,i}));return 0!==o.length&&n(o),!0}return i&&n([e]),!1},E=function(t,e){var r={get:function(t,e){return"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],r):t[e]},set:function(r,n,i){var o=r[n]!==i;return o&&(r[n]=i),g(r,n,t,e,o),!0},deleteProperty:function(r,n){return delete r[n],g(r,n,t,e),!0}};return new Proxy(t,r)},T=function(r,n,i){var o,s;void 0===n&&(n={});var u=!1,v=n.state||{};if(r){i||(i=Object.keys(v)),i[0]===a&&(u=!0);var f=function(e){if("string"==typeof e)return"continue";if(e.props.type>c.STATIC){var r=e.props,o=r.attributes,a=r.directives,s=r.ref,f=r.type,d=[];if(!u){var y=function(t){var e=1===f,r=i.some((function(e){return l(e).test(String(a[t].value))})),n=Object.keys(v).some((function(t){var e=i.some((function(e){return l(e).test(String(v[t]))}));return"function"==typeof v[t]&&e}));(e||r||n)&&d.push(t)};for(var h in a)y(h)}e.props.type=f===c.NEEDS_PATCH?c.STATIC:f,(u?Object.keys(a):d).map((function(e){var r=a[e],i=o.id?document.getElementById(o.id):s;p({el:i,name:e,data:r,app:n},t({},n.directives))}))}e.children.length>0&&T(e,v,i)};try{for(var d=e(r.children),y=d.next();!y.done;y=d.next()){f(y.value)}}catch(t){o={error:t}}finally{try{y&&!y.done&&(s=d.return)&&s.call(d)}finally{if(o)throw o.error}}}},A=function(){function e(t,e){void 0===t&&(t={}),this.state=t,this.directives={},this.components={},this.mountHook=e}return e.prototype.mount=function(e,r){void 0===r&&(r=!1);var n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),r||(this.state=E(this.state,this.patch.bind(this)),this.directives=t(t({},this.directives),f)),this.patch([a]),this.mountHook&&this.mountHook(this.state),this.state},e.prototype.component=function(t,e){this.components[t.toUpperCase()]=e},e.prototype.directive=function(t,e){this.directives[t.toUpperCase()]=e},e.prototype.patch=function(t){var e={state:this.state,directives:this.directives,components:this.components};T(this.vdom,e,t)},e.prototype.compile=function(t){return m(t,this.state,this.components,!0)},e}(),N=function(t,e){return new A(t,e)},x="l-state",O=function(t){void 0===t&&(t=document),n(t.querySelectorAll("[l-state]")).filter((function(t){return void 0===t.__l})).map((function(t){var e=t.getAttribute(x);try{var r=new Function("return "+e)(),n=N(r);n.mount(t),t.__l=n}catch(r){console.warn('Lucia Error: "'+r+'"\n\nExpression: "'+e+'"\nElement:',t)}}))},j=function(t,e,r){void 0===e&&(e=document);var n=new MutationObserver((function(i){i.map((function(e){e.addedNodes.length>0&&e.addedNodes.forEach((function(e){1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||t(e.parentElement))}))})),n.observe(e,r||{childList:!0,attributes:!0,subtree:!0})}))},w=Object.freeze({__proto__:null,createApp:N,h:d,compile:m,patch:T,reactive:E,directives:f,renderDirective:p,init:O,listen:j});return document.addEventListener("DOMContentLoaded",(function(){return O()})),document.addEventListener("turbolinks:load",(function(){return O()})),j((function(t){return O(t)})),w})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Lucia=t()}(this,(function(){"use strict";var e=function(){return(e=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n])Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e}).apply(this,arguments)};function t(e,t,n,r){return new(n||(n=Promise))((function(i,o){function a(e){try{u(r.next(e))}catch(e){o(e)}}function l(e){try{u(r.throw(e))}catch(e){o(e)}}function u(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,l)}u((r=r.apply(e,t||[])).next())}))}function n(e,t){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:l(0),throw:l(1),return:l(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function l(o){return function(l){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=a.trys,(i=i.length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){a.label=o[1];break}if(6===o[0]&&a.label<i[1]){a.label=i[1],i=o;break}if(i&&a.label<i[2]){a.label=i[2],a.ops.push(o);break}i[2]&&a.ops.pop(),a.trys.pop();continue}o=t.call(e,a)}catch(e){o=[6,e],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,l])}}}function r(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function i(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,o=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function o(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(i(arguments[t]));return e}var a,l="l-",u="%LUCIA_FIRST_RENDER%";!function(e){e["@"]="on",e[":"]="bind"}(a||(a={}));var s=function(){return new RegExp("(l-|"+Object.keys(a).join("|")+")\\w+","gim")},c=function(e,t){return void 0===t&&(t=!0),new RegExp((t?"this\\.":"")+e+"\\b")};function f(e){try{var t=this.returnable?"return "+this.expression:this.expression;return(new(Function.bind.apply(Function,o([void 0],Object.keys(this.argsKV),[t])))).bind(e).apply(void 0,o(Object.values(this.argsKV)))}catch(e){console.warn('Lucia Error: "'+e+'"\n\nExpression: "'+this.expression+'"\nElement:',this.argsKV.$el)}}var v,p=function(e,t,n){return void 0===n&&(n=!0),f.bind({expression:e,argsKV:{$el:t.$el},returnable:n})},d={BIND:function(e){var t=e.el,n=e.name,r=e.data,i=e.app;switch(n.split(":")[1]){case"class":var o=r.compute(i.state);if("string"==typeof o)return t.setAttribute("class",(t.className+" "+o).trim());if(o instanceof Array)return t.setAttribute("class",(t.className+" "+o.join(" ")).trim());var a=[];for(var l in o)o[l]&&a.push(l);return a.length>0?t.setAttribute("class",(t.className+" "+a.join(" ").trim()).trim()):t.className.trim().length>0?t.setAttribute("class",t.className):t.removeAttribute("class");case"style":var u=r.compute(i.state);for(var l in t.removeAttribute("style"),u)t.style[l]=u[l];break;default:var s=r.compute(i.state);if("object"==typeof s&&null!==s)for(var l in s)s[l]?t.setAttribute(l,s[l]):t.removeAttribute(l);else s?t.setAttribute(n.split(":")[1],s):t.removeAttribute(n.split(":")[1])}},HTML:function(t){var n,r=t.el,o=t.data,a=t.app;r.innerHTML=null!==(n=o.compute(a.state))&&void 0!==n?n:o.value;var l=N(e({},a.state));Object.entries(a.directives||{}).map((function(e){var t=i(e,2),n=t[0],r=t[1];l.directive(n,r)})),Object.entries(a.components||{}).map((function(e){var t=i(e,2),n=t[0],r=t[1];l.component(n,r)})),l.mount(r)},IF:function(e){var t=e.el,n=e.data,r=e.app;n.compute(r.state)?t.style.removeProperty("display"):t.style.display="none"},MODEL:function(e){var t=e.el,n=e.data,r=e.app,i=t,o=n.compute(r.state);i.value!==o&&(i.value=o),i.oninput=function(){return function(e,t,n,r){var i,o="number"==typeof t&&!isNaN(e.value),a="boolean"==typeof t&&("true"===e.value||"false"===e.value),l=null==t&&("null"===e.value||"undefined"===e.value);return i=o?"Number('"+e.value+"').toPrecision()":a?"Boolean('"+e.value+"')":l?"null"===e.value?null:void 0:"'"+e.value+"'",p(n.value+" = "+i,{$el:e},!1)(r.state),i}(i,o,n,r)}},ON:function(e){var t=e.el,n=e.name,r=e.data,o=e.app,a=i(n.split("."),2),l=a[0],u=a[1],s=l.split(":")[1],c=u||null;t["on"+s]=function(e){"prevent"===c&&e.preventDefault(),"stop"===c&&e.stopPropagation(),r.compute(o.state)}},TEXT:function(e){var t,n=e.el,r=e.data,i=e.app;n.textContent=null!==(t=r.compute(i.state))&&void 0!==t?t:r.value},FOR:function(t){var n=t.el,r=t.data,o=t.app,a=i(r.value.split(/ +in +/g),2),l=a[0],u=a[1],s=i(l.split(","),2),c=s[0],f=s[1],v=p(u,{$el:n})(o.state),d=String(n.__l_for);if(d){for(var h="",y=0;y<v.length;y++){var m=d;c&&(m=m.replace(new RegExp("this."+c.trim(),"g"),u+"["+y+"]")),f&&(m=m.replace(new RegExp("this."+f.trim(),"g"),String(y))),h+=m}n.innerHTML=h}else n.innerHTML=v.join("");var b=N(e({},o.state));Object.entries(o.directives||{}).map((function(e){var t=i(e,2),n=t[0],r=t[1];b.directive(n,r)})),Object.entries(o.components||{}).map((function(e){var t=i(e,2),n=t[0],r=t[1];b.component(n,r)})),b.mount(n)}},h=function(e,t){t[e.name.split(/:|\./)[0].toUpperCase()](e)};!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(v||(v={}));var y=function(t,n,r){void 0===n&&(n=[]);var i=e({},null==r?void 0:r.attributes),o=e({},null==r?void 0:r.directives);return n=n instanceof Array?n:[n],i.className&&(i.className=i.className.trim()),{tag:t,children:n,props:{attributes:i,directives:o,ref:(null==r?void 0:r.ref)||void 0,type:(null==r?void 0:r.type)||0}}},m=function(e){var t,n,i={},u={};if(e.attributes)try{for(var s=r(o(e.attributes)),c=s.next();!c.done;c=s.next()){var f=c.value,v=f.name,d=f.value,h=!0;v.includes("for")&&void 0===e.__l_for&&(e.__l_for=String(e.innerHTML).trim(),h=!1),/on|@/.test(v)&&(h=!1);var y={compute:p(d,{$el:e},h),value:d};v.startsWith(l)?u[v.slice(l.length)]=y:Object.keys(a).includes(v[0])?u[a[v[0]]+":"+v.slice(1)]=y:i[v]=d}}catch(e){t={error:e}}finally{try{c&&!c.done&&(n=s.return)&&n.call(s)}finally{if(t)throw t.error}}return{attributes:i,directives:u}},b=function(e,t,n){var r=m(e),i=r.attributes,o=r.directives,a=v.STATIC,l=Object.keys(o).length>0,u=Object.values(o).some((function(e){var n=e.value;return Object.keys(t).some((function(e){return c(e,!1).test(n)}))}));return l&&(a=v.NEEDS_PATCH),u&&(a=v.DYNAMIC),y(e.tagName.toLowerCase(),n,{attributes:i,directives:o,ref:a===v.STATIC||i.id?void 0:e,type:a})},g=function(e,t,n,o,a){var l,u,c,f,v,p,d;if(void 0===t&&(t={}),void 0===n&&(n={}),void 0===o&&(o=!1),void 0===a&&(a=!1),!e)throw new Error("Please provide a Element");var h=[],y=Array.prototype.slice.call(e.childNodes);try{for(var w=r(y),T=w.next();!T.done;T=w.next()){var A=T.value;switch(A.nodeType){case Node.TEXT_NODE:!o&&A.nodeValue&&h.push(A.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(n).includes(A.tagName)){var x=document.createElement("div"),N=n[A.tagName]({children:A.innerHTML,state:t});x.innerHTML=N;try{for(var j=(c=void 0,r(Object.entries(m(A).directives))),O=j.next();!O.done;O=j.next()){var _=i(O.value,2),S=_[0],C=_[1];null===(d=x.firstElementChild)||void 0===d||d.setAttribute("l-"+S,C.value)}}catch(e){c={error:e}}finally{try{O&&!O.done&&(f=j.return)&&f.call(j)}finally{if(c)throw c.error}}if(!o||s().test(x.outerHTML)){var k=g(x,t,n,o,!0);try{for(var L=(v=void 0,r(k)),H=L.next();!H.done;H=L.next()){var M=H.value;h.push(M)}}catch(e){v={error:e}}finally{try{H&&!H.done&&(p=L.return)&&p.call(L)}finally{if(v)throw v.error}}}e.replaceChild(x.firstElementChild,A)}else if(!o||s().test(A.outerHTML)){k=g(A,t,n,o,!0);var D=b(A,t,k);h.push(D)}}}}catch(e){l={error:e}}finally{try{T&&!T.done&&(u=w.return)&&u.call(w)}finally{if(l)throw l.error}}if(a)return h;var I=b(e,t,h);return o?E(I):I},E=function(t){var n,i,a=e({},t);a.children=a.children.filter((function(e){return"object"==typeof e&&e.props.type>0}));try{for(var l=r(t.children),u=l.next();!u.done;u=l.next()){var s=u.value;"string"!=typeof s&&(s.children.length>0&&(a.children=o(a.children,E({children:s.children}).children),s.children=[]))}}catch(e){n={error:e}}finally{try{u&&!u.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}return a},w=function(e,t,n,r,i){if(void 0===i&&(i=!1),"length"===t){var o=Object.keys(n).filter((function(t){return n[t]instanceof Array&&(r=e,i=n[t],r instanceof Array&&i instanceof Array&&r.length===i.length&&r.every((function(e,t){return e===i[t]})));var r,i}));return 0!==o.length&&r(o),!0}return i&&r([t]),!1},T=function(e,t){var n={get:function(e,t){return"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],n):e[t]},set:function(n,r,i){var o=n[r]!==i;return o&&(n[r]=i),w(n,r,e,t,o),!0},deleteProperty:function(n,r){return delete n[r],w(n,r,e,t,!0),!0}};return new Proxy(e,n)},A=function(t,n,i){var o,a;void 0===n&&(n={});var l=!1,s=n.state||{};if(t){i||(i=Object.keys(s)),i[0]===u&&(l=!0);var f=function(t){if("string"==typeof t)return"continue";if(t.props.type>v.STATIC){var r=t.props,o=r.attributes,a=r.directives,u=r.ref,f=r.type,p=[];if(!l){var d=function(e){var t=1===f,n=i.some((function(t){return c(t).test(String(a[e].value))})),r=Object.keys(s).some((function(e){var t=i.some((function(t){return c(t).test(String(s[e]))}));return"function"==typeof s[e]&&t}));(t||n||r)&&p.push(e)};for(var y in a)d(y)}t.props.type=f===v.NEEDS_PATCH?v.STATIC:f,(l?Object.keys(a):p).map((function(t){var r=a[t],i=o.id?document.getElementById(o.id):u;h({el:i,name:t,data:r,app:n},e({},n.directives))}))}t.children.length>0&&A(t,n,i)};try{for(var p=r(t.children),d=p.next();!d.done;d=p.next()){f(d.value)}}catch(e){o={error:e}}finally{try{d&&!d.done&&(a=p.return)&&a.call(p)}finally{if(o)throw o.error}}}},x=function(){function t(e,t){void 0===e&&(e={}),this.state=e,this.directives={},this.components={},this.mountHook=t}return t.prototype.mount=function(t,n){void 0===n&&(n=!1);var r="string"==typeof t?document.querySelector(t):t;return this.vdom=this.compile(r),n||(this.state=T(this.state,this.patch.bind(this)),this.directives=e(e({},this.directives),d)),this.patch([u]),this.mountHook&&this.mountHook(this.state),this.state},t.prototype.component=function(e,t){this.components[e.toUpperCase()]=t},t.prototype.directive=function(e,t){this.directives[e.toUpperCase()]=t},t.prototype.patch=function(e){var t={state:this.state,directives:this.directives,components:this.components};A(this.vdom,t,e)},t.prototype.compile=function(e){return g(e,this.state,this.components,!0)},t}(),N=function(e,t){return new x(e,t)},j="l-state",O=function(e){void 0===e&&(e=document),o(e.querySelectorAll("[l-state]")).filter((function(e){return void 0===e.__l})).map((function(e){var t=e.getAttribute(j);try{var n=new Function("return "+t)(),r=N(n);r.mount(e),e.__l=r}catch(n){console.warn('Lucia Error: "'+n+'"\n\nExpression: "'+t+'"\nElement:',e)}}))},_=function(e,t,n){void 0===t&&(t=document),new MutationObserver((function(t){t.map((function(t){if(t.addedNodes.length>0)t.addedNodes.forEach((function(t){1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||t.getAttribute(j)&&e(t.parentElement))}));else if("attributes"===t.type){if(t.target.parentElement&&t.target.parentElement.closest("[l-state]"))return;e(t.target.parentElement)}}))})).observe(t,n||{childList:!0,attributes:!0,subtree:!0})},S=Object.freeze({__proto__:null,createApp:N,h:y,compile:g,patch:A,reactive:T,directives:d,renderDirective:h,init:O,listen:_}),C=function(){return t(void 0,void 0,void 0,(function(){return n(this,(function(e){switch(e.label){case 0:return[4,new Promise((function(e){"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()}))];case 1:return e.sent(),O(),document.addEventListener("turbolinks:load",(function(){return O()})),_((function(e){return O(e)})),[2]}}))}))};return window.__l?window.__l((function(){return C()})):C(),S})); |
@@ -13,4 +13,5 @@ 'use strict'; | ||
const rawDirectiveSplitPattern = /:|\./; | ||
const keyPattern = (key, hasThis = true) => { | ||
const rawDirectiveSplitRE = () => /:|\./; | ||
const hasDirectiveRE = () => new RegExp(`(${DIRECTIVE_PREFIX}|${Object.keys(DIRECTIVE_SHORTHANDS).join('|')})\\w+`, 'gim'); | ||
const expressionPropRE = (key, hasThis = true) => { | ||
return new RegExp(`${hasThis ? 'this\\.' : ''}${key}\\b`); | ||
@@ -110,17 +111,26 @@ }; | ||
const joinDirective = ({ el, data, app }) => { | ||
const [array, contentType, delimiter] = data.value.split(/ as | by /); | ||
const hydratedArray = compute(array, { $el: el })(app.state); | ||
const accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
const inputCallback = (el, hydratedValue, data, app) => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
const modelDirective = ({ el: awaitingTypecastEl, data, app }) => { | ||
@@ -132,25 +142,3 @@ const el = awaitingTypecastEl; | ||
} | ||
el.oninput = () => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
}; | ||
el.oninput = () => inputCallback(el, hydratedValue, data, app); | ||
}; | ||
@@ -176,5 +164,34 @@ | ||
const forDirective = ({ el, data, app }) => { | ||
const [expression, target] = data.value.split(/ +in +/g); | ||
const [item, index] = expression.split(','); | ||
const hydratedArray = compute(target, { $el: el })(app.state); | ||
const template = String(el.__l_for); | ||
if (template) { | ||
let accumulator = ''; | ||
for (let i = 0; i < hydratedArray.length; i++) { | ||
let content = template; | ||
if (item) | ||
content = content.replace(new RegExp(`this.${item.trim()}`, 'g'), `${target}[${i}]`); | ||
if (index) | ||
content = content.replace(new RegExp(`this.${index.trim()}`, 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
const directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
@@ -185,5 +202,6 @@ IF: ifDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
const renderDirective = (props, directives) => { | ||
const name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
const name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
@@ -222,3 +240,10 @@ }; | ||
for (const { name, value } of [...el.attributes]) { | ||
const directiveData = { compute: compute(value, { $el: el }), value }; | ||
let returnable = true; | ||
if (name.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name)) | ||
returnable = false; | ||
const directiveData = { compute: compute(value, { $el: el }, returnable), value }; | ||
if (name.startsWith(DIRECTIVE_PREFIX)) { | ||
@@ -242,3 +267,3 @@ directives[name.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
const hasDirectives = Object.keys(directives).length > 0; | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => keyPattern(key, false).test(value))); | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => expressionPropRE(key, false).test(value))); | ||
if (hasDirectives) | ||
@@ -279,3 +304,3 @@ type = VNodeTypes.NEEDS_PATCH; | ||
} | ||
if (!strip || container.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
const compiledChildren = compile(container, state, components, strip, true); | ||
@@ -289,3 +314,3 @@ for (const componentChild of compiledChildren) { | ||
else { | ||
if (!strip || child.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
const compiledChildren = compile(child, state, components, strip, true); | ||
@@ -309,3 +334,3 @@ const node = createVNode(child, state, compiledChildren); | ||
const flattenedVDom = Object.assign({}, vdom); | ||
flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
flattenedVDom.children = flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
for (const child of vdom.children) { | ||
@@ -315,9 +340,7 @@ if (typeof child === 'string') | ||
if (child.children.length > 0) { | ||
for (const nestedChild of flat(child).children) { | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
flattenedVDom.children = [ | ||
...flattenedVDom.children, | ||
...flat({ children: child.children }).children, | ||
]; | ||
child.children = []; | ||
} | ||
@@ -370,3 +393,3 @@ } | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
@@ -396,5 +419,5 @@ }, | ||
const needsInit = type === 1; | ||
const hasKey = keys.some((key) => keyPattern(key).test(String(directives[name].value))); | ||
const hasKey = keys.some((key) => expressionPropRE(key).test(String(directives[name].value))); | ||
const hasKeyInFunction = Object.keys(state).some((key) => { | ||
const iterKeysInFunction = keys.some((k) => keyPattern(k).test(String(state[key]))); | ||
const iterKeysInFunction = keys.some((k) => expressionPropRE(k).test(String(state[key]))); | ||
return typeof state[key] === 'function' && iterKeysInFunction; | ||
@@ -418,3 +441,3 @@ }); | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
patch(node, app, keys); | ||
} | ||
@@ -491,12 +514,19 @@ }; | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest(`[${stateDirective}]`)) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
@@ -503,0 +533,0 @@ |
@@ -1,1 +0,1 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e;!function(e){e["@"]="on",e[":"]="bind"}(e||(e={}));const t=/:|\./,s=(e,t=!0)=>new RegExp(`${t?"this\\.":""}${e}\\b`);function n(e){try{const t=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),t).bind(e)(...Object.values(this.argsKV))}catch(e){console.warn(`Lucia Error: "${e}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const r=(e,t,s=!0)=>n.bind({expression:e,argsKV:{$el:t.$el},returnable:s}),o={BIND:({el:e,name:t,data:s,app:n})=>{switch(t.split(":")[1]){case"class":const r=s.compute(n.state);if("string"==typeof r)return e.setAttribute("class",`${e.className} ${r}`.trim());if(r instanceof Array)return e.setAttribute("class",`${e.className} ${r.join(" ")}`.trim());{const t=[];for(const e in r)r[e]&&t.push(e);return t.length>0?e.setAttribute("class",`${e.className} ${t.join(" ").trim()}`.trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class")}case"style":const o=s.compute(n.state);e.removeAttribute("style");for(const t in o)e.style[t]=o[t];break;default:const i=s.compute(n.state);if("object"==typeof i&&null!==i)for(const t in i)i[t]?e.setAttribute(t,i[t]):e.removeAttribute(t);else i?e.setAttribute(t.split(":")[1],i):e.removeAttribute(t.split(":")[1])}},JOIN:({el:e,data:t,app:s})=>{const[n,o,i]=t.value.split(/ as | by /),a=r(n,{$el:e})(s.state);e["text"===o?"innerText":"innerHTML"]=a.join(i||"");const c=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{c.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{c.component(e,t)})),c.mount(e)},HTML:({el:e,data:t,app:s})=>{var n;e.innerHTML=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value;const r=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{r.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{r.component(e,t)})),r.mount(e)},IF:({el:e,data:t,app:s})=>{t.compute(s.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:({el:e,data:t,app:s})=>{const n=e,o=t.compute(s.state);n.value!==o&&(n.value=o),n.oninput=()=>{const e="number"==typeof o&&!isNaN(n.value),i="boolean"==typeof o&&("true"===n.value||"false"===n.value),a=null==o&&("null"===n.value||"undefined"===n.value);let c;c=e?`Number('${n.value}').toPrecision()`:i?`Boolean('${n.value}')`:a?"null"===n.value?null:void 0:`'${n.value}'`,r(`${t.value} = ${c}`,{$el:n},!1)(s.state)}},ON:({el:e,name:t,data:s,app:n})=>{const[r,o]=t.split("."),i=r.split(":")[1],a=o||null;e[`on${i}`]=e=>{"prevent"===a&&e.preventDefault(),"stop"===a&&e.stopPropagation(),s.compute(n.state)}},TEXT:({el:e,data:t,app:s})=>{var n;e.textContent=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value}},i=(e,s)=>{s[e.name.split(t)[0].toUpperCase()](e)};var a;!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(a||(a={}));const c=(e,t=[],s)=>{const n=Object.assign({},null==s?void 0:s.attributes),r=Object.assign({},null==s?void 0:s.directives);return t=t instanceof Array?t:[t],n.className&&(n.className=n.className.trim()),{tag:e,children:t,props:{attributes:n,directives:r,ref:(null==s?void 0:s.ref)||void 0,type:(null==s?void 0:s.type)||0}}},l=t=>{const s={},n={};if(t.attributes)for(const{name:o,value:i}of[...t.attributes]){const a={compute:r(i,{$el:t}),value:i};o.startsWith("l-")?n[o.slice("l-".length)]=a:Object.keys(e).includes(o[0])?n[`${e[o[0]]}:${o.slice(1)}`]=a:s[o]=i}return{attributes:s,directives:n}},p=(e,t,n)=>{const{attributes:r,directives:o}=l(e);let i=a.STATIC;const p=Object.keys(o).length>0,u=Object.values(o).some((({value:e})=>Object.keys(t).some((t=>s(t,!1).test(e)))));return p&&(i=a.NEEDS_PATCH),u&&(i=a.DYNAMIC),c(e.tagName.toLowerCase(),n,{attributes:r,directives:o,ref:i===a.STATIC||r.id?void 0:e,type:i})},u=(e,t={},s={},n=!1,r=!1)=>{var o;if(!e)throw new Error("Please provide a Element");const i=[],a=Array.prototype.slice.call(e.childNodes);for(const r of a)switch(r.nodeType){case Node.TEXT_NODE:!n&&r.nodeValue&&i.push(r.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(s).includes(r.tagName)){const a=document.createElement("div"),c=s[r.tagName]({children:r.innerHTML,state:t});a.innerHTML=c;for(const[e,t]of Object.entries(l(r).directives))null===(o=a.firstElementChild)||void 0===o||o.setAttribute(`l-${e}`,t.value);if(!n||a.outerHTML.includes(" l-")){const e=u(a,t,s,n,!0);for(const t of e)i.push(t)}e.replaceChild(a.firstElementChild,r)}else if(!n||r.outerHTML.includes(" l-")){const e=u(r,t,s,n,!0),o=p(r,t,e);i.push(o)}}if(r)return i;{let s=p(e,t,i);return n?d(s):s}},d=e=>{const t=Object.assign({},e);t.children.filter((e=>"object"==typeof e&&e.props.type>0));for(const s of e.children)if("string"!=typeof s&&s.children.length>0)for(const e of d(s).children)"string"!=typeof e&&0!==e.props.type&&t.children.push(e);return t},m=(e,t,s,n,r=!1)=>{if("length"===t){const t=Object.keys(s).filter((t=>{return s[t]instanceof Array&&(n=e,r=s[t],n instanceof Array&&r instanceof Array&&n.length===r.length&&n.every(((e,t)=>e===r[t])));var n,r}));return 0!==t.length&&n(t),!0}return r&&n([t]),!1},h=(e,t)=>{const s={get:(e,t)=>"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],s):e[t],set(s,n,r){const o=s[n]!==r;return o&&(s[n]=r),m(s,n,e,t,o),!0},deleteProperty:(s,n)=>(delete s[n],m(s,n,e,t),!0)};return new Proxy(e,s)},v=(e,t={},n)=>{let r=!1;const o=t.state||{};if(e){n||(n=Object.keys(o)),"%LUCIA_FIRST_RENDER%"===n[0]&&(r=!0);for(let c of e.children)if("string"!=typeof c){if(c.props.type>a.STATIC){const{attributes:e,directives:l,ref:p,type:u}=c.props;let d=[];if(!r)for(const e in l){const t=1===u,r=n.some((t=>s(t).test(String(l[e].value)))),i=Object.keys(o).some((e=>{const t=n.some((t=>s(t).test(String(o[e]))));return"function"==typeof o[e]&&t}));(t||r||i)&&d.push(e)}c.props.type=u===a.NEEDS_PATCH?a.STATIC:u;(r?Object.keys(l):d).map((s=>{const n=l[s],r=e.id?document.getElementById(e.id):p;i({el:r,name:s,data:n,app:t},Object.assign({},t.directives))}))}c.children.length>0&&v(c,o,n)}}};class f{constructor(e={},t){this.state=e,this.directives={},this.components={},this.mountHook=t}mount(e,t=!1){const s="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(s),t||(this.state=h(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),o)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state}component(e,t){this.components[e.toUpperCase()]=t}directive(e,t){this.directives[e.toUpperCase()]=t}patch(e){const t={state:this.state,directives:this.directives,components:this.components};v(this.vdom,t,e)}compile(e){return u(e,this.state,this.components,!0)}}const b=(e,t)=>new f(e,t);exports.compile=u,exports.createApp=b,exports.directives=o,exports.h=c,exports.init=(e=document)=>{[...e.querySelectorAll("[l-state]")].filter((e=>void 0===e.__l)).map((e=>{const t=e.getAttribute("l-state");try{const s=new Function(`return ${t}`)(),n=b(s);n.mount(e),e.__l=n}catch(s){console.warn(`Lucia Error: "${s}"\n\nExpression: "${t}"\nElement:`,e)}}))},exports.listen=(e,t=document,s)=>{const n=new MutationObserver((r=>{r.map((t=>{t.addedNodes.length>0&&t.addedNodes.forEach((t=>{1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||e(t.parentElement))}))})),n.observe(t,s||{childList:!0,attributes:!0,subtree:!0})}))},exports.patch=v,exports.reactive=h,exports.renderDirective=i; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e;!function(e){e["@"]="on",e[":"]="bind"}(e||(e={}));const t=()=>new RegExp(`(l-|${Object.keys(e).join("|")})\\w+`,"gim"),s=(e,t=!0)=>new RegExp(`${t?"this\\.":""}${e}\\b`);function n(e){try{const t=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),t).bind(e)(...Object.values(this.argsKV))}catch(e){console.warn(`Lucia Error: "${e}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const r=(e,t,s=!0)=>n.bind({expression:e,argsKV:{$el:t.$el},returnable:s}),i={BIND:({el:e,name:t,data:s,app:n})=>{switch(t.split(":")[1]){case"class":const r=s.compute(n.state);if("string"==typeof r)return e.setAttribute("class",`${e.className} ${r}`.trim());if(r instanceof Array)return e.setAttribute("class",`${e.className} ${r.join(" ")}`.trim());{const t=[];for(const e in r)r[e]&&t.push(e);return t.length>0?e.setAttribute("class",`${e.className} ${t.join(" ").trim()}`.trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class")}case"style":const i=s.compute(n.state);e.removeAttribute("style");for(const t in i)e.style[t]=i[t];break;default:const o=s.compute(n.state);if("object"==typeof o&&null!==o)for(const t in o)o[t]?e.setAttribute(t,o[t]):e.removeAttribute(t);else o?e.setAttribute(t.split(":")[1],o):e.removeAttribute(t.split(":")[1])}},HTML:({el:e,data:t,app:s})=>{var n;e.innerHTML=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value;const r=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{r.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{r.component(e,t)})),r.mount(e)},IF:({el:e,data:t,app:s})=>{t.compute(s.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:({el:e,data:t,app:s})=>{const n=e,i=t.compute(s.state);n.value!==i&&(n.value=i),n.oninput=()=>((e,t,s,n)=>{const i="number"==typeof t&&!isNaN(e.value),o="boolean"==typeof t&&("true"===e.value||"false"===e.value),a=null==t&&("null"===e.value||"undefined"===e.value);let l;return l=i?`Number('${e.value}').toPrecision()`:o?`Boolean('${e.value}')`:a?"null"===e.value?null:void 0:`'${e.value}'`,r(`${s.value} = ${l}`,{$el:e},!1)(n.state),l})(n,i,t,s)},ON:({el:e,name:t,data:s,app:n})=>{const[r,i]=t.split("."),o=r.split(":")[1],a=i||null;e[`on${o}`]=e=>{"prevent"===a&&e.preventDefault(),"stop"===a&&e.stopPropagation(),s.compute(n.state)}},TEXT:({el:e,data:t,app:s})=>{var n;e.textContent=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value},FOR:({el:e,data:t,app:s})=>{const[n,i]=t.value.split(/ +in +/g),[o,a]=n.split(","),l=r(i,{$el:e})(s.state),c=String(e.__l_for);if(c){let t="";for(let e=0;e<l.length;e++){let s=c;o&&(s=s.replace(new RegExp(`this.${o.trim()}`,"g"),`${i}[${e}]`)),a&&(s=s.replace(new RegExp(`this.${a.trim()}`,"g"),String(e))),t+=s}e.innerHTML=t}else e.innerHTML=l.join("");const p=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{p.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{p.component(e,t)})),p.mount(e)}},o=(e,t)=>{t[e.name.split(/:|\./)[0].toUpperCase()](e)};var a;!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(a||(a={}));const l=(e,t=[],s)=>{const n=Object.assign({},null==s?void 0:s.attributes),r=Object.assign({},null==s?void 0:s.directives);return t=t instanceof Array?t:[t],n.className&&(n.className=n.className.trim()),{tag:e,children:t,props:{attributes:n,directives:r,ref:(null==s?void 0:s.ref)||void 0,type:(null==s?void 0:s.type)||0}}},c=t=>{const s={},n={};if(t.attributes)for(const{name:i,value:o}of[...t.attributes]){let a=!0;i.includes("for")&&void 0===t.__l_for&&(t.__l_for=String(t.innerHTML).trim(),a=!1),/on|@/.test(i)&&(a=!1);const l={compute:r(o,{$el:t},a),value:o};i.startsWith("l-")?n[i.slice("l-".length)]=l:Object.keys(e).includes(i[0])?n[`${e[i[0]]}:${i.slice(1)}`]=l:s[i]=o}return{attributes:s,directives:n}},p=(e,t,n)=>{const{attributes:r,directives:i}=c(e);let o=a.STATIC;const p=Object.keys(i).length>0,u=Object.values(i).some((({value:e})=>Object.keys(t).some((t=>s(t,!1).test(e)))));return p&&(o=a.NEEDS_PATCH),u&&(o=a.DYNAMIC),l(e.tagName.toLowerCase(),n,{attributes:r,directives:i,ref:o===a.STATIC||r.id?void 0:e,type:o})},u=(e,s={},n={},r=!1,i=!1)=>{var o;if(!e)throw new Error("Please provide a Element");const a=[],l=Array.prototype.slice.call(e.childNodes);for(const i of l)switch(i.nodeType){case Node.TEXT_NODE:!r&&i.nodeValue&&a.push(i.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(n).includes(i.tagName)){const l=document.createElement("div"),p=n[i.tagName]({children:i.innerHTML,state:s});l.innerHTML=p;for(const[e,t]of Object.entries(c(i).directives))null===(o=l.firstElementChild)||void 0===o||o.setAttribute(`l-${e}`,t.value);if(!r||t().test(l.outerHTML)){const e=u(l,s,n,r,!0);for(const t of e)a.push(t)}e.replaceChild(l.firstElementChild,i)}else if(!r||t().test(i.outerHTML)){const e=u(i,s,n,r,!0),t=p(i,s,e);a.push(t)}}if(i)return a;{let t=p(e,s,a);return r?d(t):t}},d=e=>{const t=Object.assign({},e);t.children=t.children.filter((e=>"object"==typeof e&&e.props.type>0));for(const s of e.children)"string"!=typeof s&&s.children.length>0&&(t.children=[...t.children,...d({children:s.children}).children],s.children=[]);return t},m=(e,t,s,n,r=!1)=>{if("length"===t){const t=Object.keys(s).filter((t=>{return s[t]instanceof Array&&(n=e,r=s[t],n instanceof Array&&r instanceof Array&&n.length===r.length&&n.every(((e,t)=>e===r[t])));var n,r}));return 0!==t.length&&n(t),!0}return r&&n([t]),!1},h=(e,t)=>{const s={get:(e,t)=>"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],s):e[t],set(s,n,r){const i=s[n]!==r;return i&&(s[n]=r),m(s,n,e,t,i),!0},deleteProperty:(s,n)=>(delete s[n],m(s,n,e,t,!0),!0)};return new Proxy(e,s)},v=(e,t={},n)=>{let r=!1;const i=t.state||{};if(e){n||(n=Object.keys(i)),"%LUCIA_FIRST_RENDER%"===n[0]&&(r=!0);for(let l of e.children)if("string"!=typeof l){if(l.props.type>a.STATIC){const{attributes:e,directives:c,ref:p,type:u}=l.props;let d=[];if(!r)for(const e in c){const t=1===u,r=n.some((t=>s(t).test(String(c[e].value)))),o=Object.keys(i).some((e=>{const t=n.some((t=>s(t).test(String(i[e]))));return"function"==typeof i[e]&&t}));(t||r||o)&&d.push(e)}l.props.type=u===a.NEEDS_PATCH?a.STATIC:u;(r?Object.keys(c):d).map((s=>{const n=c[s],r=e.id?document.getElementById(e.id):p;o({el:r,name:s,data:n,app:t},Object.assign({},t.directives))}))}l.children.length>0&&v(l,t,n)}}};class f{constructor(e={},t){this.state=e,this.directives={},this.components={},this.mountHook=t}mount(e,t=!1){const s="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(s),t||(this.state=h(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),i)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state}component(e,t){this.components[e.toUpperCase()]=t}directive(e,t){this.directives[e.toUpperCase()]=t}patch(e){const t={state:this.state,directives:this.directives,components:this.components};v(this.vdom,t,e)}compile(e){return u(e,this.state,this.components,!0)}}const b=(e,t)=>new f(e,t);exports.compile=u,exports.createApp=b,exports.directives=i,exports.h=l,exports.init=(e=document)=>{[...e.querySelectorAll("[l-state]")].filter((e=>void 0===e.__l)).map((e=>{const t=e.getAttribute("l-state");try{const s=new Function(`return ${t}`)(),n=b(s);n.mount(e),e.__l=n}catch(s){console.warn(`Lucia Error: "${s}"\n\nExpression: "${t}"\nElement:`,e)}}))},exports.listen=(e,t=document,s)=>{new MutationObserver((t=>{t.map((t=>{if(t.addedNodes.length>0)t.addedNodes.forEach((t=>{1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||t.getAttribute("l-state")&&e(t.parentElement))}));else if("attributes"===t.type){if(t.target.parentElement&&t.target.parentElement.closest("[l-state]"))return;e(t.target.parentElement)}}))})).observe(t,s||{childList:!0,attributes:!0,subtree:!0})},exports.patch=v,exports.reactive=h,exports.renderDirective=o; |
@@ -9,4 +9,5 @@ const DIRECTIVE_PREFIX = 'l-'; | ||
const rawDirectiveSplitPattern = /:|\./; | ||
const keyPattern = (key, hasThis = true) => { | ||
const rawDirectiveSplitRE = () => /:|\./; | ||
const hasDirectiveRE = () => new RegExp(`(${DIRECTIVE_PREFIX}|${Object.keys(DIRECTIVE_SHORTHANDS).join('|')})\\w+`, 'gim'); | ||
const expressionPropRE = (key, hasThis = true) => { | ||
return new RegExp(`${hasThis ? 'this\\.' : ''}${key}\\b`); | ||
@@ -106,17 +107,26 @@ }; | ||
const joinDirective = ({ el, data, app }) => { | ||
const [array, contentType, delimiter] = data.value.split(/ as | by /); | ||
const hydratedArray = compute(array, { $el: el })(app.state); | ||
const accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
const inputCallback = (el, hydratedValue, data, app) => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
const modelDirective = ({ el: awaitingTypecastEl, data, app }) => { | ||
@@ -128,25 +138,3 @@ const el = awaitingTypecastEl; | ||
} | ||
el.oninput = () => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
}; | ||
el.oninput = () => inputCallback(el, hydratedValue, data, app); | ||
}; | ||
@@ -172,5 +160,34 @@ | ||
const forDirective = ({ el, data, app }) => { | ||
const [expression, target] = data.value.split(/ +in +/g); | ||
const [item, index] = expression.split(','); | ||
const hydratedArray = compute(target, { $el: el })(app.state); | ||
const template = String(el.__l_for); | ||
if (template) { | ||
let accumulator = ''; | ||
for (let i = 0; i < hydratedArray.length; i++) { | ||
let content = template; | ||
if (item) | ||
content = content.replace(new RegExp(`this.${item.trim()}`, 'g'), `${target}[${i}]`); | ||
if (index) | ||
content = content.replace(new RegExp(`this.${index.trim()}`, 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
const directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
@@ -181,5 +198,6 @@ IF: ifDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
const renderDirective = (props, directives) => { | ||
const name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
const name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
@@ -218,3 +236,10 @@ }; | ||
for (const { name, value } of [...el.attributes]) { | ||
const directiveData = { compute: compute(value, { $el: el }), value }; | ||
let returnable = true; | ||
if (name.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name)) | ||
returnable = false; | ||
const directiveData = { compute: compute(value, { $el: el }, returnable), value }; | ||
if (name.startsWith(DIRECTIVE_PREFIX)) { | ||
@@ -238,3 +263,3 @@ directives[name.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
const hasDirectives = Object.keys(directives).length > 0; | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => keyPattern(key, false).test(value))); | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => expressionPropRE(key, false).test(value))); | ||
if (hasDirectives) | ||
@@ -275,3 +300,3 @@ type = VNodeTypes.NEEDS_PATCH; | ||
} | ||
if (!strip || container.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
const compiledChildren = compile(container, state, components, strip, true); | ||
@@ -285,3 +310,3 @@ for (const componentChild of compiledChildren) { | ||
else { | ||
if (!strip || child.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
const compiledChildren = compile(child, state, components, strip, true); | ||
@@ -305,3 +330,3 @@ const node = createVNode(child, state, compiledChildren); | ||
const flattenedVDom = Object.assign({}, vdom); | ||
flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
flattenedVDom.children = flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
for (const child of vdom.children) { | ||
@@ -311,9 +336,7 @@ if (typeof child === 'string') | ||
if (child.children.length > 0) { | ||
for (const nestedChild of flat(child).children) { | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
flattenedVDom.children = [ | ||
...flattenedVDom.children, | ||
...flat({ children: child.children }).children, | ||
]; | ||
child.children = []; | ||
} | ||
@@ -366,3 +389,3 @@ } | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
@@ -392,5 +415,5 @@ }, | ||
const needsInit = type === 1; | ||
const hasKey = keys.some((key) => keyPattern(key).test(String(directives[name].value))); | ||
const hasKey = keys.some((key) => expressionPropRE(key).test(String(directives[name].value))); | ||
const hasKeyInFunction = Object.keys(state).some((key) => { | ||
const iterKeysInFunction = keys.some((k) => keyPattern(k).test(String(state[key]))); | ||
const iterKeysInFunction = keys.some((k) => expressionPropRE(k).test(String(state[key]))); | ||
return typeof state[key] === 'function' && iterKeysInFunction; | ||
@@ -414,3 +437,3 @@ }); | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
patch(node, app, keys); | ||
} | ||
@@ -487,14 +510,21 @@ }; | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest(`[${stateDirective}]`)) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
export { compile, createApp, directives, h, init, listen, patch, reactive, renderDirective }; |
@@ -1,1 +0,1 @@ | ||
var t;!function(t){t["@"]="on",t[":"]="bind"}(t||(t={}));const e=/:|\./,s=(t,e=!0)=>new RegExp(`${e?"this\\.":""}${t}\\b`);function n(t){try{const e=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),e).bind(t)(...Object.values(this.argsKV))}catch(t){console.warn(`Lucia Error: "${t}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const o=(t,e,s=!0)=>n.bind({expression:t,argsKV:{$el:e.$el},returnable:s}),i={BIND:({el:t,name:e,data:s,app:n})=>{switch(e.split(":")[1]){case"class":const o=s.compute(n.state);if("string"==typeof o)return t.setAttribute("class",`${t.className} ${o}`.trim());if(o instanceof Array)return t.setAttribute("class",`${t.className} ${o.join(" ")}`.trim());{const e=[];for(const t in o)o[t]&&e.push(t);return e.length>0?t.setAttribute("class",`${t.className} ${e.join(" ").trim()}`.trim()):t.className.trim().length>0?t.setAttribute("class",t.className):t.removeAttribute("class")}case"style":const i=s.compute(n.state);t.removeAttribute("style");for(const e in i)t.style[e]=i[e];break;default:const r=s.compute(n.state);if("object"==typeof r&&null!==r)for(const e in r)r[e]?t.setAttribute(e,r[e]):t.removeAttribute(e);else r?t.setAttribute(e.split(":")[1],r):t.removeAttribute(e.split(":")[1])}},JOIN:({el:t,data:e,app:s})=>{const[n,i,r]=e.value.split(/ as | by /),a=o(n,{$el:t})(s.state);t["text"===i?"innerText":"innerHTML"]=a.join(r||"");const c=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([t,e])=>{c.directive(t,e)})),Object.entries(s.components||{}).map((([t,e])=>{c.component(t,e)})),c.mount(t)},HTML:({el:t,data:e,app:s})=>{var n;t.innerHTML=null!==(n=e.compute(s.state))&&void 0!==n?n:e.value;const o=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([t,e])=>{o.directive(t,e)})),Object.entries(s.components||{}).map((([t,e])=>{o.component(t,e)})),o.mount(t)},IF:({el:t,data:e,app:s})=>{e.compute(s.state)?t.style.removeProperty("display"):t.style.display="none"},MODEL:({el:t,data:e,app:s})=>{const n=t,i=e.compute(s.state);n.value!==i&&(n.value=i),n.oninput=()=>{const t="number"==typeof i&&!isNaN(n.value),r="boolean"==typeof i&&("true"===n.value||"false"===n.value),a=null==i&&("null"===n.value||"undefined"===n.value);let c;c=t?`Number('${n.value}').toPrecision()`:r?`Boolean('${n.value}')`:a?"null"===n.value?null:void 0:`'${n.value}'`,o(`${e.value} = ${c}`,{$el:n},!1)(s.state)}},ON:({el:t,name:e,data:s,app:n})=>{const[o,i]=e.split("."),r=o.split(":")[1],a=i||null;t[`on${r}`]=t=>{"prevent"===a&&t.preventDefault(),"stop"===a&&t.stopPropagation(),s.compute(n.state)}},TEXT:({el:t,data:e,app:s})=>{var n;t.textContent=null!==(n=e.compute(s.state))&&void 0!==n?n:e.value}},r=(t,s)=>{s[t.name.split(e)[0].toUpperCase()](t)};var a;!function(t){t[t.STATIC=0]="STATIC",t[t.NEEDS_PATCH=1]="NEEDS_PATCH",t[t.DYNAMIC=2]="DYNAMIC"}(a||(a={}));const c=(t,e=[],s)=>{const n=Object.assign({},null==s?void 0:s.attributes),o=Object.assign({},null==s?void 0:s.directives);return e=e instanceof Array?e:[e],n.className&&(n.className=n.className.trim()),{tag:t,children:e,props:{attributes:n,directives:o,ref:(null==s?void 0:s.ref)||void 0,type:(null==s?void 0:s.type)||0}}},l=e=>{const s={},n={};if(e.attributes)for(const{name:i,value:r}of[...e.attributes]){const a={compute:o(r,{$el:e}),value:r};i.startsWith("l-")?n[i.slice("l-".length)]=a:Object.keys(t).includes(i[0])?n[`${t[i[0]]}:${i.slice(1)}`]=a:s[i]=r}return{attributes:s,directives:n}},u=(t,e,n)=>{const{attributes:o,directives:i}=l(t);let r=a.STATIC;const u=Object.keys(i).length>0,p=Object.values(i).some((({value:t})=>Object.keys(e).some((e=>s(e,!1).test(t)))));return u&&(r=a.NEEDS_PATCH),p&&(r=a.DYNAMIC),c(t.tagName.toLowerCase(),n,{attributes:o,directives:i,ref:r===a.STATIC||o.id?void 0:t,type:r})},p=(t,e={},s={},n=!1,o=!1)=>{var i;if(!t)throw new Error("Please provide a Element");const r=[],a=Array.prototype.slice.call(t.childNodes);for(const o of a)switch(o.nodeType){case Node.TEXT_NODE:!n&&o.nodeValue&&r.push(o.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(s).includes(o.tagName)){const a=document.createElement("div"),c=s[o.tagName]({children:o.innerHTML,state:e});a.innerHTML=c;for(const[t,e]of Object.entries(l(o).directives))null===(i=a.firstElementChild)||void 0===i||i.setAttribute(`l-${t}`,e.value);if(!n||a.outerHTML.includes(" l-")){const t=p(a,e,s,n,!0);for(const e of t)r.push(e)}t.replaceChild(a.firstElementChild,o)}else if(!n||o.outerHTML.includes(" l-")){const t=p(o,e,s,n,!0),i=u(o,e,t);r.push(i)}}if(o)return r;{let s=u(t,e,r);return n?d(s):s}},d=t=>{const e=Object.assign({},t);e.children.filter((t=>"object"==typeof t&&t.props.type>0));for(const s of t.children)if("string"!=typeof s&&s.children.length>0)for(const t of d(s).children)"string"!=typeof t&&0!==t.props.type&&e.children.push(t);return e},m=(t,e,s,n,o=!1)=>{if("length"===e){const e=Object.keys(s).filter((e=>{return s[e]instanceof Array&&(n=t,o=s[e],n instanceof Array&&o instanceof Array&&n.length===o.length&&n.every(((t,e)=>t===o[e])));var n,o}));return 0!==e.length&&n(e),!0}return o&&n([e]),!1},h=(t,e)=>{const s={get:(t,e)=>"object"==typeof t[e]&&null!==t[e]?new Proxy(t[e],s):t[e],set(s,n,o){const i=s[n]!==o;return i&&(s[n]=o),m(s,n,t,e,i),!0},deleteProperty:(s,n)=>(delete s[n],m(s,n,t,e),!0)};return new Proxy(t,s)},v=(t,e={},n)=>{let o=!1;const i=e.state||{};if(t){n||(n=Object.keys(i)),"%LUCIA_FIRST_RENDER%"===n[0]&&(o=!0);for(let c of t.children)if("string"!=typeof c){if(c.props.type>a.STATIC){const{attributes:t,directives:l,ref:u,type:p}=c.props;let d=[];if(!o)for(const t in l){const e=1===p,o=n.some((e=>s(e).test(String(l[t].value)))),r=Object.keys(i).some((t=>{const e=n.some((e=>s(e).test(String(i[t]))));return"function"==typeof i[t]&&e}));(e||o||r)&&d.push(t)}c.props.type=p===a.NEEDS_PATCH?a.STATIC:p;(o?Object.keys(l):d).map((s=>{const n=l[s],o=t.id?document.getElementById(t.id):u;r({el:o,name:s,data:n,app:e},Object.assign({},e.directives))}))}c.children.length>0&&v(c,i,n)}}};class f{constructor(t={},e){this.state=t,this.directives={},this.components={},this.mountHook=e}mount(t,e=!1){const s="string"==typeof t?document.querySelector(t):t;return this.vdom=this.compile(s),e||(this.state=h(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),i)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state}component(t,e){this.components[t.toUpperCase()]=e}directive(t,e){this.directives[t.toUpperCase()]=e}patch(t){const e={state:this.state,directives:this.directives,components:this.components};v(this.vdom,e,t)}compile(t){return p(t,this.state,this.components,!0)}}const b=(t,e)=>new f(t,e),y=(t=document)=>{[...t.querySelectorAll("[l-state]")].filter((t=>void 0===t.__l)).map((t=>{const e=t.getAttribute("l-state");try{const s=new Function(`return ${e}`)(),n=b(s);n.mount(t),t.__l=n}catch(s){console.warn(`Lucia Error: "${s}"\n\nExpression: "${e}"\nElement:`,t)}}))},g=(t,e=document,s)=>{const n=new MutationObserver((o=>{o.map((e=>{e.addedNodes.length>0&&e.addedNodes.forEach((e=>{1===e.nodeType&&(e.parentElement&&e.parentElement.closest("[l-state]")||t(e.parentElement))}))})),n.observe(e,s||{childList:!0,attributes:!0,subtree:!0})}))};export{p as compile,b as createApp,i as directives,c as h,y as init,g as listen,v as patch,h as reactive,r as renderDirective}; | ||
var e;!function(e){e["@"]="on",e[":"]="bind"}(e||(e={}));const t=()=>new RegExp(`(l-|${Object.keys(e).join("|")})\\w+`,"gim"),s=(e,t=!0)=>new RegExp(`${t?"this\\.":""}${e}\\b`);function n(e){try{const t=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),t).bind(e)(...Object.values(this.argsKV))}catch(e){console.warn(`Lucia Error: "${e}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const r=(e,t,s=!0)=>n.bind({expression:e,argsKV:{$el:t.$el},returnable:s}),i={BIND:({el:e,name:t,data:s,app:n})=>{switch(t.split(":")[1]){case"class":const r=s.compute(n.state);if("string"==typeof r)return e.setAttribute("class",`${e.className} ${r}`.trim());if(r instanceof Array)return e.setAttribute("class",`${e.className} ${r.join(" ")}`.trim());{const t=[];for(const e in r)r[e]&&t.push(e);return t.length>0?e.setAttribute("class",`${e.className} ${t.join(" ").trim()}`.trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class")}case"style":const i=s.compute(n.state);e.removeAttribute("style");for(const t in i)e.style[t]=i[t];break;default:const o=s.compute(n.state);if("object"==typeof o&&null!==o)for(const t in o)o[t]?e.setAttribute(t,o[t]):e.removeAttribute(t);else o?e.setAttribute(t.split(":")[1],o):e.removeAttribute(t.split(":")[1])}},HTML:({el:e,data:t,app:s})=>{var n;e.innerHTML=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value;const r=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{r.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{r.component(e,t)})),r.mount(e)},IF:({el:e,data:t,app:s})=>{t.compute(s.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:({el:e,data:t,app:s})=>{const n=e,i=t.compute(s.state);n.value!==i&&(n.value=i),n.oninput=()=>((e,t,s,n)=>{const i="number"==typeof t&&!isNaN(e.value),o="boolean"==typeof t&&("true"===e.value||"false"===e.value),a=null==t&&("null"===e.value||"undefined"===e.value);let l;return l=i?`Number('${e.value}').toPrecision()`:o?`Boolean('${e.value}')`:a?"null"===e.value?null:void 0:`'${e.value}'`,r(`${s.value} = ${l}`,{$el:e},!1)(n.state),l})(n,i,t,s)},ON:({el:e,name:t,data:s,app:n})=>{const[r,i]=t.split("."),o=r.split(":")[1],a=i||null;e[`on${o}`]=e=>{"prevent"===a&&e.preventDefault(),"stop"===a&&e.stopPropagation(),s.compute(n.state)}},TEXT:({el:e,data:t,app:s})=>{var n;e.textContent=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value},FOR:({el:e,data:t,app:s})=>{const[n,i]=t.value.split(/ +in +/g),[o,a]=n.split(","),l=r(i,{$el:e})(s.state),c=String(e.__l_for);if(c){let t="";for(let e=0;e<l.length;e++){let s=c;o&&(s=s.replace(new RegExp(`this.${o.trim()}`,"g"),`${i}[${e}]`)),a&&(s=s.replace(new RegExp(`this.${a.trim()}`,"g"),String(e))),t+=s}e.innerHTML=t}else e.innerHTML=l.join("");const u=b(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{u.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{u.component(e,t)})),u.mount(e)}},o=(e,t)=>{t[e.name.split(/:|\./)[0].toUpperCase()](e)};var a;!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(a||(a={}));const l=(e,t=[],s)=>{const n=Object.assign({},null==s?void 0:s.attributes),r=Object.assign({},null==s?void 0:s.directives);return t=t instanceof Array?t:[t],n.className&&(n.className=n.className.trim()),{tag:e,children:t,props:{attributes:n,directives:r,ref:(null==s?void 0:s.ref)||void 0,type:(null==s?void 0:s.type)||0}}},c=t=>{const s={},n={};if(t.attributes)for(const{name:i,value:o}of[...t.attributes]){let a=!0;i.includes("for")&&void 0===t.__l_for&&(t.__l_for=String(t.innerHTML).trim(),a=!1),/on|@/.test(i)&&(a=!1);const l={compute:r(o,{$el:t},a),value:o};i.startsWith("l-")?n[i.slice("l-".length)]=l:Object.keys(e).includes(i[0])?n[`${e[i[0]]}:${i.slice(1)}`]=l:s[i]=o}return{attributes:s,directives:n}},u=(e,t,n)=>{const{attributes:r,directives:i}=c(e);let o=a.STATIC;const u=Object.keys(i).length>0,p=Object.values(i).some((({value:e})=>Object.keys(t).some((t=>s(t,!1).test(e)))));return u&&(o=a.NEEDS_PATCH),p&&(o=a.DYNAMIC),l(e.tagName.toLowerCase(),n,{attributes:r,directives:i,ref:o===a.STATIC||r.id?void 0:e,type:o})},p=(e,s={},n={},r=!1,i=!1)=>{var o;if(!e)throw new Error("Please provide a Element");const a=[],l=Array.prototype.slice.call(e.childNodes);for(const i of l)switch(i.nodeType){case Node.TEXT_NODE:!r&&i.nodeValue&&a.push(i.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(n).includes(i.tagName)){const l=document.createElement("div"),u=n[i.tagName]({children:i.innerHTML,state:s});l.innerHTML=u;for(const[e,t]of Object.entries(c(i).directives))null===(o=l.firstElementChild)||void 0===o||o.setAttribute(`l-${e}`,t.value);if(!r||t().test(l.outerHTML)){const e=p(l,s,n,r,!0);for(const t of e)a.push(t)}e.replaceChild(l.firstElementChild,i)}else if(!r||t().test(i.outerHTML)){const e=p(i,s,n,r,!0),t=u(i,s,e);a.push(t)}}if(i)return a;{let t=u(e,s,a);return r?d(t):t}},d=e=>{const t=Object.assign({},e);t.children=t.children.filter((e=>"object"==typeof e&&e.props.type>0));for(const s of e.children)"string"!=typeof s&&s.children.length>0&&(t.children=[...t.children,...d({children:s.children}).children],s.children=[]);return t},m=(e,t,s,n,r=!1)=>{if("length"===t){const t=Object.keys(s).filter((t=>{return s[t]instanceof Array&&(n=e,r=s[t],n instanceof Array&&r instanceof Array&&n.length===r.length&&n.every(((e,t)=>e===r[t])));var n,r}));return 0!==t.length&&n(t),!0}return r&&n([t]),!1},h=(e,t)=>{const s={get:(e,t)=>"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],s):e[t],set(s,n,r){const i=s[n]!==r;return i&&(s[n]=r),m(s,n,e,t,i),!0},deleteProperty:(s,n)=>(delete s[n],m(s,n,e,t,!0),!0)};return new Proxy(e,s)},v=(e,t={},n)=>{let r=!1;const i=t.state||{};if(e){n||(n=Object.keys(i)),"%LUCIA_FIRST_RENDER%"===n[0]&&(r=!0);for(let l of e.children)if("string"!=typeof l){if(l.props.type>a.STATIC){const{attributes:e,directives:c,ref:u,type:p}=l.props;let d=[];if(!r)for(const e in c){const t=1===p,r=n.some((t=>s(t).test(String(c[e].value)))),o=Object.keys(i).some((e=>{const t=n.some((t=>s(t).test(String(i[e]))));return"function"==typeof i[e]&&t}));(t||r||o)&&d.push(e)}l.props.type=p===a.NEEDS_PATCH?a.STATIC:p;(r?Object.keys(c):d).map((s=>{const n=c[s],r=e.id?document.getElementById(e.id):u;o({el:r,name:s,data:n,app:t},Object.assign({},t.directives))}))}l.children.length>0&&v(l,t,n)}}};class f{constructor(e={},t){this.state=e,this.directives={},this.components={},this.mountHook=t}mount(e,t=!1){const s="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(s),t||(this.state=h(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),i)),this.patch(["%LUCIA_FIRST_RENDER%"]),this.mountHook&&this.mountHook(this.state),this.state}component(e,t){this.components[e.toUpperCase()]=t}directive(e,t){this.directives[e.toUpperCase()]=t}patch(e){const t={state:this.state,directives:this.directives,components:this.components};v(this.vdom,t,e)}compile(e){return p(e,this.state,this.components,!0)}}const b=(e,t)=>new f(e,t),y=(e=document)=>{[...e.querySelectorAll("[l-state]")].filter((e=>void 0===e.__l)).map((e=>{const t=e.getAttribute("l-state");try{const s=new Function(`return ${t}`)(),n=b(s);n.mount(e),e.__l=n}catch(s){console.warn(`Lucia Error: "${s}"\n\nExpression: "${t}"\nElement:`,e)}}))},g=(e,t=document,s)=>{new MutationObserver((t=>{t.map((t=>{if(t.addedNodes.length>0)t.addedNodes.forEach((t=>{1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||t.getAttribute("l-state")&&e(t.parentElement))}));else if("attributes"===t.type){if(t.target.parentElement&&t.target.parentElement.closest("[l-state]"))return;e(t.target.parentElement)}}))})).observe(t,s||{childList:!0,attributes:!0,subtree:!0})};export{p as compile,b as createApp,i as directives,l as h,y as init,g as listen,v as patch,h as reactive,o as renderDirective}; |
1040
dist/lucia.js
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : | ||
typeof define === 'function' && define.amd ? define(factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Lucia = factory()); | ||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : | ||
typeof define === 'function' && define.amd ? define(factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Lucia = factory()); | ||
}(this, (function () { 'use strict'; | ||
const DIRECTIVE_PREFIX = 'l-'; | ||
const LUCIA_FIRST_RENDER = '%LUCIA_FIRST_RENDER%'; | ||
var DIRECTIVE_SHORTHANDS; | ||
(function (DIRECTIVE_SHORTHANDS) { | ||
DIRECTIVE_SHORTHANDS["@"] = "on"; | ||
DIRECTIVE_SHORTHANDS[":"] = "bind"; | ||
})(DIRECTIVE_SHORTHANDS || (DIRECTIVE_SHORTHANDS = {})); | ||
/*! ***************************************************************************** | ||
Copyright (c) Microsoft Corporation. | ||
const rawDirectiveSplitPattern = /:|\./; | ||
const keyPattern = (key, hasThis = true) => { | ||
return new RegExp(`${hasThis ? 'this\\.' : ''}${key}\\b`); | ||
}; | ||
Permission to use, copy, modify, and/or distribute this software for any | ||
purpose with or without fee is hereby granted. | ||
const bindDirective = ({ el, name, data, app }) => { | ||
switch (name.split(':')[1]) { | ||
case 'class': | ||
const hydratedClasses = data.compute(app.state); | ||
if (typeof hydratedClasses === 'string') { | ||
return el.setAttribute('class', `${el.className} ${hydratedClasses}`.trim()); | ||
} | ||
else if (hydratedClasses instanceof Array) { | ||
return el.setAttribute('class', `${el.className} ${hydratedClasses.join(' ')}`.trim()); | ||
} | ||
else { | ||
const classes = []; | ||
for (const key in hydratedClasses) { | ||
if (hydratedClasses[key]) | ||
classes.push(key); | ||
} | ||
if (classes.length > 0) { | ||
return el.setAttribute('class', `${el.className} ${classes.join(' ').trim()}`.trim()); | ||
} | ||
else if (el.className.trim().length > 0) { | ||
return el.setAttribute('class', el.className); | ||
} | ||
else { | ||
return el.removeAttribute('class'); | ||
} | ||
} | ||
case 'style': | ||
const hydratedStyles = data.compute(app.state); | ||
el.removeAttribute('style'); | ||
for (const key in hydratedStyles) { | ||
el.style[key] = hydratedStyles[key]; | ||
} | ||
break; | ||
default: | ||
const hydratedAttributes = data.compute(app.state); | ||
if (typeof hydratedAttributes === 'object' && hydratedAttributes !== null) { | ||
for (const key in hydratedAttributes) { | ||
if (hydratedAttributes[key]) { | ||
el.setAttribute(key, hydratedAttributes[key]); | ||
} | ||
else { | ||
el.removeAttribute(key); | ||
} | ||
} | ||
} | ||
else if (hydratedAttributes) { | ||
el.setAttribute(name.split(':')[1], hydratedAttributes); | ||
} | ||
else { | ||
el.removeAttribute(name.split(':')[1]); | ||
} | ||
break; | ||
} | ||
}; | ||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | ||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY | ||
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | ||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM | ||
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR | ||
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR | ||
PERFORMANCE OF THIS SOFTWARE. | ||
***************************************************************************** */ | ||
const htmlDirective = ({ el, data, app }) => { | ||
var _a; | ||
el.innerHTML = (_a = data.compute(app.state)) !== null && _a !== void 0 ? _a : data.value; | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
function __awaiter(thisArg, _arguments, P, generator) { | ||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } | ||
return new (P || (P = Promise))(function (resolve, reject) { | ||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } | ||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } | ||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } | ||
step((generator = generator.apply(thisArg, _arguments || [])).next()); | ||
}); | ||
} | ||
const ifDirective = ({ el, data, app }) => { | ||
const hydratedConditional = data.compute(app.state); | ||
if (hydratedConditional) { | ||
el.style.removeProperty('display'); | ||
} | ||
else { | ||
el.style.display = 'none'; | ||
} | ||
}; | ||
const DIRECTIVE_PREFIX = 'l-'; | ||
const LUCIA_FIRST_RENDER = '%LUCIA_FIRST_RENDER%'; | ||
var DIRECTIVE_SHORTHANDS; | ||
(function (DIRECTIVE_SHORTHANDS) { | ||
DIRECTIVE_SHORTHANDS["@"] = "on"; | ||
DIRECTIVE_SHORTHANDS[":"] = "bind"; | ||
})(DIRECTIVE_SHORTHANDS || (DIRECTIVE_SHORTHANDS = {})); | ||
function createComputeFunction(state) { | ||
try { | ||
const expression = this.returnable ? `return ${this.expression}` : this.expression; | ||
return new Function(...Object.keys(this.argsKV), expression).bind(state)(...Object.values(this.argsKV)); | ||
} | ||
catch (err) { | ||
console.warn(`Lucia Error: "${err}"\n\nExpression: "${this.expression}"\nElement:`, this.argsKV.$el); | ||
} | ||
} | ||
const compute = (expression, data, returnable = true) => { | ||
return createComputeFunction.bind({ expression, argsKV: { $el: data.$el }, returnable }); | ||
}; | ||
const rawDirectiveSplitRE = () => /:|\./; | ||
const hasDirectiveRE = () => new RegExp(`(${DIRECTIVE_PREFIX}|${Object.keys(DIRECTIVE_SHORTHANDS).join('|')})\\w+`, 'gim'); | ||
const expressionPropRE = (key, hasThis = true) => { | ||
return new RegExp(`${hasThis ? 'this\\.' : ''}${key}\\b`); | ||
}; | ||
const joinDirective = ({ el, data, app }) => { | ||
const [array, contentType, delimiter] = data.value.split(/ as | by /); | ||
const hydratedArray = compute(array, { $el: el })(app.state); | ||
const accessProp = contentType === 'text' ? 'innerText' : 'innerHTML'; | ||
el[accessProp] = hydratedArray.join(delimiter || ''); | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
const bindDirective = ({ el, name, data, app }) => { | ||
switch (name.split(':')[1]) { | ||
case 'class': | ||
const hydratedClasses = data.compute(app.state); | ||
if (typeof hydratedClasses === 'string') { | ||
return el.setAttribute('class', `${el.className} ${hydratedClasses}`.trim()); | ||
} | ||
else if (hydratedClasses instanceof Array) { | ||
return el.setAttribute('class', `${el.className} ${hydratedClasses.join(' ')}`.trim()); | ||
} | ||
else { | ||
const classes = []; | ||
for (const key in hydratedClasses) { | ||
if (hydratedClasses[key]) | ||
classes.push(key); | ||
} | ||
if (classes.length > 0) { | ||
return el.setAttribute('class', `${el.className} ${classes.join(' ').trim()}`.trim()); | ||
} | ||
else if (el.className.trim().length > 0) { | ||
return el.setAttribute('class', el.className); | ||
} | ||
else { | ||
return el.removeAttribute('class'); | ||
} | ||
} | ||
case 'style': | ||
const hydratedStyles = data.compute(app.state); | ||
el.removeAttribute('style'); | ||
for (const key in hydratedStyles) { | ||
el.style[key] = hydratedStyles[key]; | ||
} | ||
break; | ||
default: | ||
const hydratedAttributes = data.compute(app.state); | ||
if (typeof hydratedAttributes === 'object' && hydratedAttributes !== null) { | ||
for (const key in hydratedAttributes) { | ||
if (hydratedAttributes[key]) { | ||
el.setAttribute(key, hydratedAttributes[key]); | ||
} | ||
else { | ||
el.removeAttribute(key); | ||
} | ||
} | ||
} | ||
else if (hydratedAttributes) { | ||
el.setAttribute(name.split(':')[1], hydratedAttributes); | ||
} | ||
else { | ||
el.removeAttribute(name.split(':')[1]); | ||
} | ||
break; | ||
} | ||
}; | ||
const modelDirective = ({ el: awaitingTypecastEl, data, app }) => { | ||
const el = awaitingTypecastEl; | ||
const hydratedValue = data.compute(app.state); | ||
if (el.value !== hydratedValue) { | ||
el.value = hydratedValue; | ||
} | ||
el.oninput = () => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
}; | ||
}; | ||
const htmlDirective = ({ el, data, app }) => { | ||
var _a; | ||
el.innerHTML = (_a = data.compute(app.state)) !== null && _a !== void 0 ? _a : data.value; | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
const onDirective = ({ el, name, data, app }) => { | ||
const [directiveAndEventName, prop] = name.split('.'); | ||
const eventName = directiveAndEventName.split(':')[1]; | ||
const eventProp = prop || null; | ||
el[`on${eventName}`] = ($event) => { | ||
if (eventProp === 'prevent') | ||
$event.preventDefault(); | ||
if (eventProp === 'stop') | ||
$event.stopPropagation(); | ||
data.compute(app.state); | ||
}; | ||
}; | ||
const ifDirective = ({ el, data, app }) => { | ||
const hydratedConditional = data.compute(app.state); | ||
if (hydratedConditional) { | ||
el.style.removeProperty('display'); | ||
} | ||
else { | ||
el.style.display = 'none'; | ||
} | ||
}; | ||
const textDirective = ({ el, data, app }) => { | ||
var _a; | ||
el.textContent = (_a = data.compute(app.state)) !== null && _a !== void 0 ? _a : data.value; | ||
}; | ||
function createComputeFunction(state) { | ||
try { | ||
const expression = this.returnable ? `return ${this.expression}` : this.expression; | ||
return new Function(...Object.keys(this.argsKV), expression).bind(state)(...Object.values(this.argsKV)); | ||
} | ||
catch (err) { | ||
console.warn(`Lucia Error: "${err}"\n\nExpression: "${this.expression}"\nElement:`, this.argsKV.$el); | ||
} | ||
} | ||
const compute = (expression, data, returnable = true) => { | ||
return createComputeFunction.bind({ expression, argsKV: { $el: data.$el }, returnable }); | ||
}; | ||
const directives = { | ||
BIND: bindDirective, | ||
JOIN: joinDirective, | ||
HTML: htmlDirective, | ||
IF: ifDirective, | ||
MODEL: modelDirective, | ||
ON: onDirective, | ||
TEXT: textDirective, | ||
}; | ||
const renderDirective = (props, directives) => { | ||
const name = props.name.split(rawDirectiveSplitPattern)[0]; | ||
directives[name.toUpperCase()](props); | ||
}; | ||
const inputCallback = (el, hydratedValue, data, app) => { | ||
const isNumber = typeof hydratedValue === 'number' && !isNaN(el.value); | ||
const isBoolean = typeof hydratedValue === 'boolean' && (el.value === 'true' || el.value === 'false'); | ||
const isNullish = (hydratedValue === null || hydratedValue === undefined) && | ||
(el.value === 'null' || el.value === 'undefined'); | ||
let payload; | ||
if (isNumber) { | ||
payload = `Number('${el.value}').toPrecision()`; | ||
} | ||
else if (isBoolean) { | ||
payload = `Boolean('${el.value}')`; | ||
} | ||
else if (isNullish) { | ||
if (el.value === 'null') | ||
payload = null; | ||
else | ||
payload = undefined; | ||
} | ||
else { | ||
payload = `'${el.value}'`; | ||
} | ||
compute(`${data.value} = ${payload}`, { $el: el }, false)(app.state); | ||
return payload; | ||
}; | ||
const modelDirective = ({ el: awaitingTypecastEl, data, app }) => { | ||
const el = awaitingTypecastEl; | ||
const hydratedValue = data.compute(app.state); | ||
if (el.value !== hydratedValue) { | ||
el.value = hydratedValue; | ||
} | ||
el.oninput = () => inputCallback(el, hydratedValue, data, app); | ||
}; | ||
var VNodeTypes; | ||
(function (VNodeTypes) { | ||
VNodeTypes[VNodeTypes["STATIC"] = 0] = "STATIC"; | ||
VNodeTypes[VNodeTypes["NEEDS_PATCH"] = 1] = "NEEDS_PATCH"; | ||
VNodeTypes[VNodeTypes["DYNAMIC"] = 2] = "DYNAMIC"; | ||
})(VNodeTypes || (VNodeTypes = {})); | ||
const onDirective = ({ el, name, data, app }) => { | ||
const [directiveAndEventName, prop] = name.split('.'); | ||
const eventName = directiveAndEventName.split(':')[1]; | ||
const eventProp = prop || null; | ||
el[`on${eventName}`] = ($event) => { | ||
if (eventProp === 'prevent') | ||
$event.preventDefault(); | ||
if (eventProp === 'stop') | ||
$event.stopPropagation(); | ||
data.compute(app.state); | ||
}; | ||
}; | ||
const h = (tag, children = [], props) => { | ||
const attributes = Object.assign({}, props === null || props === void 0 ? void 0 : props.attributes); | ||
const directives = Object.assign({}, props === null || props === void 0 ? void 0 : props.directives); | ||
children = children instanceof Array ? children : [children]; | ||
if (attributes.className) | ||
attributes.className = attributes.className.trim(); | ||
return { | ||
tag, | ||
children, | ||
props: { | ||
attributes, | ||
directives, | ||
ref: (props === null || props === void 0 ? void 0 : props.ref) || undefined, | ||
type: (props === null || props === void 0 ? void 0 : props.type) || 0, | ||
}, | ||
}; | ||
}; | ||
const textDirective = ({ el, data, app }) => { | ||
var _a; | ||
el.textContent = (_a = data.compute(app.state)) !== null && _a !== void 0 ? _a : data.value; | ||
}; | ||
const props = (el) => { | ||
const attributes = {}; | ||
const directives = {}; | ||
if (el.attributes) { | ||
for (const { name, value } of [...el.attributes]) { | ||
const directiveData = { compute: compute(value, { $el: el }), value }; | ||
if (name.startsWith(DIRECTIVE_PREFIX)) { | ||
directives[name.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
} | ||
else if (Object.keys(DIRECTIVE_SHORTHANDS).includes(name[0])) { | ||
directives[`${DIRECTIVE_SHORTHANDS[name[0]]}:${name.slice(1)}`] = directiveData; | ||
} | ||
else { | ||
attributes[name] = value; | ||
} | ||
} | ||
} | ||
return { attributes, directives }; | ||
}; | ||
const forDirective = ({ el, data, app }) => { | ||
const [expression, target] = data.value.split(/ +in +/g); | ||
const [item, index] = expression.split(','); | ||
const hydratedArray = compute(target, { $el: el })(app.state); | ||
const template = String(el.__l_for); | ||
if (template) { | ||
let accumulator = ''; | ||
for (let i = 0; i < hydratedArray.length; i++) { | ||
let content = template; | ||
if (item) | ||
content = content.replace(new RegExp(`this.${item.trim()}`, 'g'), `${target}[${i}]`); | ||
if (index) | ||
content = content.replace(new RegExp(`this.${index.trim()}`, 'g'), String(i)); | ||
accumulator += content; | ||
} | ||
el.innerHTML = accumulator; | ||
} | ||
else { | ||
el.innerHTML = hydratedArray.join(''); | ||
} | ||
const scope = createApp(Object.assign({}, app.state)); | ||
Object.entries(app.directives || {}).map(([name, evaluationCallback]) => { | ||
scope.directive(name, evaluationCallback); | ||
}); | ||
Object.entries(app.components || {}).map(([name, templateCallback]) => { | ||
scope.component(name, templateCallback); | ||
}); | ||
scope.mount(el); | ||
}; | ||
const createVNode = (el, state, children) => { | ||
const { attributes, directives } = props(el); | ||
let type = VNodeTypes.STATIC; | ||
const hasDirectives = Object.keys(directives).length > 0; | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => keyPattern(key, false).test(value))); | ||
if (hasDirectives) | ||
type = VNodeTypes.NEEDS_PATCH; | ||
if (hasKeyInDirectives) | ||
type = VNodeTypes.DYNAMIC; | ||
return h(el.tagName.toLowerCase(), children, { | ||
attributes: attributes, | ||
directives: directives, | ||
ref: type === VNodeTypes.STATIC || attributes.id ? undefined : el, | ||
type, | ||
}); | ||
}; | ||
const compile = (el, state = {}, components = {}, strip = false, callSelf = false) => { | ||
var _a; | ||
if (!el) | ||
throw new Error('Please provide a Element'); | ||
const children = []; | ||
const childNodes = Array.prototype.slice.call(el.childNodes); | ||
for (const child of childNodes) { | ||
switch (child.nodeType) { | ||
case Node.TEXT_NODE: | ||
if (!strip && child.nodeValue) { | ||
children.push(child.nodeValue); | ||
} | ||
break; | ||
case Node.ELEMENT_NODE: | ||
if (Object.keys(components).includes(child.tagName)) { | ||
const container = document.createElement('div'); | ||
const template = components[child.tagName]({ | ||
children: child.innerHTML, | ||
state, | ||
}); | ||
container.innerHTML = template; | ||
for (const [key, data] of Object.entries(props(child).directives)) { | ||
(_a = container.firstElementChild) === null || _a === void 0 ? void 0 : _a.setAttribute(`${DIRECTIVE_PREFIX}${key}`, data.value); | ||
} | ||
if (!strip || container.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
const compiledChildren = compile(container, state, components, strip, true); | ||
for (const componentChild of compiledChildren) { | ||
children.push(componentChild); | ||
} | ||
} | ||
el.replaceChild(container.firstElementChild, child); | ||
} | ||
else { | ||
if (!strip || child.outerHTML.includes(` ${DIRECTIVE_PREFIX}`)) { | ||
const compiledChildren = compile(child, state, components, strip, true); | ||
const node = createVNode(child, state, compiledChildren); | ||
children.push(node); | ||
} | ||
} | ||
break; | ||
} | ||
} | ||
if (callSelf) { | ||
return children; | ||
} | ||
else { | ||
let vnode = createVNode(el, state, children); | ||
return strip ? flat(vnode) : vnode; | ||
} | ||
}; | ||
const flat = (vdom) => { | ||
const flattenedVDom = Object.assign({}, vdom); | ||
flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
for (const child of vdom.children) { | ||
if (typeof child === 'string') | ||
continue; | ||
if (child.children.length > 0) { | ||
for (const nestedChild of flat(child).children) { | ||
if (typeof nestedChild === 'string') | ||
continue; | ||
if (nestedChild.props.type !== 0) { | ||
flattenedVDom.children.push(nestedChild); | ||
} | ||
} | ||
} | ||
} | ||
return flattenedVDom; | ||
}; | ||
const directives = { | ||
BIND: bindDirective, | ||
HTML: htmlDirective, | ||
IF: ifDirective, | ||
MODEL: modelDirective, | ||
ON: onDirective, | ||
TEXT: textDirective, | ||
FOR: forDirective, | ||
}; | ||
const renderDirective = (props, directives) => { | ||
const name = props.name.split(rawDirectiveSplitRE())[0]; | ||
directives[name.toUpperCase()](props); | ||
}; | ||
const arrayEquals = (firstArray, secondArray) => { | ||
return (firstArray instanceof Array && | ||
secondArray instanceof Array && | ||
firstArray.length === secondArray.length && | ||
firstArray.every((value, i) => value === secondArray[i])); | ||
}; | ||
var VNodeTypes; | ||
(function (VNodeTypes) { | ||
VNodeTypes[VNodeTypes["STATIC"] = 0] = "STATIC"; | ||
VNodeTypes[VNodeTypes["NEEDS_PATCH"] = 1] = "NEEDS_PATCH"; | ||
VNodeTypes[VNodeTypes["DYNAMIC"] = 2] = "DYNAMIC"; | ||
})(VNodeTypes || (VNodeTypes = {})); | ||
const handlePatch = (target, key, state, patch, needsUpdate = false) => { | ||
if (key === 'length') { | ||
const affectedKeys = Object.keys(state).filter((k) => { | ||
return state[k] instanceof Array && arrayEquals(target, state[k]); | ||
}); | ||
if (affectedKeys.length !== 0) | ||
patch(affectedKeys); | ||
return true; | ||
} | ||
else { | ||
if (needsUpdate) | ||
patch([key]); | ||
return false; | ||
} | ||
}; | ||
const reactive = (state, patch) => { | ||
const handler = { | ||
get(target, key) { | ||
if (typeof target[key] === 'object' && target[key] !== null) { | ||
return new Proxy(target[key], handler); | ||
} | ||
else { | ||
return target[key]; | ||
} | ||
}, | ||
set(target, key, value) { | ||
const needsUpdate = target[key] !== value; | ||
if (needsUpdate) { | ||
target[key] = value; | ||
} | ||
handlePatch(target, key, state, patch, needsUpdate); | ||
return true; | ||
}, | ||
deleteProperty(target, key) { | ||
delete target[key]; | ||
handlePatch(target, key, state, patch); | ||
return true; | ||
}, | ||
}; | ||
return new Proxy(state, handler); | ||
}; | ||
const h = (tag, children = [], props) => { | ||
const attributes = Object.assign({}, props === null || props === void 0 ? void 0 : props.attributes); | ||
const directives = Object.assign({}, props === null || props === void 0 ? void 0 : props.directives); | ||
children = children instanceof Array ? children : [children]; | ||
if (attributes.className) | ||
attributes.className = attributes.className.trim(); | ||
return { | ||
tag, | ||
children, | ||
props: { | ||
attributes, | ||
directives, | ||
ref: (props === null || props === void 0 ? void 0 : props.ref) || undefined, | ||
type: (props === null || props === void 0 ? void 0 : props.type) || 0, | ||
}, | ||
}; | ||
}; | ||
const patch = (rootVNode, app = {}, keys) => { | ||
let firstRender = false; | ||
const state = app.state || {}; | ||
if (!rootVNode) | ||
return; | ||
if (!keys) | ||
keys = Object.keys(state); | ||
if (keys[0] === LUCIA_FIRST_RENDER) | ||
firstRender = true; | ||
for (let node of rootVNode.children) { | ||
if (typeof node === 'string') | ||
continue; | ||
if (node.props.type > VNodeTypes.STATIC) { | ||
const { attributes, directives, ref, type } = node.props; | ||
let affectedDirectives = []; | ||
if (!firstRender) { | ||
for (const name in directives) { | ||
const needsInit = type === 1; | ||
const hasKey = keys.some((key) => keyPattern(key).test(String(directives[name].value))); | ||
const hasKeyInFunction = Object.keys(state).some((key) => { | ||
const iterKeysInFunction = keys.some((k) => keyPattern(k).test(String(state[key]))); | ||
return typeof state[key] === 'function' && iterKeysInFunction; | ||
}); | ||
if (needsInit || hasKey || hasKeyInFunction) { | ||
affectedDirectives.push(name); | ||
} | ||
} | ||
} | ||
node.props.type = type === VNodeTypes.NEEDS_PATCH ? VNodeTypes.STATIC : type; | ||
const directivesToRender = firstRender | ||
? Object.keys(directives) | ||
: affectedDirectives; | ||
directivesToRender.map((name) => { | ||
const data = directives[name]; | ||
const el = (attributes.id ? document.getElementById(attributes.id) : ref); | ||
renderDirective({ el, name, data, app }, Object.assign({}, app.directives)); | ||
}); | ||
} | ||
if (node.children.length > 0) | ||
patch(node, state, keys); | ||
} | ||
}; | ||
const props = (el) => { | ||
const attributes = {}; | ||
const directives = {}; | ||
if (el.attributes) { | ||
for (const { name, value } of [...el.attributes]) { | ||
let returnable = true; | ||
if (name.includes('for') && el.__l_for === undefined) { | ||
el.__l_for = String(el.innerHTML).trim(); | ||
returnable = false; | ||
} | ||
if (/on|@/.test(name)) | ||
returnable = false; | ||
const directiveData = { compute: compute(value, { $el: el }, returnable), value }; | ||
if (name.startsWith(DIRECTIVE_PREFIX)) { | ||
directives[name.slice(DIRECTIVE_PREFIX.length)] = directiveData; | ||
} | ||
else if (Object.keys(DIRECTIVE_SHORTHANDS).includes(name[0])) { | ||
directives[`${DIRECTIVE_SHORTHANDS[name[0]]}:${name.slice(1)}`] = directiveData; | ||
} | ||
else { | ||
attributes[name] = value; | ||
} | ||
} | ||
} | ||
return { attributes, directives }; | ||
}; | ||
class App { | ||
constructor(state = {}, mountHook) { | ||
this.state = state; | ||
this.directives = {}; | ||
this.components = {}; | ||
this.mountHook = mountHook; | ||
} | ||
mount(el, shallow = false) { | ||
const rootEl = typeof el === 'string' ? document.querySelector(el) : el; | ||
this.vdom = this.compile(rootEl); | ||
if (!shallow) { | ||
this.state = reactive(this.state, this.patch.bind(this)); | ||
this.directives = Object.assign(Object.assign({}, this.directives), directives); | ||
} | ||
this.patch([LUCIA_FIRST_RENDER]); | ||
if (this.mountHook) | ||
this.mountHook(this.state); | ||
return this.state; | ||
} | ||
component(name, templateCallback) { | ||
this.components[name.toUpperCase()] = templateCallback; | ||
} | ||
directive(name, evaluationCallback) { | ||
this.directives[name.toUpperCase()] = evaluationCallback; | ||
} | ||
patch(keys) { | ||
const app = { | ||
state: this.state, | ||
directives: this.directives, | ||
components: this.components, | ||
}; | ||
patch(this.vdom, app, keys); | ||
} | ||
compile(el) { | ||
return compile(el, this.state, this.components, true); | ||
} | ||
} | ||
const createApp = (state, mountHook) => { | ||
return new App(state, mountHook); | ||
}; | ||
const createVNode = (el, state, children) => { | ||
const { attributes, directives } = props(el); | ||
let type = VNodeTypes.STATIC; | ||
const hasDirectives = Object.keys(directives).length > 0; | ||
const hasKeyInDirectives = Object.values(directives).some(({ value }) => Object.keys(state).some((key) => expressionPropRE(key, false).test(value))); | ||
if (hasDirectives) | ||
type = VNodeTypes.NEEDS_PATCH; | ||
if (hasKeyInDirectives) | ||
type = VNodeTypes.DYNAMIC; | ||
return h(el.tagName.toLowerCase(), children, { | ||
attributes: attributes, | ||
directives: directives, | ||
ref: type === VNodeTypes.STATIC || attributes.id ? undefined : el, | ||
type, | ||
}); | ||
}; | ||
const compile = (el, state = {}, components = {}, strip = false, callSelf = false) => { | ||
var _a; | ||
if (!el) | ||
throw new Error('Please provide a Element'); | ||
const children = []; | ||
const childNodes = Array.prototype.slice.call(el.childNodes); | ||
for (const child of childNodes) { | ||
switch (child.nodeType) { | ||
case Node.TEXT_NODE: | ||
if (!strip && child.nodeValue) { | ||
children.push(child.nodeValue); | ||
} | ||
break; | ||
case Node.ELEMENT_NODE: | ||
if (Object.keys(components).includes(child.tagName)) { | ||
const container = document.createElement('div'); | ||
const template = components[child.tagName]({ | ||
children: child.innerHTML, | ||
state, | ||
}); | ||
container.innerHTML = template; | ||
for (const [key, data] of Object.entries(props(child).directives)) { | ||
(_a = container.firstElementChild) === null || _a === void 0 ? void 0 : _a.setAttribute(`${DIRECTIVE_PREFIX}${key}`, data.value); | ||
} | ||
if (!strip || hasDirectiveRE().test(container.outerHTML)) { | ||
const compiledChildren = compile(container, state, components, strip, true); | ||
for (const componentChild of compiledChildren) { | ||
children.push(componentChild); | ||
} | ||
} | ||
el.replaceChild(container.firstElementChild, child); | ||
} | ||
else { | ||
if (!strip || hasDirectiveRE().test(child.outerHTML)) { | ||
const compiledChildren = compile(child, state, components, strip, true); | ||
const node = createVNode(child, state, compiledChildren); | ||
children.push(node); | ||
} | ||
} | ||
break; | ||
} | ||
} | ||
if (callSelf) { | ||
return children; | ||
} | ||
else { | ||
let vnode = createVNode(el, state, children); | ||
return strip ? flat(vnode) : vnode; | ||
} | ||
}; | ||
const flat = (vdom) => { | ||
const flattenedVDom = Object.assign({}, vdom); | ||
flattenedVDom.children = flattenedVDom.children.filter((child) => typeof child === 'object' && child.props.type > 0); | ||
for (const child of vdom.children) { | ||
if (typeof child === 'string') | ||
continue; | ||
if (child.children.length > 0) { | ||
flattenedVDom.children = [ | ||
...flattenedVDom.children, | ||
...flat({ children: child.children }).children, | ||
]; | ||
child.children = []; | ||
} | ||
} | ||
return flattenedVDom; | ||
}; | ||
const stateDirective = `${DIRECTIVE_PREFIX}state`; | ||
const init = (element = document) => { | ||
const elements = [...element.querySelectorAll(`[${stateDirective}]`)]; | ||
elements | ||
.filter((el) => el.__l === undefined) | ||
.map((el) => { | ||
const expression = el.getAttribute(stateDirective); | ||
try { | ||
const state = new Function(`return ${expression}`)(); | ||
const app = createApp(state); | ||
app.mount(el); | ||
el.__l = app; | ||
} | ||
catch (err) { | ||
console.warn(`Lucia Error: "${err}"\n\nExpression: "${expression}"\nElement:`, el); | ||
} | ||
}); | ||
}; | ||
const listen = (callback, element = document, config) => { | ||
const observer = new MutationObserver((mutations) => { | ||
mutations.map((mut) => { | ||
if (mut.addedNodes.length > 0) { | ||
mut.addedNodes.forEach((node) => { | ||
if (node.nodeType !== 1) | ||
return; | ||
if (node.parentElement && node.parentElement.closest(`[${stateDirective}]`)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}); | ||
}; | ||
const arrayEquals = (firstArray, secondArray) => { | ||
return (firstArray instanceof Array && | ||
secondArray instanceof Array && | ||
firstArray.length === secondArray.length && | ||
firstArray.every((value, i) => value === secondArray[i])); | ||
}; | ||
var Lucia = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
createApp: createApp, | ||
h: h, | ||
compile: compile, | ||
patch: patch, | ||
reactive: reactive, | ||
directives: directives, | ||
renderDirective: renderDirective, | ||
init: init, | ||
listen: listen | ||
}); | ||
const handlePatch = (target, key, state, patch, needsUpdate = false) => { | ||
if (key === 'length') { | ||
const affectedKeys = Object.keys(state).filter((k) => { | ||
return state[k] instanceof Array && arrayEquals(target, state[k]); | ||
}); | ||
if (affectedKeys.length !== 0) | ||
patch(affectedKeys); | ||
return true; | ||
} | ||
else { | ||
if (needsUpdate) | ||
patch([key]); | ||
return false; | ||
} | ||
}; | ||
const reactive = (state, patch) => { | ||
const handler = { | ||
get(target, key) { | ||
if (typeof target[key] === 'object' && target[key] !== null) { | ||
return new Proxy(target[key], handler); | ||
} | ||
else { | ||
return target[key]; | ||
} | ||
}, | ||
set(target, key, value) { | ||
const needsUpdate = target[key] !== value; | ||
if (needsUpdate) { | ||
target[key] = value; | ||
} | ||
handlePatch(target, key, state, patch, needsUpdate); | ||
return true; | ||
}, | ||
deleteProperty(target, key) { | ||
delete target[key]; | ||
handlePatch(target, key, state, patch, true); | ||
return true; | ||
}, | ||
}; | ||
return new Proxy(state, handler); | ||
}; | ||
document.addEventListener('DOMContentLoaded', () => init()); | ||
document.addEventListener('turbolinks:load', () => init()); | ||
listen((el) => init(el)); | ||
const patch = (rootVNode, app = {}, keys) => { | ||
let firstRender = false; | ||
const state = app.state || {}; | ||
if (!rootVNode) | ||
return; | ||
if (!keys) | ||
keys = Object.keys(state); | ||
if (keys[0] === LUCIA_FIRST_RENDER) | ||
firstRender = true; | ||
for (let node of rootVNode.children) { | ||
if (typeof node === 'string') | ||
continue; | ||
if (node.props.type > VNodeTypes.STATIC) { | ||
const { attributes, directives, ref, type } = node.props; | ||
let affectedDirectives = []; | ||
if (!firstRender) { | ||
for (const name in directives) { | ||
const needsInit = type === 1; | ||
const hasKey = keys.some((key) => expressionPropRE(key).test(String(directives[name].value))); | ||
const hasKeyInFunction = Object.keys(state).some((key) => { | ||
const iterKeysInFunction = keys.some((k) => expressionPropRE(k).test(String(state[key]))); | ||
return typeof state[key] === 'function' && iterKeysInFunction; | ||
}); | ||
if (needsInit || hasKey || hasKeyInFunction) { | ||
affectedDirectives.push(name); | ||
} | ||
} | ||
} | ||
node.props.type = type === VNodeTypes.NEEDS_PATCH ? VNodeTypes.STATIC : type; | ||
const directivesToRender = firstRender | ||
? Object.keys(directives) | ||
: affectedDirectives; | ||
directivesToRender.map((name) => { | ||
const data = directives[name]; | ||
const el = (attributes.id ? document.getElementById(attributes.id) : ref); | ||
renderDirective({ el, name, data, app }, Object.assign({}, app.directives)); | ||
}); | ||
} | ||
if (node.children.length > 0) | ||
patch(node, app, keys); | ||
} | ||
}; | ||
return Lucia; | ||
class App { | ||
constructor(state = {}, mountHook) { | ||
this.state = state; | ||
this.directives = {}; | ||
this.components = {}; | ||
this.mountHook = mountHook; | ||
} | ||
mount(el, shallow = false) { | ||
const rootEl = typeof el === 'string' ? document.querySelector(el) : el; | ||
this.vdom = this.compile(rootEl); | ||
if (!shallow) { | ||
this.state = reactive(this.state, this.patch.bind(this)); | ||
this.directives = Object.assign(Object.assign({}, this.directives), directives); | ||
} | ||
this.patch([LUCIA_FIRST_RENDER]); | ||
if (this.mountHook) | ||
this.mountHook(this.state); | ||
return this.state; | ||
} | ||
component(name, templateCallback) { | ||
this.components[name.toUpperCase()] = templateCallback; | ||
} | ||
directive(name, evaluationCallback) { | ||
this.directives[name.toUpperCase()] = evaluationCallback; | ||
} | ||
patch(keys) { | ||
const app = { | ||
state: this.state, | ||
directives: this.directives, | ||
components: this.components, | ||
}; | ||
patch(this.vdom, app, keys); | ||
} | ||
compile(el) { | ||
return compile(el, this.state, this.components, true); | ||
} | ||
} | ||
const createApp = (state, mountHook) => { | ||
return new App(state, mountHook); | ||
}; | ||
const stateDirective = `${DIRECTIVE_PREFIX}state`; | ||
const init = (element = document) => { | ||
const elements = [...element.querySelectorAll(`[${stateDirective}]`)]; | ||
elements | ||
.filter((el) => el.__l === undefined) | ||
.map((el) => { | ||
const expression = el.getAttribute(stateDirective); | ||
try { | ||
const state = new Function(`return ${expression}`)(); | ||
const app = createApp(state); | ||
app.mount(el); | ||
el.__l = app; | ||
} | ||
catch (err) { | ||
console.warn(`Lucia Error: "${err}"\n\nExpression: "${expression}"\nElement:`, el); | ||
} | ||
}); | ||
}; | ||
const listen = (callback, element = document, config) => { | ||
const observer = new MutationObserver((mutations) => { | ||
mutations.map((mut) => { | ||
if (mut.addedNodes.length > 0) { | ||
mut.addedNodes.forEach((node) => { | ||
if (node.nodeType !== 1) | ||
return; | ||
if (node.parentElement && node.parentElement.closest(`[${stateDirective}]`)) | ||
return; | ||
if (!node.getAttribute(stateDirective)) | ||
return; | ||
callback(node.parentElement); | ||
}); | ||
} | ||
else if (mut.type === 'attributes') { | ||
if (mut.target.parentElement && mut.target.parentElement.closest(`[${stateDirective}]`)) | ||
return; | ||
callback(mut.target.parentElement); | ||
} | ||
}); | ||
}); | ||
observer.observe(element, config || { | ||
childList: true, | ||
attributes: true, | ||
subtree: true, | ||
}); | ||
}; | ||
var Lucia = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
createApp: createApp, | ||
h: h, | ||
compile: compile, | ||
patch: patch, | ||
reactive: reactive, | ||
directives: directives, | ||
renderDirective: renderDirective, | ||
init: init, | ||
listen: listen | ||
}); | ||
const DOMReady = () => { | ||
return new Promise((resolve) => { | ||
if (document.readyState === 'loading') { | ||
document.addEventListener('DOMContentLoaded', resolve); | ||
} | ||
else { | ||
resolve(); | ||
} | ||
}); | ||
}; | ||
const start = () => __awaiter(void 0, void 0, void 0, function* () { | ||
yield DOMReady(); | ||
init(); | ||
document.addEventListener('turbolinks:load', () => init()); | ||
listen((el) => init(el)); | ||
}); | ||
if (window.__l) { | ||
window.__l(() => start()); | ||
} | ||
else { | ||
start(); | ||
} | ||
return Lucia; | ||
}))); |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Lucia=t()}(this,(function(){"use strict";const e="l-",t="%LUCIA_FIRST_RENDER%";var s;!function(e){e["@"]="on",e[":"]="bind"}(s||(s={}));const n=/:|\./,i=(e,t=!0)=>new RegExp(`${t?"this\\.":""}${e}\\b`);function o(e){try{const t=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),t).bind(e)(...Object.values(this.argsKV))}catch(e){console.warn(`Lucia Error: "${e}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const r=(e,t,s=!0)=>o.bind({expression:e,argsKV:{$el:t.$el},returnable:s}),a={BIND:({el:e,name:t,data:s,app:n})=>{switch(t.split(":")[1]){case"class":const i=s.compute(n.state);if("string"==typeof i)return e.setAttribute("class",`${e.className} ${i}`.trim());if(i instanceof Array)return e.setAttribute("class",`${e.className} ${i.join(" ")}`.trim());{const t=[];for(const e in i)i[e]&&t.push(e);return t.length>0?e.setAttribute("class",`${e.className} ${t.join(" ").trim()}`.trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class")}case"style":const o=s.compute(n.state);e.removeAttribute("style");for(const t in o)e.style[t]=o[t];break;default:const r=s.compute(n.state);if("object"==typeof r&&null!==r)for(const t in r)r[t]?e.setAttribute(t,r[t]):e.removeAttribute(t);else r?e.setAttribute(t.split(":")[1],r):e.removeAttribute(t.split(":")[1])}},JOIN:({el:e,data:t,app:s})=>{const[n,i,o]=t.value.split(/ as | by /),a=r(n,{$el:e})(s.state);e["text"===i?"innerText":"innerHTML"]=a.join(o||"");const c=g(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{c.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{c.component(e,t)})),c.mount(e)},HTML:({el:e,data:t,app:s})=>{var n;e.innerHTML=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value;const i=g(Object.assign({},s.state));Object.entries(s.directives||{}).map((([e,t])=>{i.directive(e,t)})),Object.entries(s.components||{}).map((([e,t])=>{i.component(e,t)})),i.mount(e)},IF:({el:e,data:t,app:s})=>{t.compute(s.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:({el:e,data:t,app:s})=>{const n=e,i=t.compute(s.state);n.value!==i&&(n.value=i),n.oninput=()=>{const e="number"==typeof i&&!isNaN(n.value),o="boolean"==typeof i&&("true"===n.value||"false"===n.value),a=null==i&&("null"===n.value||"undefined"===n.value);let c;c=e?`Number('${n.value}').toPrecision()`:o?`Boolean('${n.value}')`:a?"null"===n.value?null:void 0:`'${n.value}'`,r(`${t.value} = ${c}`,{$el:n},!1)(s.state)}},ON:({el:e,name:t,data:s,app:n})=>{const[i,o]=t.split("."),r=i.split(":")[1],a=o||null;e[`on${r}`]=e=>{"prevent"===a&&e.preventDefault(),"stop"===a&&e.stopPropagation(),s.compute(n.state)}},TEXT:({el:e,data:t,app:s})=>{var n;e.textContent=null!==(n=t.compute(s.state))&&void 0!==n?n:t.value}},c=(e,t)=>{t[e.name.split(n)[0].toUpperCase()](e)};var l;!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(l||(l={}));const u=(e,t=[],s)=>{const n=Object.assign({},null==s?void 0:s.attributes),i=Object.assign({},null==s?void 0:s.directives);return t=t instanceof Array?t:[t],n.className&&(n.className=n.className.trim()),{tag:e,children:t,props:{attributes:n,directives:i,ref:(null==s?void 0:s.ref)||void 0,type:(null==s?void 0:s.type)||0}}},p=t=>{const n={},i={};if(t.attributes)for(const{name:o,value:a}of[...t.attributes]){const c={compute:r(a,{$el:t}),value:a};o.startsWith(e)?i[o.slice(e.length)]=c:Object.keys(s).includes(o[0])?i[`${s[o[0]]}:${o.slice(1)}`]=c:n[o]=a}return{attributes:n,directives:i}},d=(e,t,s)=>{const{attributes:n,directives:o}=p(e);let r=l.STATIC;const a=Object.keys(o).length>0,c=Object.values(o).some((({value:e})=>Object.keys(t).some((t=>i(t,!1).test(e)))));return a&&(r=l.NEEDS_PATCH),c&&(r=l.DYNAMIC),u(e.tagName.toLowerCase(),s,{attributes:n,directives:o,ref:r===l.STATIC||n.id?void 0:e,type:r})},m=(e,t={},s={},n=!1,i=!1)=>{var o;if(!e)throw new Error("Please provide a Element");const r=[],a=Array.prototype.slice.call(e.childNodes);for(const i of a)switch(i.nodeType){case Node.TEXT_NODE:!n&&i.nodeValue&&r.push(i.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(s).includes(i.tagName)){const a=document.createElement("div"),c=s[i.tagName]({children:i.innerHTML,state:t});a.innerHTML=c;for(const[e,t]of Object.entries(p(i).directives))null===(o=a.firstElementChild)||void 0===o||o.setAttribute(`l-${e}`,t.value);if(!n||a.outerHTML.includes(" l-")){const e=m(a,t,s,n,!0);for(const t of e)r.push(t)}e.replaceChild(a.firstElementChild,i)}else if(!n||i.outerHTML.includes(" l-")){const e=m(i,t,s,n,!0),o=d(i,t,e);r.push(o)}}if(i)return r;{let s=d(e,t,r);return n?f(s):s}},f=e=>{const t=Object.assign({},e);t.children.filter((e=>"object"==typeof e&&e.props.type>0));for(const s of e.children)if("string"!=typeof s&&s.children.length>0)for(const e of f(s).children)"string"!=typeof e&&0!==e.props.type&&t.children.push(e);return t},h=(e,t,s,n,i=!1)=>{if("length"===t){const t=Object.keys(s).filter((t=>{return s[t]instanceof Array&&(n=e,i=s[t],n instanceof Array&&i instanceof Array&&n.length===i.length&&n.every(((e,t)=>e===i[t])));var n,i}));return 0!==t.length&&n(t),!0}return i&&n([t]),!1},v=(e,t)=>{const s={get:(e,t)=>"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],s):e[t],set(s,n,i){const o=s[n]!==i;return o&&(s[n]=i),h(s,n,e,t,o),!0},deleteProperty:(s,n)=>(delete s[n],h(s,n,e,t),!0)};return new Proxy(e,s)},b=(e,s={},n)=>{let o=!1;const r=s.state||{};if(e){n||(n=Object.keys(r)),n[0]===t&&(o=!0);for(let t of e.children)if("string"!=typeof t){if(t.props.type>l.STATIC){const{attributes:e,directives:a,ref:u,type:p}=t.props;let d=[];if(!o)for(const e in a){const t=1===p,s=n.some((t=>i(t).test(String(a[e].value)))),o=Object.keys(r).some((e=>{const t=n.some((t=>i(t).test(String(r[e]))));return"function"==typeof r[e]&&t}));(t||s||o)&&d.push(e)}t.props.type=p===l.NEEDS_PATCH?l.STATIC:p;(o?Object.keys(a):d).map((t=>{const n=a[t],i=e.id?document.getElementById(e.id):u;c({el:i,name:t,data:n,app:s},Object.assign({},s.directives))}))}t.children.length>0&&b(t,r,n)}}};class y{constructor(e={},t){this.state=e,this.directives={},this.components={},this.mountHook=t}mount(e,s=!1){const n="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(n),s||(this.state=v(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),a)),this.patch([t]),this.mountHook&&this.mountHook(this.state),this.state}component(e,t){this.components[e.toUpperCase()]=t}directive(e,t){this.directives[e.toUpperCase()]=t}patch(e){const t={state:this.state,directives:this.directives,components:this.components};b(this.vdom,t,e)}compile(e){return m(e,this.state,this.components,!0)}}const g=(e,t)=>new y(e,t),E="l-state",A=(e=document)=>{[...e.querySelectorAll("[l-state]")].filter((e=>void 0===e.__l)).map((e=>{const t=e.getAttribute(E);try{const s=new Function(`return ${t}`)(),n=g(s);n.mount(e),e.__l=n}catch(s){console.warn(`Lucia Error: "${s}"\n\nExpression: "${t}"\nElement:`,e)}}))},T=(e,t=document,s)=>{const n=new MutationObserver((i=>{i.map((t=>{t.addedNodes.length>0&&t.addedNodes.forEach((t=>{1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||e(t.parentElement))}))})),n.observe(t,s||{childList:!0,attributes:!0,subtree:!0})}))};var N=Object.freeze({__proto__:null,createApp:g,h:u,compile:m,patch:b,reactive:v,directives:a,renderDirective:c,init:A,listen:T});return document.addEventListener("DOMContentLoaded",(()=>A())),document.addEventListener("turbolinks:load",(()=>A())),T((e=>A(e))),N})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).Lucia=t()}(this,(function(){"use strict";function e(e,t,n,s){return new(n||(n=Promise))((function(i,r){function o(e){try{c(s.next(e))}catch(e){r(e)}}function a(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,a)}c((s=s.apply(e,t||[])).next())}))}const t="l-",n="%LUCIA_FIRST_RENDER%";var s;!function(e){e["@"]="on",e[":"]="bind"}(s||(s={}));const i=()=>new RegExp(`(l-|${Object.keys(s).join("|")})\\w+`,"gim"),r=(e,t=!0)=>new RegExp(`${t?"this\\.":""}${e}\\b`);function o(e){try{const t=this.returnable?`return ${this.expression}`:this.expression;return new Function(...Object.keys(this.argsKV),t).bind(e)(...Object.values(this.argsKV))}catch(e){console.warn(`Lucia Error: "${e}"\n\nExpression: "${this.expression}"\nElement:`,this.argsKV.$el)}}const a=(e,t,n=!0)=>o.bind({expression:e,argsKV:{$el:t.$el},returnable:n}),c={BIND:({el:e,name:t,data:n,app:s})=>{switch(t.split(":")[1]){case"class":const i=n.compute(s.state);if("string"==typeof i)return e.setAttribute("class",`${e.className} ${i}`.trim());if(i instanceof Array)return e.setAttribute("class",`${e.className} ${i.join(" ")}`.trim());{const t=[];for(const e in i)i[e]&&t.push(e);return t.length>0?e.setAttribute("class",`${e.className} ${t.join(" ").trim()}`.trim()):e.className.trim().length>0?e.setAttribute("class",e.className):e.removeAttribute("class")}case"style":const r=n.compute(s.state);e.removeAttribute("style");for(const t in r)e.style[t]=r[t];break;default:const o=n.compute(s.state);if("object"==typeof o&&null!==o)for(const t in o)o[t]?e.setAttribute(t,o[t]):e.removeAttribute(t);else o?e.setAttribute(t.split(":")[1],o):e.removeAttribute(t.split(":")[1])}},HTML:({el:e,data:t,app:n})=>{var s;e.innerHTML=null!==(s=t.compute(n.state))&&void 0!==s?s:t.value;const i=E(Object.assign({},n.state));Object.entries(n.directives||{}).map((([e,t])=>{i.directive(e,t)})),Object.entries(n.components||{}).map((([e,t])=>{i.component(e,t)})),i.mount(e)},IF:({el:e,data:t,app:n})=>{t.compute(n.state)?e.style.removeProperty("display"):e.style.display="none"},MODEL:({el:e,data:t,app:n})=>{const s=e,i=t.compute(n.state);s.value!==i&&(s.value=i),s.oninput=()=>((e,t,n,s)=>{const i="number"==typeof t&&!isNaN(e.value),r="boolean"==typeof t&&("true"===e.value||"false"===e.value),o=null==t&&("null"===e.value||"undefined"===e.value);let c;return c=i?`Number('${e.value}').toPrecision()`:r?`Boolean('${e.value}')`:o?"null"===e.value?null:void 0:`'${e.value}'`,a(`${n.value} = ${c}`,{$el:e},!1)(s.state),c})(s,i,t,n)},ON:({el:e,name:t,data:n,app:s})=>{const[i,r]=t.split("."),o=i.split(":")[1],a=r||null;e[`on${o}`]=e=>{"prevent"===a&&e.preventDefault(),"stop"===a&&e.stopPropagation(),n.compute(s.state)}},TEXT:({el:e,data:t,app:n})=>{var s;e.textContent=null!==(s=t.compute(n.state))&&void 0!==s?s:t.value},FOR:({el:e,data:t,app:n})=>{const[s,i]=t.value.split(/ +in +/g),[r,o]=s.split(","),c=a(i,{$el:e})(n.state),l=String(e.__l_for);if(l){let t="";for(let e=0;e<c.length;e++){let n=l;r&&(n=n.replace(new RegExp(`this.${r.trim()}`,"g"),`${i}[${e}]`)),o&&(n=n.replace(new RegExp(`this.${o.trim()}`,"g"),String(e))),t+=n}e.innerHTML=t}else e.innerHTML=c.join("");const u=E(Object.assign({},n.state));Object.entries(n.directives||{}).map((([e,t])=>{u.directive(e,t)})),Object.entries(n.components||{}).map((([e,t])=>{u.component(e,t)})),u.mount(e)}},l=(e,t)=>{t[e.name.split(/:|\./)[0].toUpperCase()](e)};var u;!function(e){e[e.STATIC=0]="STATIC",e[e.NEEDS_PATCH=1]="NEEDS_PATCH",e[e.DYNAMIC=2]="DYNAMIC"}(u||(u={}));const p=(e,t=[],n)=>{const s=Object.assign({},null==n?void 0:n.attributes),i=Object.assign({},null==n?void 0:n.directives);return t=t instanceof Array?t:[t],s.className&&(s.className=s.className.trim()),{tag:e,children:t,props:{attributes:s,directives:i,ref:(null==n?void 0:n.ref)||void 0,type:(null==n?void 0:n.type)||0}}},d=e=>{const n={},i={};if(e.attributes)for(const{name:r,value:o}of[...e.attributes]){let c=!0;r.includes("for")&&void 0===e.__l_for&&(e.__l_for=String(e.innerHTML).trim(),c=!1),/on|@/.test(r)&&(c=!1);const l={compute:a(o,{$el:e},c),value:o};r.startsWith(t)?i[r.slice(t.length)]=l:Object.keys(s).includes(r[0])?i[`${s[r[0]]}:${r.slice(1)}`]=l:n[r]=o}return{attributes:n,directives:i}},m=(e,t,n)=>{const{attributes:s,directives:i}=d(e);let o=u.STATIC;const a=Object.keys(i).length>0,c=Object.values(i).some((({value:e})=>Object.keys(t).some((t=>r(t,!1).test(e)))));return a&&(o=u.NEEDS_PATCH),c&&(o=u.DYNAMIC),p(e.tagName.toLowerCase(),n,{attributes:s,directives:i,ref:o===u.STATIC||s.id?void 0:e,type:o})},f=(e,t={},n={},s=!1,r=!1)=>{var o;if(!e)throw new Error("Please provide a Element");const a=[],c=Array.prototype.slice.call(e.childNodes);for(const r of c)switch(r.nodeType){case Node.TEXT_NODE:!s&&r.nodeValue&&a.push(r.nodeValue);break;case Node.ELEMENT_NODE:if(Object.keys(n).includes(r.tagName)){const c=document.createElement("div"),l=n[r.tagName]({children:r.innerHTML,state:t});c.innerHTML=l;for(const[e,t]of Object.entries(d(r).directives))null===(o=c.firstElementChild)||void 0===o||o.setAttribute(`l-${e}`,t.value);if(!s||i().test(c.outerHTML)){const e=f(c,t,n,s,!0);for(const t of e)a.push(t)}e.replaceChild(c.firstElementChild,r)}else if(!s||i().test(r.outerHTML)){const e=f(r,t,n,s,!0),i=m(r,t,e);a.push(i)}}if(r)return a;{let n=m(e,t,a);return s?h(n):n}},h=e=>{const t=Object.assign({},e);t.children=t.children.filter((e=>"object"==typeof e&&e.props.type>0));for(const n of e.children)"string"!=typeof n&&n.children.length>0&&(t.children=[...t.children,...h({children:n.children}).children],n.children=[]);return t},v=(e,t,n,s,i=!1)=>{if("length"===t){const t=Object.keys(n).filter((t=>{return n[t]instanceof Array&&(s=e,i=n[t],s instanceof Array&&i instanceof Array&&s.length===i.length&&s.every(((e,t)=>e===i[t])));var s,i}));return 0!==t.length&&s(t),!0}return i&&s([t]),!1},b=(e,t)=>{const n={get:(e,t)=>"object"==typeof e[t]&&null!==e[t]?new Proxy(e[t],n):e[t],set(n,s,i){const r=n[s]!==i;return r&&(n[s]=i),v(n,s,e,t,r),!0},deleteProperty:(n,s)=>(delete n[s],v(n,s,e,t,!0),!0)};return new Proxy(e,n)},y=(e,t={},s)=>{let i=!1;const o=t.state||{};if(e){s||(s=Object.keys(o)),s[0]===n&&(i=!0);for(let n of e.children)if("string"!=typeof n){if(n.props.type>u.STATIC){const{attributes:e,directives:a,ref:c,type:p}=n.props;let d=[];if(!i)for(const e in a){const t=1===p,n=s.some((t=>r(t).test(String(a[e].value)))),i=Object.keys(o).some((e=>{const t=s.some((t=>r(t).test(String(o[e]))));return"function"==typeof o[e]&&t}));(t||n||i)&&d.push(e)}n.props.type=p===u.NEEDS_PATCH?u.STATIC:p;(i?Object.keys(a):d).map((n=>{const s=a[n],i=e.id?document.getElementById(e.id):c;l({el:i,name:n,data:s,app:t},Object.assign({},t.directives))}))}n.children.length>0&&y(n,t,s)}}};class g{constructor(e={},t){this.state=e,this.directives={},this.components={},this.mountHook=t}mount(e,t=!1){const s="string"==typeof e?document.querySelector(e):e;return this.vdom=this.compile(s),t||(this.state=b(this.state,this.patch.bind(this)),this.directives=Object.assign(Object.assign({},this.directives),c)),this.patch([n]),this.mountHook&&this.mountHook(this.state),this.state}component(e,t){this.components[e.toUpperCase()]=t}directive(e,t){this.directives[e.toUpperCase()]=t}patch(e){const t={state:this.state,directives:this.directives,components:this.components};y(this.vdom,t,e)}compile(e){return f(e,this.state,this.components,!0)}}const E=(e,t)=>new g(e,t),A="l-state",T=(e=document)=>{[...e.querySelectorAll("[l-state]")].filter((e=>void 0===e.__l)).map((e=>{const t=e.getAttribute(A);try{const n=new Function(`return ${t}`)(),s=E(n);s.mount(e),e.__l=s}catch(n){console.warn(`Lucia Error: "${n}"\n\nExpression: "${t}"\nElement:`,e)}}))},j=(e,t=document,n)=>{new MutationObserver((t=>{t.map((t=>{if(t.addedNodes.length>0)t.addedNodes.forEach((t=>{1===t.nodeType&&(t.parentElement&&t.parentElement.closest("[l-state]")||t.getAttribute(A)&&e(t.parentElement))}));else if("attributes"===t.type){if(t.target.parentElement&&t.target.parentElement.closest("[l-state]"))return;e(t.target.parentElement)}}))})).observe(t,n||{childList:!0,attributes:!0,subtree:!0})};var $=Object.freeze({__proto__:null,createApp:E,h:p,compile:f,patch:y,reactive:b,directives:c,renderDirective:l,init:T,listen:j});const O=()=>e(void 0,void 0,void 0,(function*(){yield new Promise((e=>{"loading"===document.readyState?document.addEventListener("DOMContentLoaded",e):e()})),T(),document.addEventListener("turbolinks:load",(()=>T())),j((e=>T(e)))}));return window.__l?window.__l((()=>O())):O(),$})); |
@@ -13,6 +13,6 @@ import { Directives, Components, State } from './models/structs'; | ||
directive(name: string, evaluationCallback: Function): void; | ||
private patch; | ||
private compile; | ||
patch(this: App, keys?: string[]): void; | ||
compile(el: HTMLElement): VNode; | ||
} | ||
export declare const createApp: (state: State, mountHook?: Function | undefined) => App; | ||
export default createApp; |
@@ -1,2 +0,3 @@ | ||
import { DirectiveProps } from '../../models/structs'; | ||
import { DirectiveProps, DirectiveData, DirectiveApp } from '../../models/structs'; | ||
export declare const inputCallback: (el: HTMLInputElement, hydratedValue: unknown, data: DirectiveData, app: DirectiveApp) => string | null | undefined; | ||
export declare const modelDirective: ({ el: awaitingTypecastEl, data, app }: DirectiveProps) => void; |
@@ -1,2 +0,3 @@ | ||
export declare const rawDirectiveSplitPattern: RegExp; | ||
export declare const keyPattern: (key: string, hasThis?: boolean) => RegExp; | ||
export declare const rawDirectiveSplitRE: () => RegExp; | ||
export declare const hasDirectiveRE: () => RegExp; | ||
export declare const expressionPropRE: (key: string, hasThis?: boolean) => RegExp; |
{ | ||
"name": "lucia", | ||
"version": "0.3.7-0", | ||
"version": "0.3.7", | ||
"description": "A tiny 3kb JavaScript library for prototyping web applications.", | ||
@@ -10,3 +10,3 @@ "main": "dist/lucia.cjs.js", | ||
"scripts": { | ||
"dev": "del-cli dist/ && rollup -c -w", | ||
"dev": "rollup -c -w", | ||
"build": "del-cli dist/ && rollup -c", | ||
@@ -13,0 +13,0 @@ "test": "jest --coverage", |
@@ -60,2 +60,3 @@ # <a href="http://lucia.js.org"><img src="https://raw.githubusercontent.com/aidenybai/lucia/master/.github/img/logo.svg" height="60" alt="Lucia Logo" aria-label="http://lucia.js.org" /></a> | ||
- [Mavo](https://github.com/mavoweb/mavo) - Create web applications entirely by writing HTML and CSS! | ||
- [htmx](https://github.com/bigskysoftware/htmx) - High power tools for HTML. | ||
@@ -62,0 +63,0 @@ ## π§βπ€βπ§ Contributing |
223531
38
3956
76