hookStore.tsx 1.5 KB

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