plugins.js 2.4 KB

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