@kanety/stimulus-static-actions
Version:
A stimulus extension to define actions in controller
3 lines (2 loc) • 2.15 kB
JavaScript
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("@hotwired/stimulus")):"function"==typeof define&&define.amd?define(["@hotwired/stimulus"],e):e((t||self).Stimulus)}(this,function(t){class e{constructor(t,e){this.identifier=t,this.name=e[0],this.descriptor=e[1],this.options=e[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 i{constructor(t){this.context=t,this.controller=t.controller,this.actions=[]}run(){var t;this.add((t=function(t){for(var e=[];t;)e.push(t),t=Object.getPrototypeOf(t);return e.reverse()}(this.controller.constructor),Array.from(t.reduce((t,e)=>(function(t,e){var i=t.actions;return Array.isArray(i)?i:[]}(e).forEach(e=>t.add(e)),t),new Set))))}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){var 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=>{var i=this.controller[e];return"function"==typeof i&&(i=i.apply(this.controller,t)),0!=i})}addAction(t,e){var i=e.description,r=(t.dataset.action||"").split(" ");r.some(t=>t==i)||r.push(i),t.dataset.action=r.join(" ").trim()}removeAction(t,e){var i=e.description,r=(t.dataset.action||"").split(" ");r=r.filter(t=>t!=i),t.dataset.action=r.join(" ").trim()}}var r=t.Context.prototype.connect,o=t.Context.prototype.targetConnected;t.Context.prototype.connect=function(){return this.actionSet=new i(this),this.actionSet.run(),r.apply(this,arguments)},t.Context.prototype.targetConnected=function(){return this.actionSet.run(),o.apply(this,arguments)}});
//# sourceMappingURL=index.umd.js.map