79db1a0079037c8084dec03b1f99c91462d5a871bcbe105d62c06ccf6d312ff6fb7c5a356a3de516506948ce434119e96a35a9ee7a1a427f9429c7aaf7d633 2.3 KB

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