minsky-kit
Version:
Kit of components for MINSKY web agency
114 lines (94 loc) • 3.06 kB
JavaScript
/* eslint no-unused-vars: "off" */
import Core from '../core/Core';
class PluginManager extends Core {
// constructor
constructor (args = {}) {
super({}, 'Plugin MGR');
// prepare properties
this.plugins = [];
this.Target = args.Target;
// register plugins if already known
if (args.plugins) this.register(args.plugins);
// call super
// super(args);
}
// methods
define (plugin) {
// add plugin(s)
if (Array.isArray(plugin)) {
for (let i = 0, len = plugin.length; i < len; i++) {
this.define(plugin[i]);
}
}
else {
// adds necessary methods to parent class definition
for (const p of Object.keys(plugin)) {
// extract property
const method = plugin[p];
// only process when it's a method
if (!this.Target.prototype[p] && typeof method === 'function') {
// add method to parent definition
this.Target.prototype[p] = method;
}
}
this.plugins.push(plugin);
}
}
get (pluginId) {
for (const p of this.plugins) {
if (p.name && p.name === pluginId) return p;
}
return false;
}
setOption (plugin, options) {
plugin = this.get(plugin);
if (plugin) {
Object.assign(plugin.options, options);
}
}
run (method, args, scope = null) {
// check if plugins are registered, if not stop immediatelly
if (Array.isArray(this.plugins) && this.plugins.length) {
// make reference shortcut, just in case
const { plugins } = this;
// loop over all registered plugins and run their method if defined
for (let i = 0, len = plugins.length; i < len; i++) {
if (plugins[i][method]) plugins[i][method].call(scope || this.scope, args);
}
}
}
logPlugins () {
const lines = [];
this.plugins.forEach((p) => {
lines.push(`\t${[p.name, p.version].join(' ')}`);
});
this.log('Plugins defined: \n', lines.join('\n'));
}
destroy () {
if (this.plugins) {
// clear properties
this.plugins.length = 0;
this.plugins = null;
}
// destroy super
super.destroy();
}
// statics
}
// sti needs to remove name from arguments passed to methods!!!
// function generateMethod (name, original, scope) {
// return (function (name, original) {
// // function () {
// // this.pluginmanager.run(name, ...arguments);
// // }
// })(name, original);
// }
// Utils
export function getPluginConfig (prop, args = null) {
const instance = args || this;
if (instance) {
return (instance._plugins || instance.plugins || {})[prop] || false;
}
return false;
}
export default PluginManager;