UNPKG

@kanety/stimulus-static-actions

Version:

A stimulus extension to define actions in controller

3 lines (2 loc) 1.99 kB
import{Context as t}from"@hotwired/stimulus";class e{constructor(t,e){this.identifier=t,this.name=e[0],this.descriptor=e[1],this.options=e[2]||{}}get description(){let t=this.descriptor;return t.match(/^:/)&&(t=t.replace(/^:/,`${this.identifier}:`)),t.includes("->")?t.replace(/->/,`->${this.identifier}#`):`${this.identifier}#${t}`}}class r{constructor(t){this.context=t,this.controller=t.controller,this.actions=[]}run(){this.add(function(t,e){let r=function(t){const e=[];for(;t;)e.push(t),t=Object.getPrototypeOf(t);return e.reverse()}(t);return Array.from(r.reduce((t,e)=>(function(t,e){const r=t.actions;return Array.isArray(r)?r:[]}(e).forEach(e=>t.add(e)),t),new Set))}(this.controller.constructor))}add(t){t.map(t=>new e(this.controller.identifier,t)).forEach(t=>{this.resolveTargets(t).forEach(e=>{this.addAction(e,t)}),this.actions.push(t)})}remove(t){t.map(t=>new e(this.controller.identifier,t)).forEach(t=>{this.resolveTargets(t).forEach(e=>{this.removeAction(e,t)}),this.actions=this.actions.filter(e=>e.description!=t.description)})}resolveTargets(t){let e=this.findTargets(t.name);return t.options.if?this.filterTargets(e,t.options.if):e}findTargets(t){return"element"==t?[this.controller.element]:this.controller[`${t}Targets`]?[].concat(this.controller[`${t}Targets`]):[]}filterTargets(t,e){return t.filter(t=>{let r=this.controller[e];return"function"==typeof r&&(r=r.apply(this.controller,t)),0!=r})}addAction(t,e){let r=e.description,i=(t.dataset.action||"").split(" ");i.some(t=>t==r)||i.push(r),t.dataset.action=i.join(" ").trim()}removeAction(t,e){let r=e.description,i=(t.dataset.action||"").split(" ");i=i.filter(t=>t!=r),t.dataset.action=i.join(" ").trim()}}let i=t.prototype.connect,o=t.prototype.targetConnected;t.prototype.connect=function(){return this.actionSet=new r(this),this.actionSet.run(),i.apply(this,arguments)},t.prototype.targetConnected=function(){return this.actionSet.run(),o.apply(this,arguments)}; //# sourceMappingURL=index.modern.mjs.map