From 491624004ab6cb8f82c9ba04cdcb5db3573cac40 Mon Sep 17 00:00:00 2001 From: Adam Weston Date: Sun, 17 Dec 2023 16:54:57 -0500 Subject: [PATCH 1/3] Fix: Destory existing element tree on reinitialization --- dist/async-alpine.cjs.js | 1 + dist/async-alpine.esm.js | 1 + dist/async-alpine.script.js | 2 +- package-lock.json | 4 +- src/core/async-alpine.js | 90 +++++++++++++++++++++---------------- 5 files changed, 57 insertions(+), 41 deletions(-) diff --git a/dist/async-alpine.cjs.js b/dist/async-alpine.cjs.js index 77909d0..6921e90 100644 --- a/dist/async-alpine.cjs.js +++ b/dist/async-alpine.cjs.js @@ -288,6 +288,7 @@ var AsyncAlpine = { return whichExport; }, _activate(component) { + this.Alpine.destroyTree(component.el); component.el.removeAttribute(`${this._options.alpinePrefix}ignore`); component.el._x_ignore = false; this.Alpine.initTree(component.el); diff --git a/dist/async-alpine.esm.js b/dist/async-alpine.esm.js index 6d29c5b..47c4b3b 100644 --- a/dist/async-alpine.esm.js +++ b/dist/async-alpine.esm.js @@ -283,6 +283,7 @@ var AsyncAlpine = { return whichExport; }, _activate(component) { + this.Alpine.destroyTree(component.el); component.el.removeAttribute(`${this._options.alpinePrefix}ignore`); component.el._x_ignore = false; this.Alpine.initTree(component.el); diff --git a/dist/async-alpine.script.js b/dist/async-alpine.script.js index 835ede2..5a2581f 100644 --- a/dist/async-alpine.script.js +++ b/dist/async-alpine.script.js @@ -1 +1 @@ -(()=>{var d=Object.defineProperty;var y=e=>d(e,"__esModule",{value:!0});var v=(e,t)=>{y(e);for(var i in t)d(e,i,{get:t[i],enumerable:!0})};var a={};v(a,{eager:()=>h,event:()=>f,idle:()=>c,media:()=>_,visible:()=>m});var A=()=>!0,h=A;var b=({component:e,argument:t})=>new Promise(i=>{if(t)window.addEventListener(t,()=>i(),{once:!0});else{let s=n=>{n.detail.id===e.id&&(window.removeEventListener("async-alpine:load",s),i())};window.addEventListener("async-alpine:load",s)}}),f=b;var $=()=>new Promise(e=>{"requestIdleCallback"in window?window.requestIdleCallback(e):setTimeout(e,200)}),c=$;var E=({argument:e})=>new Promise(t=>{if(!e)return console.log("Async Alpine: media strategy requires a media query. Treating as 'eager'"),t();let i=window.matchMedia(`(${e})`);i.matches?t():i.addEventListener("change",t,{once:!0})}),_=E;var q=({component:e,argument:t})=>new Promise(i=>{let s=t||"0px 0px 0px 0px",n=new IntersectionObserver(o=>{o[0].isIntersecting&&(n.disconnect(),i())},{rootMargin:s});n.observe(e.el)}),m=q;function u(e){let t=P(e),i=x(t);return i.type==="method"?{type:"expression",operator:"&&",parameters:[i]}:i}function P(e){let t=/\s*([()])\s*|\s*(\|\||&&|\|)\s*|\s*((?:[^()&|]+\([^()]+\))|[^()&|]+)\s*/g,i=[],s;for(;(s=t.exec(e))!==null;){let[,n,o,r]=s;if(n!==void 0)i.push({type:"parenthesis",value:n});else if(o!==void 0)i.push({type:"operator",value:o==="|"?"&&":o});else{let p={type:"method",method:r.trim()};r.includes("(")&&(p.method=r.substring(0,r.indexOf("(")).trim(),p.argument=r.substring(r.indexOf("(")+1,r.indexOf(")"))),r.method==="immediate"&&(r.method="eager"),i.push(p)}}return i}function x(e){let t=g(e);for(;e.length>0&&(e[0].value==="&&"||e[0].value==="|"||e[0].value==="||");){let i=e.shift().value,s=g(e);t.type==="expression"&&t.operator===i?t.parameters.push(s):t={type:"expression",operator:i,parameters:[t,s]}}return t}function g(e){if(e[0].value==="("){e.shift();let t=x(e);return e[0].value===")"&&e.shift(),t}else return e.shift()}var w="__internal_",l={Alpine:null,_options:{prefix:"ax-",alpinePrefix:"x-",root:"load",inline:"load-src",defaultStrategy:"eager"},_alias:!1,_data:{},_realIndex:0,get _index(){return this._realIndex++},init(e,t={}){return this.Alpine=e,this._options={...this._options,...t},this},start(){return this._processInline(),this._setupComponents(),this._mutations(),this},data(e,t=!1){return this._data[e]={loaded:!1,download:t},this},url(e,t){!e||!t||(this._data[e]||this.data(e),this._data[e].download=()=>import(this._parseUrl(t)))},alias(e){this._alias=e},_processInline(){let e=document.querySelectorAll(`[${this._options.prefix}${this._options.inline}]`);for(let t of e)this._inlineElement(t)},_inlineElement(e){let t=e.getAttribute(`${this._options.alpinePrefix}data`),i=e.getAttribute(`${this._options.prefix}${this._options.inline}`);if(!t||!i)return;let s=this._parseName(t);this.url(s,i)},_setupComponents(){let e=document.querySelectorAll(`[${this._options.prefix}${this._options.root}]`);for(let t of e)this._setupComponent(t)},_setupComponent(e){let t=e.getAttribute(`${this._options.alpinePrefix}data`);e.setAttribute(`${this._options.alpinePrefix}ignore`,"");let i=this._parseName(t),s=e.getAttribute(`${this._options.prefix}${this._options.root}`)||this._options.defaultStrategy;this._componentStrategy({name:i,strategy:s,el:e,id:e.id||this._index})},async _componentStrategy(e){let t=u(e.strategy);await this._generateRequirements(e,t),await this._download(e.name),this._activate(e)},_generateRequirements(e,t){if(t.type==="expression"){if(t.operator==="&&")return Promise.all(t.parameters.map(i=>this._generateRequirements(e,i)));if(t.operator==="||")return Promise.any(t.parameters.map(i=>this._generateRequirements(e,i)))}return a[t.method]?a[t.method]({component:e,argument:t.argument}):!1},async _download(e){if(e.startsWith(w)||(this._handleAlias(e),!this._data[e]||this._data[e].loaded))return;let t=await this._getModule(e);this.Alpine.data(e,t),this._data[e].loaded=!0},async _getModule(e){if(!this._data[e])return;let t=await this._data[e].download(e);return typeof t=="function"?t:t[e]||t.default||Object.values(t)[0]||!1},_activate(e){e.el.removeAttribute(`${this._options.alpinePrefix}ignore`),e.el._x_ignore=!1,this.Alpine.initTree(e.el)},_mutations(){new MutationObserver(t=>{for(let i of t)if(!!i.addedNodes)for(let s of i.addedNodes){if(s.nodeType!==1)continue;s.hasAttribute(`${this._options.prefix}${this._options.root}`)&&this._mutationEl(s),s.querySelectorAll(`[${this._options.prefix}${this._options.root}]`).forEach(o=>this._mutationEl(o))}}).observe(document,{attributes:!0,childList:!0,subtree:!0})},_mutationEl(e){e.hasAttribute(`${this._options.prefix}${this._options.inline}`)&&this._inlineElement(e),this._setupComponent(e)},_handleAlias(e){if(!(!this._alias||this._data[e])){if(typeof this._alias=="function"){this.data(e,this._alias);return}this.url(e,this._alias.replaceAll("[name]",e))}},_parseName(e){return(e||"").split(/[({]/g)[0]||`${w}${this._index}`},_parseUrl(e){return new RegExp("^(?:[a-z+]+:)?//","i").test(e)?e:new URL(e,document.baseURI).href}};document.addEventListener("alpine:init",()=>{window.AsyncAlpine=l,l.init(Alpine,window.AsyncAlpineOptions||{}),document.dispatchEvent(new CustomEvent("async-alpine:init")),l.start()});})(); +(()=>{var d=Object.defineProperty;var w=e=>d(e,"__esModule",{value:!0});var A=(e,t)=>{w(e);for(var i in t)d(e,i,{get:t[i],enumerable:!0})};var a={};A(a,{eager:()=>h,event:()=>f,idle:()=>c,media:()=>_,visible:()=>m});var v=()=>!0,h=v;var b=({component:e,argument:t})=>new Promise(i=>{if(t)window.addEventListener(t,()=>i(),{once:!0});else{let s=n=>{n.detail.id===e.id&&(window.removeEventListener("async-alpine:load",s),i())};window.addEventListener("async-alpine:load",s)}}),f=b;var $=()=>new Promise(e=>{"requestIdleCallback"in window?window.requestIdleCallback(e):setTimeout(e,200)}),c=$;var E=({argument:e})=>new Promise(t=>{if(!e)return console.log("Async Alpine: media strategy requires a media query. Treating as 'eager'"),t();let i=window.matchMedia(`(${e})`);i.matches?t():i.addEventListener("change",t,{once:!0})}),_=E;var q=({component:e,argument:t})=>new Promise(i=>{let s=t||"0px 0px 0px 0px",n=new IntersectionObserver(o=>{o[0].isIntersecting&&(n.disconnect(),i())},{rootMargin:s});n.observe(e.el)}),m=q;function u(e){let t=P(e),i=x(t);return i.type==="method"?{type:"expression",operator:"&&",parameters:[i]}:i}function P(e){let t=/\s*([()])\s*|\s*(\|\||&&|\|)\s*|\s*((?:[^()&|]+\([^()]+\))|[^()&|]+)\s*/g,i=[],s;for(;(s=t.exec(e))!==null;){let[,n,o,r]=s;if(n!==void 0)i.push({type:"parenthesis",value:n});else if(o!==void 0)i.push({type:"operator",value:o==="|"?"&&":o});else{let p={type:"method",method:r.trim()};r.includes("(")&&(p.method=r.substring(0,r.indexOf("(")).trim(),p.argument=r.substring(r.indexOf("(")+1,r.indexOf(")"))),r.method==="immediate"&&(r.method="eager"),i.push(p)}}return i}function x(e){let t=g(e);for(;e.length>0&&(e[0].value==="&&"||e[0].value==="|"||e[0].value==="||");){let i=e.shift().value,s=g(e);t.type==="expression"&&t.operator===i?t.parameters.push(s):t={type:"expression",operator:i,parameters:[t,s]}}return t}function g(e){if(e[0].value==="("){e.shift();let t=x(e);return e[0].value===")"&&e.shift(),t}else return e.shift()}var y="__internal_",l={Alpine:null,_options:{prefix:"ax-",alpinePrefix:"x-",root:"load",inline:"load-src",defaultStrategy:"eager"},_alias:!1,_data:{},_realIndex:0,get _index(){return this._realIndex++},init(e,t={}){return this.Alpine=e,this._options={...this._options,...t},this},start(){return this._processInline(),this._setupComponents(),this._mutations(),this},data(e,t=!1){return this._data[e]={loaded:!1,download:t},this},url(e,t){!e||!t||(this._data[e]||this.data(e),this._data[e].download=()=>import(this._parseUrl(t)))},alias(e){this._alias=e},_processInline(){let e=document.querySelectorAll(`[${this._options.prefix}${this._options.inline}]`);for(let t of e)this._inlineElement(t)},_inlineElement(e){let t=e.getAttribute(`${this._options.alpinePrefix}data`),i=e.getAttribute(`${this._options.prefix}${this._options.inline}`);if(!t||!i)return;let s=this._parseName(t);this.url(s,i)},_setupComponents(){let e=document.querySelectorAll(`[${this._options.prefix}${this._options.root}]`);for(let t of e)this._setupComponent(t)},_setupComponent(e){let t=e.getAttribute(`${this._options.alpinePrefix}data`);e.setAttribute(`${this._options.alpinePrefix}ignore`,"");let i=this._parseName(t),s=e.getAttribute(`${this._options.prefix}${this._options.root}`)||this._options.defaultStrategy;this._componentStrategy({name:i,strategy:s,el:e,id:e.id||this._index})},async _componentStrategy(e){let t=u(e.strategy);await this._generateRequirements(e,t),await this._download(e.name),this._activate(e)},_generateRequirements(e,t){if(t.type==="expression"){if(t.operator==="&&")return Promise.all(t.parameters.map(i=>this._generateRequirements(e,i)));if(t.operator==="||")return Promise.any(t.parameters.map(i=>this._generateRequirements(e,i)))}return a[t.method]?a[t.method]({component:e,argument:t.argument}):!1},async _download(e){if(e.startsWith(y)||(this._handleAlias(e),!this._data[e]||this._data[e].loaded))return;let t=await this._getModule(e);this.Alpine.data(e,t),this._data[e].loaded=!0},async _getModule(e){if(!this._data[e])return;let t=await this._data[e].download(e);return typeof t=="function"?t:t[e]||t.default||Object.values(t)[0]||!1},_activate(e){this.Alpine.destroyTree(e.el),e.el.removeAttribute(`${this._options.alpinePrefix}ignore`),e.el._x_ignore=!1,this.Alpine.initTree(e.el)},_mutations(){new MutationObserver(t=>{for(let i of t)if(!!i.addedNodes)for(let s of i.addedNodes){if(s.nodeType!==1)continue;s.hasAttribute(`${this._options.prefix}${this._options.root}`)&&this._mutationEl(s),s.querySelectorAll(`[${this._options.prefix}${this._options.root}]`).forEach(o=>this._mutationEl(o))}}).observe(document,{attributes:!0,childList:!0,subtree:!0})},_mutationEl(e){e.hasAttribute(`${this._options.prefix}${this._options.inline}`)&&this._inlineElement(e),this._setupComponent(e)},_handleAlias(e){if(!(!this._alias||this._data[e])){if(typeof this._alias=="function"){this.data(e,this._alias);return}this.url(e,this._alias.replaceAll("[name]",e))}},_parseName(e){return(e||"").split(/[({]/g)[0]||`${y}${this._index}`},_parseUrl(e){return new RegExp("^(?:[a-z+]+:)?//","i").test(e)?e:new URL(e,document.baseURI).href}};document.addEventListener("alpine:init",()=>{window.AsyncAlpine=l,l.init(Alpine,window.AsyncAlpineOptions||{}),document.dispatchEvent(new CustomEvent("async-alpine:init")),l.start()});})(); diff --git a/package-lock.json b/package-lock.json index 5440730..d5e3175 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "async-alpine", - "version": "1.1.0", + "version": "1.2.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "async-alpine", - "version": "1.1.0", + "version": "1.2.0", "license": "Apache-2.0", "devDependencies": { "alpinejs": "^3.10.2", diff --git a/src/core/async-alpine.js b/src/core/async-alpine.js index 5269931..f1e0add 100644 --- a/src/core/async-alpine.js +++ b/src/core/async-alpine.js @@ -1,18 +1,18 @@ -import * as strategies from './strategies/index.js'; -import parseRequirements from './requirement-parser.js'; +import * as strategies from "./strategies/index.js"; +import parseRequirements from "./requirement-parser.js"; -const internalNamePrefix = '__internal_'; +const internalNamePrefix = "__internal_"; const AsyncAlpine = { Alpine: null, // custom options, over-ridden by the second param of init _options: { - prefix: 'ax-', - alpinePrefix: 'x-', - root: 'load', - inline: 'load-src', - defaultStrategy: 'eager', + prefix: "ax-", + alpinePrefix: "x-", + root: "load", + inline: "load-src", + defaultStrategy: "eager", }, // if we fall back to an alias when components aren't pre-registered @@ -68,11 +68,12 @@ const AsyncAlpine = { url(name, url) { if (!name || !url) return; if (!this._data[name]) this.data(name); - this._data[name].download = () => import( - /* @vite-ignore */ - /* webpackIgnore: true */ - this._parseUrl(url) - ); + this._data[name].download = () => + import( + /* @vite-ignore */ + /* webpackIgnore: true */ + this._parseUrl(url) + ); }, // fall back to requesting an unknown URL if a component isn't registered @@ -87,7 +88,9 @@ const AsyncAlpine = { */ // loop through all elements with ax-load-src to process them _processInline() { - const inlineComponents = document.querySelectorAll(`[${this._options.prefix}${this._options.inline}]`); + const inlineComponents = document.querySelectorAll( + `[${this._options.prefix}${this._options.inline}]` + ); for (const component of inlineComponents) { this._inlineElement(component); } @@ -96,7 +99,9 @@ const AsyncAlpine = { // process element to add the download function for this component _inlineElement(component) { const xData = component.getAttribute(`${this._options.alpinePrefix}data`); - let srcUrl = component.getAttribute(`${this._options.prefix}${this._options.inline}`); + let srcUrl = component.getAttribute( + `${this._options.prefix}${this._options.inline}` + ); if (!xData || !srcUrl) return; const name = this._parseName(xData); @@ -110,7 +115,9 @@ const AsyncAlpine = { */ // loop through elements with ax-load and set them up as components _setupComponents() { - const components = document.querySelectorAll(`[${this._options.prefix}${this._options.root}]`); + const components = document.querySelectorAll( + `[${this._options.prefix}${this._options.root}]` + ); for (let component of components) { this._setupComponent(component); } @@ -119,10 +126,12 @@ const AsyncAlpine = { // set this element up as a component _setupComponent(component) { const xData = component.getAttribute(`${this._options.alpinePrefix}data`); - component.setAttribute(`${this._options.alpinePrefix}ignore`, ''); + component.setAttribute(`${this._options.alpinePrefix}ignore`, ""); const name = this._parseName(xData); - const strategy = component.getAttribute(`${this._options.prefix}${this._options.root}`) || this._options.defaultStrategy; + const strategy = + component.getAttribute(`${this._options.prefix}${this._options.root}`) || + this._options.defaultStrategy; this._componentStrategy({ name, @@ -148,18 +157,20 @@ const AsyncAlpine = { }, _generateRequirements(component, obj) { - if (obj.type === 'expression') { - if (obj.operator === '&&') { + if (obj.type === "expression") { + if (obj.operator === "&&") { return Promise.all( - obj.parameters - .map(param => this._generateRequirements(component, param)) + obj.parameters.map((param) => + this._generateRequirements(component, param) + ) ); } - if (obj.operator === '||') { + if (obj.operator === "||") { return Promise.any( - obj.parameters - .map(param => this._generateRequirements(component, param)) + obj.parameters.map((param) => + this._generateRequirements(component, param) + ) ); } } @@ -194,11 +205,12 @@ const AsyncAlpine = { const module = await this._data[name].download(name); // if the download function returns a function instead return that - if (typeof module === 'function') return module; + if (typeof module === "function") return module; // work out which export to use in order of preference: // name; default; first export - let whichExport = module[name] || module.default || Object.values(module)[0] || false; + let whichExport = + module[name] || module.default || Object.values(module)[0] || false; return whichExport; }, @@ -210,6 +222,7 @@ const AsyncAlpine = { * them force Alpine to re-scan the tree */ _activate(component) { + this.Alpine.destroyTree(component.el); component.el.removeAttribute(`${this._options.alpinePrefix}ignore`); // eslint-disable-next-line camelcase component.el._x_ignore = false; @@ -223,7 +236,7 @@ const AsyncAlpine = { * watch for DOM mutations and set up added elements as new components */ _mutations() { - const observer = new MutationObserver(entries => { + const observer = new MutationObserver((entries) => { for (const entry of entries) { if (!entry.addedNodes) continue; for (const node of entry.addedNodes) { @@ -231,13 +244,17 @@ const AsyncAlpine = { if (node.nodeType !== 1) continue; // if the directly added node has ax-load then set it up - if (node.hasAttribute(`${this._options.prefix}${this._options.root}`)) { + if ( + node.hasAttribute(`${this._options.prefix}${this._options.root}`) + ) { this._mutationEl(node); } // check all descendants for ax-load - const childComponents = node.querySelectorAll(`[${this._options.prefix}${this._options.root}]`); - childComponents.forEach(el => this._mutationEl(el)); + const childComponents = node.querySelectorAll( + `[${this._options.prefix}${this._options.root}]` + ); + childComponents.forEach((el) => this._mutationEl(el)); } } }); @@ -268,16 +285,13 @@ const AsyncAlpine = { _handleAlias(name) { if (!this._alias || this._data[name]) return; - if (typeof this._alias === 'function') { + if (typeof this._alias === "function") { this.data(name, this._alias); return; } // at this point alias is enabled and the component doesn't exist - this.url( - name, - this._alias.replaceAll('[name]', name) - ); + this.url(name, this._alias.replaceAll("[name]", name)); }, /** @@ -287,7 +301,7 @@ const AsyncAlpine = { */ // take x-data content to parse out name 'output("test")' becomes 'output' _parseName(attribute) { - const parsedName = (attribute || '').split(/[({]/g)[0]; + const parsedName = (attribute || "").split(/[({]/g)[0]; const ourName = parsedName || `${internalNamePrefix}${this._index}`; return ourName; }, @@ -295,7 +309,7 @@ const AsyncAlpine = { _parseUrl(url) { // if the URL is relative then convert it to absolute based on the document baseURI // this is needed for when async alpine is loaded from a different origin than the page and component - const absoluteReg = new RegExp('^(?:[a-z+]+:)?//', 'i'); + const absoluteReg = new RegExp("^(?:[a-z+]+:)?//", "i"); if (!absoluteReg.test(url)) { return new URL(url, document.baseURI).href; } From 3c00a961c56326fdf84c5fa803eb6c38196c47a7 Mon Sep 17 00:00:00 2001 From: Adam Weston Date: Sun, 17 Dec 2023 17:03:21 -0500 Subject: [PATCH 2/3] reformat with single quotes --- src/core/async-alpine.js | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/core/async-alpine.js b/src/core/async-alpine.js index f1e0add..8fead14 100644 --- a/src/core/async-alpine.js +++ b/src/core/async-alpine.js @@ -1,18 +1,18 @@ -import * as strategies from "./strategies/index.js"; -import parseRequirements from "./requirement-parser.js"; +import * as strategies from './strategies/index.js'; +import parseRequirements from './requirement-parser.js'; -const internalNamePrefix = "__internal_"; +const internalNamePrefix = '__internal_'; const AsyncAlpine = { Alpine: null, // custom options, over-ridden by the second param of init _options: { - prefix: "ax-", - alpinePrefix: "x-", - root: "load", - inline: "load-src", - defaultStrategy: "eager", + prefix: 'ax-', + alpinePrefix: 'x-', + root: 'load', + inline: 'load-src', + defaultStrategy: 'eager', }, // if we fall back to an alias when components aren't pre-registered @@ -126,7 +126,7 @@ const AsyncAlpine = { // set this element up as a component _setupComponent(component) { const xData = component.getAttribute(`${this._options.alpinePrefix}data`); - component.setAttribute(`${this._options.alpinePrefix}ignore`, ""); + component.setAttribute(`${this._options.alpinePrefix}ignore`, ''); const name = this._parseName(xData); const strategy = @@ -157,8 +157,8 @@ const AsyncAlpine = { }, _generateRequirements(component, obj) { - if (obj.type === "expression") { - if (obj.operator === "&&") { + if (obj.type === 'expression') { + if (obj.operator === '&&') { return Promise.all( obj.parameters.map((param) => this._generateRequirements(component, param) @@ -166,7 +166,7 @@ const AsyncAlpine = { ); } - if (obj.operator === "||") { + if (obj.operator === '||') { return Promise.any( obj.parameters.map((param) => this._generateRequirements(component, param) @@ -205,7 +205,7 @@ const AsyncAlpine = { const module = await this._data[name].download(name); // if the download function returns a function instead return that - if (typeof module === "function") return module; + if (typeof module === 'function') return module; // work out which export to use in order of preference: // name; default; first export @@ -285,13 +285,13 @@ const AsyncAlpine = { _handleAlias(name) { if (!this._alias || this._data[name]) return; - if (typeof this._alias === "function") { + if (typeof this._alias === 'function') { this.data(name, this._alias); return; } // at this point alias is enabled and the component doesn't exist - this.url(name, this._alias.replaceAll("[name]", name)); + this.url(name, this._alias.replaceAll('[name]', name)); }, /** @@ -299,9 +299,9 @@ const AsyncAlpine = { * helpers * ================================= */ - // take x-data content to parse out name 'output("test")' becomes 'output' + // take x-data content to parse out name 'output('test')' becomes 'output' _parseName(attribute) { - const parsedName = (attribute || "").split(/[({]/g)[0]; + const parsedName = (attribute || '').split(/[({]/g)[0]; const ourName = parsedName || `${internalNamePrefix}${this._index}`; return ourName; }, @@ -309,7 +309,7 @@ const AsyncAlpine = { _parseUrl(url) { // if the URL is relative then convert it to absolute based on the document baseURI // this is needed for when async alpine is loaded from a different origin than the page and component - const absoluteReg = new RegExp("^(?:[a-z+]+:)?//", "i"); + const absoluteReg = new RegExp('^(?:[a-z+]+:)?//', 'i'); if (!absoluteReg.test(url)) { return new URL(url, document.baseURI).href; } From 6f3b04bc69f14970ec3b9e7ff921f0d7b695e2d6 Mon Sep 17 00:00:00 2001 From: Adam Weston Date: Sun, 17 Dec 2023 17:04:56 -0500 Subject: [PATCH 3/3] undo other format changes --- src/core/async-alpine.js | 59 ++++++++++++++++------------------------ 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/src/core/async-alpine.js b/src/core/async-alpine.js index 8fead14..ce991f1 100644 --- a/src/core/async-alpine.js +++ b/src/core/async-alpine.js @@ -68,12 +68,11 @@ const AsyncAlpine = { url(name, url) { if (!name || !url) return; if (!this._data[name]) this.data(name); - this._data[name].download = () => - import( - /* @vite-ignore */ - /* webpackIgnore: true */ - this._parseUrl(url) - ); + this._data[name].download = () => import( + /* @vite-ignore */ + /* webpackIgnore: true */ + this._parseUrl(url) + ); }, // fall back to requesting an unknown URL if a component isn't registered @@ -88,9 +87,7 @@ const AsyncAlpine = { */ // loop through all elements with ax-load-src to process them _processInline() { - const inlineComponents = document.querySelectorAll( - `[${this._options.prefix}${this._options.inline}]` - ); + const inlineComponents = document.querySelectorAll(`[${this._options.prefix}${this._options.inline}]`); for (const component of inlineComponents) { this._inlineElement(component); } @@ -99,9 +96,7 @@ const AsyncAlpine = { // process element to add the download function for this component _inlineElement(component) { const xData = component.getAttribute(`${this._options.alpinePrefix}data`); - let srcUrl = component.getAttribute( - `${this._options.prefix}${this._options.inline}` - ); + let srcUrl = component.getAttribute(`${this._options.prefix}${this._options.inline}`); if (!xData || !srcUrl) return; const name = this._parseName(xData); @@ -115,9 +110,7 @@ const AsyncAlpine = { */ // loop through elements with ax-load and set them up as components _setupComponents() { - const components = document.querySelectorAll( - `[${this._options.prefix}${this._options.root}]` - ); + const components = document.querySelectorAll(`[${this._options.prefix}${this._options.root}]`); for (let component of components) { this._setupComponent(component); } @@ -129,9 +122,7 @@ const AsyncAlpine = { component.setAttribute(`${this._options.alpinePrefix}ignore`, ''); const name = this._parseName(xData); - const strategy = - component.getAttribute(`${this._options.prefix}${this._options.root}`) || - this._options.defaultStrategy; + const strategy = component.getAttribute(`${this._options.prefix}${this._options.root}`) || this._options.defaultStrategy; this._componentStrategy({ name, @@ -160,17 +151,15 @@ const AsyncAlpine = { if (obj.type === 'expression') { if (obj.operator === '&&') { return Promise.all( - obj.parameters.map((param) => - this._generateRequirements(component, param) - ) + obj.parameters + .map(param => this._generateRequirements(component, param)) ); } if (obj.operator === '||') { return Promise.any( - obj.parameters.map((param) => - this._generateRequirements(component, param) - ) + obj.parameters + .map(param => this._generateRequirements(component, param)) ); } } @@ -209,8 +198,7 @@ const AsyncAlpine = { // work out which export to use in order of preference: // name; default; first export - let whichExport = - module[name] || module.default || Object.values(module)[0] || false; + let whichExport = module[name] || module.default || Object.values(module)[0] || false; return whichExport; }, @@ -236,7 +224,7 @@ const AsyncAlpine = { * watch for DOM mutations and set up added elements as new components */ _mutations() { - const observer = new MutationObserver((entries) => { + const observer = new MutationObserver(entries => { for (const entry of entries) { if (!entry.addedNodes) continue; for (const node of entry.addedNodes) { @@ -244,17 +232,13 @@ const AsyncAlpine = { if (node.nodeType !== 1) continue; // if the directly added node has ax-load then set it up - if ( - node.hasAttribute(`${this._options.prefix}${this._options.root}`) - ) { + if (node.hasAttribute(`${this._options.prefix}${this._options.root}`)) { this._mutationEl(node); } // check all descendants for ax-load - const childComponents = node.querySelectorAll( - `[${this._options.prefix}${this._options.root}]` - ); - childComponents.forEach((el) => this._mutationEl(el)); + const childComponents = node.querySelectorAll(`[${this._options.prefix}${this._options.root}]`); + childComponents.forEach(el => this._mutationEl(el)); } } }); @@ -291,7 +275,10 @@ const AsyncAlpine = { } // at this point alias is enabled and the component doesn't exist - this.url(name, this._alias.replaceAll('[name]', name)); + this.url( + name, + this._alias.replaceAll('[name]', name) + ); }, /** @@ -299,7 +286,7 @@ const AsyncAlpine = { * helpers * ================================= */ - // take x-data content to parse out name 'output('test')' becomes 'output' + // take x-data content to parse out name 'output("test")' becomes 'output' _parseName(attribute) { const parsedName = (attribute || '').split(/[({]/g)[0]; const ourName = parsedName || `${internalNamePrefix}${this._index}`;