forked from handsontable/handsontable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.js
94 lines (77 loc) · 2.39 KB
/
plugins.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* Utility to register plugins and common namespace for keeping reference to all plugins classes
*/
import {objectEach} from './helpers/object';
import {toUpperCaseFirst} from './helpers/string';
const registeredPlugins = new WeakMap();
Handsontable.plugins = Handsontable.plugins || {};
/**
* Registers plugin under given name
*
* @param {String} pluginName
* @param {Function} PluginClass
*/
function registerPlugin(pluginName, PluginClass) {
pluginName = toUpperCaseFirst(pluginName);
Handsontable.plugins[pluginName] = PluginClass;
Handsontable.hooks.add('construct', function() {
let holder;
if (!registeredPlugins.has(this)) {
registeredPlugins.set(this, {});
}
holder = registeredPlugins.get(this);
if (!holder[pluginName]) {
holder[pluginName] = new PluginClass(this);
}
});
Handsontable.hooks.add('afterDestroy', function() {
if (registeredPlugins.has(this)) {
let pluginsHolder = registeredPlugins.get(this);
objectEach(pluginsHolder, (plugin) => plugin.destroy());
registeredPlugins.delete(this);
}
});
}
/**
* @param {Object} instance
* @param {String|Function} pluginName
* @returns {Function} pluginClass Returns plugin instance if exists or `undefined` if not exists.
*/
function getPlugin(instance, pluginName) {
if (typeof pluginName != 'string') {
throw Error('Only strings can be passed as "plugin" parameter');
}
let _pluginName = toUpperCaseFirst(pluginName);
if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[_pluginName]) {
return void 0;
}
return registeredPlugins.get(instance)[_pluginName];
}
/**
* Get all registred plugins names for concrete Handsontable instance.
*
* @param {Object} hotInstance
* @returns {Array}
*/
function getRegistredPluginNames(hotInstance) {
return registeredPlugins.has(hotInstance) ? Object.keys(registeredPlugins.get(hotInstance)) : [];
}
/**
* Get plugin name.
*
* @param {Object} hotInstance
* @param {Object} plugin
* @returns {String|null}
*/
function getPluginName(hotInstance, plugin) {
let pluginName = null;
if (registeredPlugins.has(hotInstance)) {
objectEach(registeredPlugins.get(hotInstance), (pluginInstance, name) => {
if (pluginInstance === plugin) {
pluginName = name;
}
});
}
return pluginName;
}
export {registerPlugin, getPlugin, getRegistredPluginNames, getPluginName};