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