Comparing version 1.5.0 to 1.6.0
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Alpine=t()}(this,(function(){"use strict";function e(){return navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")}function t(e,i,n=!0){if(e.hasAttribute("x-data")&&!n)return;i(e);let s=e.firstElementChild;for(;s;)t(s,i,!1),s=s.nextElementSibling}function i(e,t,i={}){return new Function(["$data",...Object.keys(i)],`var result; with($data) { result = ${e} }; return result`)(t,...Object.values(i))}function n(e,t,i={}){return new Function(["$data",...Object.keys(i)],`with($data) { ${e} }`)(t,...Object.values(i))}function s(e){const t=r(e.name);return/x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/.test(t)}function a(e,t){return Array.from(e.attributes).filter(s).map(e=>{const t=r(e.name),i=t.match(/x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/),n=t.match(/:([a-zA-Z\-]+)/),s=t.match(/\.[^.\]]+(?=[^\]]*$)/g)||[];return{type:i?i[1]:null,value:n?n[1]:null,modifiers:s.map(e=>e.replace(".","")),expression:e.value}}).filter(e=>!t||e.type===t)}function r(e){return e.startsWith("@")?e.replace("@","x-on:"):e.startsWith(":")?e.replace(":","x-bind:"):e}function o(e,t,i=!1){i&&t();const n=a(e,"transition");n.length<1&&t(),u(e,(n.find(e=>"enter"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"enter-start"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"enter-end"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),t,()=>{})}function l(e,t,i=!1){i&&t();const n=a(e,"transition");n.length<1&&t(),u(e,(n.find(e=>"leave"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"leave-start"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"leave-end"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),()=>{},t)}function u(e,t,i,n,s,a){e.classList.add(...i),e.classList.add(...t),requestAnimationFrame(()=>{const r=1e3*Number(getComputedStyle(e).transitionDuration.replace("s",""));s(),requestAnimationFrame(()=>{e.classList.remove(...i),e.classList.add(...n),setTimeout(()=>{a(),e.isConnected&&(e.classList.remove(...t),e.classList.remove(...n))},r)})})}class c{constructor(e){this.el=e,this.tickStack=[],this.collectingTickCallbacks=!1;const t=i(this.el.getAttribute("x-data"),{});t.$refs=this.getRefsProxy(),t.$nextTick=e=>{this.delayRunByATick(e)},this.runXInit(this.el.getAttribute("x-init"),t),this.data=this.wrapDataInObservable(t),this.initializeElements(),this.listenForNewElementsToInitialize()}delayRunByATick(e){this.collectingTickCallbacks?this.tickStack.push(e):e()}startTick(){this.collectingTickCallbacks=!0}clearAndEndTick(){this.tickStack.forEach(e=>e()),this.tickStack=[],this.collectingTickCallbacks=!1}runXInit(e,t){e&&n(e,t)}wrapDataInObservable(e){this.concernedData=[];var t=this;const i=e=>({set(i,n,s){const a=e?`${e}.${n}`:n,r=Reflect.set(i,n,s);return-1===t.concernedData.indexOf(a)&&t.concernedData.push(a),t.refresh(),r},get(t,n){if("isProxy"===n)return!0;if(t[n]&&t[n].isProxy)return t[n];if("object"==typeof t[n]&&null!==t[n]){const s=e?`${e}.${n}`:n;return new Proxy(t[n],i(s))}return t[n]}});return new Proxy(e,i())}initializeElements(){t(this.el,e=>{this.initializeElement(e)})}initializeElement(e){a(e).forEach(({type:t,value:i,modifiers:n,expression:s})=>{switch(t){case"on":var a=i;this.registerListener(e,a,n,s);break;case"model":a="select"===e.tagName.toLowerCase()||["checkbox","radio"].includes(e.type)||n.includes("lazy")?"change":"input";const t=this.generateExpressionForXModelListener(e,n,s);this.registerListener(e,a,n,t);var r="value",{output:o}=this.evaluateReturnExpression(s);this.updateAttributeValue(e,r,o);break;case"bind":r=i;var{output:o}=this.evaluateReturnExpression(s);this.updateAttributeValue(e,r,o);break;case"text":var{output:o}=this.evaluateReturnExpression(s);this.updateTextValue(e,o);break;case"html":var{output:o}=this.evaluateReturnExpression(s);this.updateHtmlValue(e,o);break;case"show":var{output:o}=this.evaluateReturnExpression(s);this.updateVisibility(e,o,!0);break;case"if":var{output:o}=this.evaluateReturnExpression(s);this.updatePresence(e,o);break;case"cloak":e.removeAttribute("x-cloak")}})}listenForNewElementsToInitialize(){const e=this.el;new MutationObserver(e=>{for(let t=0;t<e.length;t++){if(!e[t].target.closest("[x-data]").isSameNode(this.el))return;if("attributes"===e[t].type&&"x-data"===e[t].attributeName){const n=i(e[t].target.getAttribute("x-data"),{});Object.keys(n).forEach(e=>{this.data[e]!==n[e]&&(this.data[e]=n[e])})}e[t].addedNodes.length>0&&e[t].addedNodes.forEach(e=>{1===e.nodeType&&(e.matches("[x-data]")||a(e).length>0&&this.initializeElement(e))})}}).observe(e,{childList:!0,attributes:!0,subtree:!0})}refresh(){var e=this;const i={model:({el:t,output:i})=>{e.updateAttributeValue(t,"value",i)},bind:({el:t,attrName:i,output:n})=>{e.updateAttributeValue(t,i,n)},text:({el:t,output:i})=>{e.updateTextValue(t,i)},html:({el:t,output:i})=>{e.updateHtmlValue(t,i)},show:({el:t,output:i})=>{e.updateVisibility(t,i)},if:({el:t,output:i})=>{e.updatePresence(t,i)}};var n,s,r,o;this.startTick(),(n=(i,n)=>{t(i,n),e.concernedData=[],e.clearAndEndTick()},s=5,function(){var e=this,t=arguments,i=function(){o=null,r||n.apply(e,t)},a=r&&!o;clearTimeout(o),o=setTimeout(i,s),a&&n.apply(e,t)})(this.el,(function(t){a(t).forEach(({type:n,value:s,expression:a})=>{if(i[n]){var{output:r,deps:o}=e.evaluateReturnExpression(a);e.concernedData.filter(e=>o.includes(e)).length>0&&i[n]({el:t,attrName:s,output:r})}})}))}generateExpressionForXModelListener(e,t,i){var n="";return n="checkbox"===e.type?Array.isArray(this.data[i])?`$event.target.checked ? ${i}.concat([$event.target.value]) : ${i}.filter(i => i !== $event.target.value)`:"$event.target.checked":"select"===e.tagName.toLowerCase()&&e.multiple?t.includes("number")?"Array.from($event.target.selectedOptions).map(option => { return parseFloat(option.value || option.text) })":"Array.from($event.target.selectedOptions).map(option => { return option.value || option.text })":t.includes("number")?"parseFloat($event.target.value)":t.includes("trim")?"$event.target.value.trim()":"$event.target.value","radio"===e.type&&(e.hasAttribute("name")||e.setAttribute("name",i)),`${i} = ${n}`}registerListener(e,t,i,n){if(i.includes("away")){const s=a=>{e.contains(a.target)||e.offsetWidth<1&&e.offsetHeight<1||(this.runListenerHandler(n,a),i.includes("once")&&document.removeEventListener(t,s))};document.addEventListener(t,s)}else{const s=i.includes("window")?window:i.includes("document")?document:e,a=e=>{const r=i.filter(e=>"window"!==e).filter(e=>"document"!==e);"keydown"===t&&r.length>0&&!r.includes(e.key.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]/,"-").toLowerCase())||(i.includes("prevent")&&e.preventDefault(),i.includes("stop")&&e.stopPropagation(),this.runListenerHandler(n,e),i.includes("once")&&s.removeEventListener(t,a))};s.addEventListener(t,a)}}runListenerHandler(e,t){this.evaluateCommandExpression(e,{$event:t})}evaluateReturnExpression(e){var t=[];const n=e=>({get(i,s){if("symbol"==typeof s)return;const a=e?`${e}.${s}`:s;return"object"!=typeof i[s]||null===i[s]||Array.isArray(i[s])?(t.push(a),i[s]):new Proxy(i[s],n(a))}});return{output:i(e,new Proxy(this.data,n())),deps:t}}evaluateCommandExpression(e,t){n(e,this.data,t)}updateTextValue(e,t){e.innerText=t}updateHtmlValue(e,t){e.innerHTML=t}updateVisibility(e,t,i=!1){t?o(e,()=>{1===e.style.length&&""!==e.style.display?e.removeAttribute("style"):e.style.removeProperty("display")},i):l(e,()=>{e.style.display="none"},i)}updatePresence(e,t){"template"!==e.nodeName.toLowerCase()&&console.warn("Alpine: [x-if] directive should only be added to <template> tags.");const i=e.nextElementSibling&&!0===e.nextElementSibling.__x_inserted_me;if(t&&!i){const t=document.importNode(e.content,!0);e.parentElement.insertBefore(t,e.nextElementSibling),e.nextElementSibling.__x_inserted_me=!0,o(e.nextElementSibling,()=>{})}else!t&&i&&l(e.nextElementSibling,()=>{e.nextElementSibling.remove()})}updateAttributeValue(e,t,i){if("value"===t)if("radio"===e.type)e.checked=e.value==i;else if("checkbox"===e.type)if(Array.isArray(i)){let t=!1;i.forEach(i=>{i==e.value&&(t=!0)}),e.checked=t}else e.checked=!!i;else"SELECT"===e.tagName?this.updateSelect(e,i):e.value=i;else"class"===t?"string"==typeof i?e.setAttribute("class",i):Array.isArray(i)?e.setAttribute("class",i.join(" ")):Object.keys(i).forEach(t=>{i[t]?t.split(" ").forEach(t=>e.classList.add(t)):t.split(" ").forEach(t=>e.classList.remove(t))}):["disabled","readonly","required","checked","hidden"].includes(t)?i?e.setAttribute(t,""):e.removeAttribute(t):e.setAttribute(t,i)}updateSelect(e,t){const i=[].concat(t).map(e=>e+"");Array.from(e.options).forEach(e=>{e.selected=i.includes(e.value||e.text)})}getRefsProxy(){var e=this;return new Proxy({},{get(i,n){return"isProxy"===n||(t(e.el,e=>{e.hasAttribute("x-ref")&&e.getAttribute("x-ref")===n&&(s=e)}),s);var s}})}}const d={start:async function(){e()||await new Promise(e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",e):e()}),this.discoverComponents(e=>{this.initializeComponent(e)}),document.addEventListener("turbolinks:load",()=>{this.discoverUninitializedComponents(e=>{this.initializeComponent(e)})}),this.listenForNewUninitializedComponentsAtRunTime(e=>{this.initializeComponent(e)})},discoverComponents:function(e){document.querySelectorAll("[x-data]").forEach(t=>{e(t)})},discoverUninitializedComponents:function(e){const t=document.querySelectorAll("[x-data]");Array.from(t).filter(e=>void 0===e.__x).forEach(t=>{e(t)})},listenForNewUninitializedComponentsAtRunTime:function(e){const t=document.querySelector("body");new MutationObserver(t=>{for(let i=0;i<t.length;i++)t[i].addedNodes.length>0&&t[i].addedNodes.forEach(t=>{1===t.nodeType&&t.matches("[x-data]")&&e(t)})}).observe(t,{childList:!0,attributes:!0,subtree:!0})},initializeComponent:function(e){e.__x=new c(e)}};return e()||(window.Alpine=d,window.Alpine.start()),d})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Alpine=t()}(this,(function(){"use strict";function e(){return navigator.userAgent.includes("Node.js")||navigator.userAgent.includes("jsdom")}function t(e,i,n=!0){if(e.hasAttribute("x-data")&&!n)return;i(e);let s=e.firstElementChild;for(;s;)t(s,i,!1),s=s.nextElementSibling}function i(e,t,i={}){return new Function(["$data",...Object.keys(i)],`var result; with($data) { result = ${e} }; return result`)(t,...Object.values(i))}function n(e,t,i={}){return new Function(["dataContext",...Object.keys(i)],`with(dataContext) { ${e} }`)(t,...Object.values(i))}function s(e){const t=r(e.name);return/x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/.test(t)}function a(e,t){return Array.from(e.attributes).filter(s).map(e=>{const t=r(e.name),i=t.match(/x-(on|bind|data|text|html|model|if|show|cloak|transition|ref)/),n=t.match(/:([a-zA-Z\-]+)/),s=t.match(/\.[^.\]]+(?=[^\]]*$)/g)||[];return{type:i?i[1]:null,value:n?n[1]:null,modifiers:s.map(e=>e.replace(".","")),expression:e.value}}).filter(e=>!t||e.type===t)}function r(e){return e.startsWith("@")?e.replace("@","x-on:"):e.startsWith(":")?e.replace(":","x-bind:"):e}function o(e,t,i=!1){i&&t();const n=a(e,"transition");n.length<1&&t(),u(e,(n.find(e=>"enter"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"enter-start"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"enter-end"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),t,()=>{})}function l(e,t,i=!1){i&&t();const n=a(e,"transition");n.length<1&&t(),u(e,(n.find(e=>"leave"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"leave-start"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),(n.find(e=>"leave-end"===e.value)||{expression:""}).expression.split(" ").filter(e=>""!==e),()=>{},t)}function u(e,t,i,n,s,a){e.classList.add(...i),e.classList.add(...t),requestAnimationFrame(()=>{const r=1e3*Number(getComputedStyle(e).transitionDuration.replace("s",""));s(),requestAnimationFrame(()=>{e.classList.remove(...i),e.classList.add(...n),setTimeout(()=>{a(),e.isConnected&&(e.classList.remove(...t),e.classList.remove(...n))},r)})})}class c{constructor(e){this.$el=e;const t=this.$el.getAttribute("x-data"),s=""===t?"{}":t,a=this.$el.getAttribute("x-created"),r=this.$el.getAttribute("x-mounted"),o=i(s,{});this.$data=this.wrapDataInObservable(o),Object.keys(o).forEach(e=>{"function"==typeof o[e]&&(o[e]=o[e].bind(this.$data))}),o.$el=this.$el,o.$refs=this.getRefsProxy(),o.$nextTick=e=>{this.delayRunByATick(e)},this.tickStack=[],this.collectingTickCallbacks=!1,a&&(this.pauseReactivity=!0,n(this.$el.getAttribute("x-created"),this.$data),this.pauseReactivity=!1),this.initializeElements(),this.listenForNewElementsToInitialize(),r&&n(r,this.$data)}wrapDataInObservable(e){this.concernedData=[];var t=this;const i=e=>({set(i,n,s){const a=e?`${e}.${n}`:n,r=Reflect.set(i,n,s);if(!t.pauseReactivity)return-1===t.concernedData.indexOf(a)&&t.concernedData.push(a),t.refresh(),r},get(t,n){if("isProxy"===n)return!0;if(t[n]&&t[n].isProxy)return t[n];if("object"==typeof t[n]&&null!==t[n]){const s=e?`${e}.${n}`:n;return new Proxy(t[n],i(s))}return t[n]}});return new Proxy(e,i())}delayRunByATick(e){this.collectingTickCallbacks?this.tickStack.push(e):e()}startTick(){this.collectingTickCallbacks=!0}clearAndEndTick(){this.tickStack.forEach(e=>e()),this.tickStack=[],this.collectingTickCallbacks=!1}initializeElements(){t(this.$el,e=>{this.initializeElement(e)})}initializeElement(e){a(e).forEach(({type:t,value:i,modifiers:n,expression:s})=>{switch(t){case"on":var a=i;this.registerListener(e,a,n,s);break;case"model":a="select"===e.tagName.toLowerCase()||["checkbox","radio"].includes(e.type)||n.includes("lazy")?"change":"input";const t=this.generateExpressionForXModelListener(e,n,s);this.registerListener(e,a,n,t);var r="value",{output:o}=this.evaluateReturnExpression(s);this.updateAttributeValue(e,r,o);break;case"bind":r=i;var{output:o}=this.evaluateReturnExpression(s);this.updateAttributeValue(e,r,o);break;case"text":var{output:o}=this.evaluateReturnExpression(s);this.updateTextValue(e,o);break;case"html":var{output:o}=this.evaluateReturnExpression(s);this.updateHtmlValue(e,o);break;case"show":var{output:o}=this.evaluateReturnExpression(s);this.updateVisibility(e,o,!0);break;case"if":var{output:o}=this.evaluateReturnExpression(s);this.updatePresence(e,o);break;case"cloak":e.removeAttribute("x-cloak")}})}listenForNewElementsToInitialize(){const e=this.$el;new MutationObserver(e=>{for(let t=0;t<e.length;t++){if(!e[t].target.closest("[x-data]").isSameNode(this.$el))return;if("attributes"===e[t].type&&"x-data"===e[t].attributeName){const n=i(e[t].target.getAttribute("x-data"),{});Object.keys(n).forEach(e=>{this.$data[e]!==n[e]&&(this.$data[e]=n[e])})}e[t].addedNodes.length>0&&e[t].addedNodes.forEach(e=>{1===e.nodeType&&(e.matches("[x-data]")||a(e).length>0&&this.initializeElement(e))})}}).observe(e,{childList:!0,attributes:!0,subtree:!0})}refresh(){var e=this;const i={model:({el:t,output:i})=>{e.updateAttributeValue(t,"value",i)},bind:({el:t,attrName:i,output:n})=>{e.updateAttributeValue(t,i,n)},text:({el:t,output:i})=>{e.updateTextValue(t,i)},html:({el:t,output:i})=>{e.updateHtmlValue(t,i)},show:({el:t,output:i})=>{e.updateVisibility(t,i)},if:({el:t,output:i})=>{e.updatePresence(t,i)}};var n,s,r,o;this.startTick(),(n=(i,n)=>{t(i,n),e.concernedData=[],e.clearAndEndTick()},s=5,function(){var e=this,t=arguments,i=function(){o=null,r||n.apply(e,t)},a=r&&!o;clearTimeout(o),o=setTimeout(i,s),a&&n.apply(e,t)})(this.$el,(function(t){a(t).forEach(({type:n,value:s,expression:a})=>{if(i[n]){var{output:r,deps:o}=e.evaluateReturnExpression(a);e.concernedData.filter(e=>o.includes(e)).length>0&&i[n]({el:t,attrName:s,output:r})}})}))}generateExpressionForXModelListener(e,t,i){var n="";return n="checkbox"===e.type?Array.isArray(this.$data[i])?`$event.target.checked ? ${i}.concat([$event.target.value]) : ${i}.filter(i => i !== $event.target.value)`:"$event.target.checked":"select"===e.tagName.toLowerCase()&&e.multiple?t.includes("number")?"Array.from($event.target.selectedOptions).map(option => { return parseFloat(option.value || option.text) })":"Array.from($event.target.selectedOptions).map(option => { return option.value || option.text })":t.includes("number")?"parseFloat($event.target.value)":t.includes("trim")?"$event.target.value.trim()":"$event.target.value","radio"===e.type&&(e.hasAttribute("name")||e.setAttribute("name",i)),`${i} = ${n}`}registerListener(e,t,i,n){if(i.includes("away")){const s=a=>{e.contains(a.target)||e.offsetWidth<1&&e.offsetHeight<1||(this.runListenerHandler(n,a),i.includes("once")&&document.removeEventListener(t,s))};document.addEventListener(t,s)}else{const s=i.includes("window")?window:i.includes("document")?document:e,a=e=>{const r=i.filter(e=>"window"!==e).filter(e=>"document"!==e);"keydown"===t&&r.length>0&&!r.includes(e.key.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]/,"-").toLowerCase())||(i.includes("prevent")&&e.preventDefault(),i.includes("stop")&&e.stopPropagation(),this.runListenerHandler(n,e),i.includes("once")&&s.removeEventListener(t,a))};s.addEventListener(t,a)}}runListenerHandler(e,t){this.evaluateCommandExpression(e,{$event:t})}evaluateReturnExpression(e){var t=[];const n=e=>({get(i,s){if("symbol"==typeof s)return;const a=e?`${e}.${s}`:s;return"object"!=typeof i[s]||null===i[s]||Array.isArray(i[s])?(t.push(a),i[s]):new Proxy(i[s],n(a))}});return{output:i(e,new Proxy(this.$data,n())),deps:t}}evaluateCommandExpression(e,t){n(e,this.$data,t)}updateTextValue(e,t){e.innerText=t}updateHtmlValue(e,t){e.innerHTML=t}updateVisibility(e,t,i=!1){t?o(e,()=>{1===e.style.length&&""!==e.style.display?e.removeAttribute("style"):e.style.removeProperty("display")},i):l(e,()=>{e.style.display="none"},i)}updatePresence(e,t){"template"!==e.nodeName.toLowerCase()&&console.warn("Alpine: [x-if] directive should only be added to <template> tags.");const i=e.nextElementSibling&&!0===e.nextElementSibling.__x_inserted_me;if(t&&!i){const t=document.importNode(e.content,!0);e.parentElement.insertBefore(t,e.nextElementSibling),e.nextElementSibling.__x_inserted_me=!0,o(e.nextElementSibling,()=>{})}else!t&&i&&l(e.nextElementSibling,()=>{e.nextElementSibling.remove()})}updateAttributeValue(e,t,i){if("value"===t)if("radio"===e.type)e.checked=e.value==i;else if("checkbox"===e.type)if(Array.isArray(i)){let t=!1;i.forEach(i=>{i==e.value&&(t=!0)}),e.checked=t}else e.checked=!!i;else"SELECT"===e.tagName?this.updateSelect(e,i):e.value=i;else"class"===t?"string"==typeof i?e.setAttribute("class",i):Array.isArray(i)?e.setAttribute("class",i.join(" ")):Object.keys(i).forEach(t=>{i[t]?t.split(" ").forEach(t=>e.classList.add(t)):t.split(" ").forEach(t=>e.classList.remove(t))}):["disabled","readonly","required","checked","hidden"].includes(t)?i?e.setAttribute(t,""):e.removeAttribute(t):e.setAttribute(t,i)}updateSelect(e,t){const i=[].concat(t).map(e=>e+"");Array.from(e.options).forEach(e=>{e.selected=i.includes(e.value||e.text)})}getRefsProxy(){var e=this;return new Proxy({},{get(i,n){return"isProxy"===n||(t(e.$el,e=>{e.hasAttribute("x-ref")&&e.getAttribute("x-ref")===n&&(s=e)}),s);var s}})}}const d={start:async function(){e()||await new Promise(e=>{"loading"==document.readyState?document.addEventListener("DOMContentLoaded",e):e()}),this.discoverComponents(e=>{this.initializeComponent(e)}),document.addEventListener("turbolinks:load",()=>{this.discoverUninitializedComponents(e=>{this.initializeComponent(e)})}),this.listenForNewUninitializedComponentsAtRunTime(e=>{this.initializeComponent(e)})},discoverComponents:function(e){document.querySelectorAll("[x-data]").forEach(t=>{e(t)})},discoverUninitializedComponents:function(e){const t=document.querySelectorAll("[x-data]");Array.from(t).filter(e=>void 0===e.__x).forEach(t=>{e(t)})},listenForNewUninitializedComponentsAtRunTime:function(e){const t=document.querySelector("body");new MutationObserver(t=>{for(let i=0;i<t.length;i++)t[i].addedNodes.length>0&&t[i].addedNodes.forEach(t=>{1===t.nodeType&&t.matches("[x-data]")&&e(t)})}).observe(t,{childList:!0,attributes:!0,subtree:!0})},initializeComponent:function(e){e.__x=new c(e)}};return e()||(window.Alpine=d,window.Alpine.start()),d})); | ||
//# sourceMappingURL=alpine.js.map |
{ | ||
"main": "dist/alpine.js", | ||
"name": "alpinejs", | ||
"version": "1.5.0", | ||
"version": "1.6.0", | ||
"repository": { | ||
@@ -6,0 +6,0 @@ "type": "git", |
@@ -17,3 +17,3 @@ # Alpine.js | ||
```html | ||
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v1.4.0/dist/alpine.js" defer></script> | ||
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v1.6.0/dist/alpine.js" defer></script> | ||
``` | ||
@@ -45,7 +45,7 @@ | ||
<div x-data="{ open: false }"> | ||
<button x-on:click="open = true">Open Dropdown</button> | ||
<button @click="open = true">Open Dropdown</button> | ||
<ul | ||
x-show="open" | ||
x-on:click.away="open = false" | ||
@click.away="open = false" | ||
> | ||
@@ -60,4 +60,4 @@ Dropdown Body | ||
<div x-data="{ tab: 'foo' }"> | ||
<button x-bind:class="{ 'active': tab === 'foo' }" x-on:click="tab = 'foo'">Foo</button> | ||
<button x-bind:class="{ 'active': tab === 'bar' }" x-on:click="tab = 'bar'">Bar</button> | ||
<button :class="{ 'active': tab === 'foo' }" @click="tab = 'foo'">Foo</button> | ||
<button :class="{ 'active': tab === 'bar' }" @click="tab = 'bar'">Bar</button> | ||
@@ -74,3 +74,3 @@ <div x-show="tab === 'foo'">Tab Foo</div> | ||
<button | ||
x-on:mouseenter.once=" | ||
@mouseenter.once=" | ||
fetch('/dropdown-partial.html') | ||
@@ -80,6 +80,6 @@ .then(response => response.text()) | ||
" | ||
x-on:click="open = true" | ||
@click="open = true" | ||
>Show Dropdown</button> | ||
<div x-ref="dropdown" x-show="open" x-on:click.away="open = false"> | ||
<div x-ref="dropdown" x-show="open" @click.away="open = false"> | ||
Loading Spinner... | ||
@@ -92,3 +92,3 @@ </div> | ||
There are 12 directives available to you: | ||
There are 13 directives available to you: | ||
@@ -98,3 +98,4 @@ | Directive | ||
| [`x-data`](#x-data) | | ||
| [`x-init`](#x-init) | | ||
| [`x-created`](#x-created) | | ||
| [`x-mounted`](#x-mounted) | | ||
| [`x-show`](#x-show) | | ||
@@ -111,6 +112,7 @@ | [`x-bind`](#x-bind) | | ||
And 2 magic objects/functions: | ||
And 3 magic properties: | ||
| Magic Object/Functions | ||
| Magic Properties | ||
| --- | | ||
| [`$el`](#el) | | ||
| [`$refs`](#refs) | | ||
@@ -166,11 +168,20 @@ | [`$nextTick`](#nexttick) | | ||
### `x-init` | ||
**Example:** `<div x-data"{ foo: 'bar' }" x-init="foo = 'baz"></div>` | ||
### `x-created` | ||
**Example:** `<div x-data"{ foo: 'bar' }" x-created="foo = 'baz"></div>` | ||
**Structure:** `<div x-data="..." x-init="[expression]"></div>` | ||
**Structure:** `<div x-data="..." x-created="[expression]"></div>` | ||
`x-init` runs an expression (with the initial data object in scope) when a component is initialized. | ||
`x-created` runs an expression when a component is initialized, but BEFORE the component initializes the DOM. | ||
--- | ||
### `x-mounted` | ||
**Example:** `<div x-data"{ foo: 'bar' }" x-mounted="foo = 'baz"></div>` | ||
**Structure:** `<div x-data="..." x-mounted="[expression]"></div>` | ||
`x-mounted` runs an expression when a component is initialized, and AFTER the component initializes the DOM. | ||
--- | ||
### `x-show` | ||
@@ -186,2 +197,5 @@ **Example:** `<div x-show="open"></div>` | ||
### `x-bind` | ||
> Note: You are free to use the shorter ":" syntax: `:type="..."` | ||
**Example:** `<input x-bind:type="inputType">` | ||
@@ -221,2 +235,4 @@ | ||
> Note: You are free to use the shorter "@" syntax: `@click="..."` | ||
**Example:** `<button x-on:click="foo = 'bar'"></button>` | ||
@@ -376,6 +392,16 @@ | ||
### Magic Objects/Functions | ||
### Magic Properties | ||
--- | ||
### `$el` | ||
**Example:** | ||
```html | ||
<div x-data> | ||
<button @click="$el.innerHTML = 'foo'">Replace me with "foo"</button> | ||
</div> | ||
``` | ||
`$el` is a magic property that can be used to retreive the root component DOM node. | ||
### `$refs` | ||
@@ -389,3 +415,3 @@ **Example:** | ||
`$refs` is a magic object that can be used to retreive DOM elements marked with `x-ref` inside the component. This is useful when you need to manually manipulate DOM elements. | ||
`$refs` is a magic property that can be used to retreive DOM elements marked with `x-ref` inside the component. This is useful when you need to manually manipulate DOM elements. | ||
@@ -408,2 +434,2 @@ --- | ||
`$nextTick` is a magic function that allows you to only execute a given expression AFTER Alpine has made it's reactive DOM updates. This is useful for times you want to interact with the DOM state AFTER it's reflected any data updates you've made. | ||
`$nextTick` is a magic property that allows you to only execute a given expression AFTER Alpine has made it's reactive DOM updates. This is useful for times you want to interact with the DOM state AFTER it's reflected any data updates you've made. |
@@ -5,48 +5,56 @@ import { walkSkippingNestedComponents, kebabCase, saferEval, saferEvalNoReturn, getXAttrs, debounce, transitionIn, transitionOut } from './utils' | ||
constructor(el) { | ||
this.el = el | ||
this.$el = el | ||
// For $nextTick(). | ||
this.tickStack = [] | ||
this.collectingTickCallbacks = false | ||
const dataAttr = this.$el.getAttribute('x-data') | ||
const dataExpression = dataAttr === '' ? '{}' : dataAttr | ||
const createdExpression = this.$el.getAttribute('x-created') | ||
const mountedExpression = this.$el.getAttribute('x-mounted') | ||
const rawData = saferEval(this.el.getAttribute('x-data'), {}) | ||
const unobservedData = saferEval(dataExpression, {}) | ||
rawData.$refs = this.getRefsProxy() | ||
// Construct a Proxy-based observable. This will be used to handle reactivity. | ||
this.$data = this.wrapDataInObservable(unobservedData) | ||
rawData.$nextTick = (callback) => { | ||
// Walk through the raw data and set the "this" context of any functions | ||
// to the observable, so data manipulations are reactive. | ||
Object.keys(unobservedData).forEach(key => { | ||
if (typeof unobservedData[key] === 'function') { | ||
unobservedData[key] = unobservedData[key].bind(this.$data) | ||
} | ||
}) | ||
// After making user-supplied data methods reactive, we can now add | ||
// our magic properties to the original data for access. | ||
unobservedData.$el = this.$el | ||
unobservedData.$refs = this.getRefsProxy() | ||
unobservedData.$nextTick = (callback) => { | ||
this.delayRunByATick(callback) | ||
} | ||
this.runXInit(this.el.getAttribute('x-init'), rawData) | ||
// For $nextTick(). | ||
this.tickStack = [] | ||
this.collectingTickCallbacks = false | ||
this.data = this.wrapDataInObservable(rawData) | ||
if (createdExpression) { | ||
// We want to allow data manipulation, but not trigger DOM updates just yet. | ||
// We haven't even initialized the elements with their Alpine bindings. I mean c'mon. | ||
this.pauseReactivity = true | ||
saferEvalNoReturn(this.$el.getAttribute('x-created'), this.$data) | ||
this.pauseReactivity = false | ||
} | ||
// Register all our listeners and set all our attribute bindings. | ||
this.initializeElements() | ||
// Use mutation observer to detect new elements being added within this component at run-time. | ||
// Alpine's just so darn flexible amirite? | ||
this.listenForNewElementsToInitialize() | ||
} | ||
delayRunByATick(callback) { | ||
if (this.collectingTickCallbacks) { | ||
this.tickStack.push(callback) | ||
} else { | ||
callback() | ||
if (mountedExpression) { | ||
// Run an "x-mounted" hook to allow the user to do stuff after | ||
// Alpine's got it's grubby little paws all over everything. | ||
saferEvalNoReturn(mountedExpression, this.$data) | ||
} | ||
} | ||
startTick() { | ||
this.collectingTickCallbacks = true | ||
} | ||
clearAndEndTick() { | ||
this.tickStack.forEach(callable => callable()) | ||
this.tickStack = [] | ||
this.collectingTickCallbacks = false | ||
} | ||
runXInit(initExpression, rawData) { | ||
initExpression && saferEvalNoReturn(initExpression, rawData) | ||
} | ||
wrapDataInObservable(data) { | ||
@@ -63,2 +71,5 @@ this.concernedData = [] | ||
// Don't react to data changes for cases like the `x-created` hook. | ||
if (self.pauseReactivity) return | ||
if (self.concernedData.indexOf(propertyName) === -1) { | ||
@@ -73,7 +84,10 @@ self.concernedData.push(propertyName) | ||
get(target, key) { | ||
// This is because there is no way to do something like `typeof foo === 'Proxy'`. | ||
if (key === 'isProxy') return true | ||
// If the property we are trying to get is a proxy, just return it. | ||
// Like in the case of $refs | ||
if (target[key] && target[key].isProxy) return target[key] | ||
// If accessing a nested property, retur this proxy recursively. | ||
if (typeof target[key] === 'object' && target[key] !== null) { | ||
@@ -85,2 +99,3 @@ const propertyName = keyPrefix ? `${keyPrefix}.${key}` : key | ||
// If none of the above, just return the flippin' value. Gawsh. | ||
return target[key] | ||
@@ -93,4 +108,23 @@ } | ||
delayRunByATick(callback) { | ||
if (this.collectingTickCallbacks) { | ||
this.tickStack.push(callback) | ||
} else { | ||
callback() | ||
} | ||
} | ||
startTick() { | ||
this.collectingTickCallbacks = true | ||
} | ||
clearAndEndTick() { | ||
this.tickStack.forEach(callable => callable()) | ||
this.tickStack = [] | ||
this.collectingTickCallbacks = false | ||
} | ||
initializeElements() { | ||
walkSkippingNestedComponents(this.el, el => { | ||
walkSkippingNestedComponents(this.$el, el => { | ||
this.initializeElement(el) | ||
@@ -162,3 +196,3 @@ }) | ||
listenForNewElementsToInitialize() { | ||
const targetNode = this.el | ||
const targetNode = this.$el | ||
@@ -174,3 +208,3 @@ const observerOptions = { | ||
// Filter out mutations triggered from child components. | ||
if (! mutations[i].target.closest('[x-data]').isSameNode(this.el)) return | ||
if (! mutations[i].target.closest('[x-data]').isSameNode(this.$el)) return | ||
@@ -181,4 +215,4 @@ if (mutations[i].type === 'attributes' && mutations[i].attributeName === 'x-data') { | ||
Object.keys(rawData).forEach(key => { | ||
if (this.data[key] !== rawData[key]) { | ||
this.data[key] = rawData[key] | ||
if (this.$data[key] !== rawData[key]) { | ||
this.$data[key] = rawData[key] | ||
} | ||
@@ -226,3 +260,3 @@ }) | ||
debounce(walkThenClearDependancyTracker, 5)(this.el, function (el) { | ||
debounce(walkThenClearDependancyTracker, 5)(this.$el, function (el) { | ||
getXAttrs(el).forEach(({ type, value, expression }) => { | ||
@@ -244,3 +278,3 @@ if (! actionByDirectiveType[type]) return | ||
// If the data we are binding to is an array, toggle it's value inside the array. | ||
if (Array.isArray(this.data[dataKey])) { | ||
if (Array.isArray(this.$data[dataKey])) { | ||
rightSideOfExpression = `$event.target.checked ? ${dataKey}.concat([$event.target.value]) : ${dataKey}.filter(i => i !== $event.target.value)` | ||
@@ -343,3 +377,3 @@ } else { | ||
const proxiedData = new Proxy(this.data, proxyHandler()) | ||
const proxiedData = new Proxy(this.$data, proxyHandler()) | ||
@@ -355,3 +389,3 @@ const result = saferEval(expression, proxiedData) | ||
evaluateCommandExpression(expression, extraData) { | ||
saferEvalNoReturn(expression, this.data, extraData) | ||
saferEvalNoReturn(expression, this.$data, extraData) | ||
} | ||
@@ -381,3 +415,2 @@ | ||
} | ||
} | ||
@@ -480,3 +513,3 @@ | ||
// nested components. | ||
walkSkippingNestedComponents(self.el, el => { | ||
walkSkippingNestedComponents(self.$el, el => { | ||
if (el.hasAttribute('x-ref') && el.getAttribute('x-ref') === property) { | ||
@@ -483,0 +516,0 @@ ref = el |
@@ -63,3 +63,3 @@ | ||
export function saferEvalNoReturn(expression, dataContext, additionalHelperVariables = {}) { | ||
return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `with($data) { ${expression} }`))( | ||
return (new Function(['dataContext', ...Object.keys(additionalHelperVariables)], `with(dataContext) { ${expression} }`))( | ||
dataContext, ...Object.values(additionalHelperVariables) | ||
@@ -66,0 +66,0 @@ ) |
@@ -17,5 +17,17 @@ import Alpine from 'alpinejs' | ||
document.querySelector('div').__x.data.foo = 'baz' | ||
document.querySelector('div').__x.$data.foo = 'baz' | ||
await wait(() => { expect(document.querySelector('span').innerText).toEqual('baz') }) | ||
}) | ||
test('x-data attribute value is optional', async () => { | ||
document.body.innerHTML = ` | ||
<div x-data> | ||
<span x-text="'foo'"></span> | ||
</div> | ||
` | ||
Alpine.start() | ||
expect(document.querySelector('span').innerText).toEqual('foo') | ||
}) |
@@ -61,3 +61,3 @@ import Alpine from 'alpinejs' | ||
await wait(() => { expect(document.querySelector('[x-data]').__x.data.foo).toEqual(123) }) | ||
await wait(() => { expect(document.querySelector('[x-data]').__x.$data.foo).toEqual(123) }) | ||
}) | ||
@@ -64,0 +64,0 @@ |
@@ -57,3 +57,3 @@ import Alpine from 'alpinejs' | ||
expect(document.querySelector('div').__x.data.foo).toEqual('bar') | ||
expect(document.querySelector('div').__x.$data.foo).toEqual('bar') | ||
@@ -63,3 +63,3 @@ document.querySelector('span').click() | ||
await wait(() => { | ||
expect(document.querySelector('div').__x.data.foo).toEqual('baz') | ||
expect(document.querySelector('div').__x.$data.foo).toEqual('baz') | ||
}) | ||
@@ -66,0 +66,0 @@ }) |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
148637
33
1769
422