hookStore.tsx 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. this.hooks = {};
  18. },
  19. add(hookName, callback) {
  20. if (this.hooks[hookName] === undefined) {
  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 (this.hooks[hookName] === undefined) {
  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 = createStore(storeConfig);
  44. export default HookStore;