hookStore.tsx 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import isUndefined from 'lodash/isUndefined';
  2. import Reflux from 'reflux';
  3. import {HookName, Hooks} from 'sentry/types/hooks';
  4. type HookStoreInterface = {
  5. // XXX(epurkhiser): We could type this as {[H in HookName]?:
  6. // Array<Hooks[H]>}, however this causes typescript to produce a complex
  7. // union that it complains is 'too complex'
  8. hooks: any;
  9. add<H extends HookName>(hookName: H, callback: Hooks[H]): void;
  10. remove<H extends HookName>(hookName: H, callback: Hooks[H]): void;
  11. get<H extends HookName>(hookName: H): Array<Hooks[H]>;
  12. };
  13. const storeConfig: Reflux.StoreDefinition & HookStoreInterface = {
  14. hooks: {},
  15. init() {
  16. this.hooks = {};
  17. },
  18. add(hookName, callback) {
  19. if (isUndefined(this.hooks[hookName])) {
  20. this.hooks[hookName] = [];
  21. }
  22. this.hooks[hookName]!.push(callback);
  23. this.trigger(hookName, this.hooks[hookName]);
  24. },
  25. remove(hookName, callback) {
  26. if (isUndefined(this.hooks[hookName])) {
  27. return;
  28. }
  29. this.hooks[hookName] = this.hooks[hookName]!.filter(cb => cb !== callback);
  30. this.trigger(hookName, this.hooks[hookName]);
  31. },
  32. get(hookName) {
  33. return this.hooks[hookName]! || [];
  34. },
  35. };
  36. /**
  37. * HookStore is used to allow extensibility into Sentry's frontend via
  38. * registration of 'hook functions'.
  39. *
  40. * This functionality is primarily used by the SASS sentry.io product.
  41. */
  42. const HookStore = Reflux.createStore(storeConfig) as Reflux.Store & HookStoreInterface;
  43. export default HookStore;