hookStore.tsx 1.6 KB

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