plugins.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. var 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. var holder = void 0;
  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. var pluginsHolder = registeredPlugins.get(this);
  29. objectEach(pluginsHolder, function (plugin) {
  30. return plugin.destroy();
  31. });
  32. registeredPlugins.delete(this);
  33. }
  34. });
  35. }
  36. /**
  37. * @param {Object} instance
  38. * @param {String|Function} pluginName
  39. * @returns {Function} pluginClass Returns plugin instance if exists or `undefined` if not exists.
  40. */
  41. function getPlugin(instance, pluginName) {
  42. if (typeof pluginName != 'string') {
  43. throw Error('Only strings can be passed as "plugin" parameter');
  44. }
  45. var _pluginName = toUpperCaseFirst(pluginName);
  46. if (!registeredPlugins.has(instance) || !registeredPlugins.get(instance)[_pluginName]) {
  47. return void 0;
  48. }
  49. return registeredPlugins.get(instance)[_pluginName];
  50. }
  51. /**
  52. * Get all registred plugins names for concrete Handsontable instance.
  53. *
  54. * @param {Object} hotInstance
  55. * @returns {Array}
  56. */
  57. function getRegistredPluginNames(hotInstance) {
  58. return registeredPlugins.has(hotInstance) ? Object.keys(registeredPlugins.get(hotInstance)) : [];
  59. }
  60. /**
  61. * Get plugin name.
  62. *
  63. * @param {Object} hotInstance
  64. * @param {Object} plugin
  65. * @returns {String|null}
  66. */
  67. function getPluginName(hotInstance, plugin) {
  68. var pluginName = null;
  69. if (registeredPlugins.has(hotInstance)) {
  70. objectEach(registeredPlugins.get(hotInstance), function (pluginInstance, name) {
  71. if (pluginInstance === plugin) {
  72. pluginName = name;
  73. }
  74. });
  75. }
  76. return pluginName;
  77. }
  78. export { registerPlugin, getPlugin, getRegistredPluginNames, getPluginName };