hookStore.tsx 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import {createStore, StoreDefinition} from 'reflux';
  2. import {HookName, Hooks} from 'sentry/types/hooks';
  3. import {makeSafeRefluxStore} from 'sentry/utils/makeSafeRefluxStore';
  4. interface Internals {
  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. }
  10. interface HookStoreDefinition extends StoreDefinition, Internals {
  11. add<H extends HookName>(hookName: H, callback: Hooks[H]): void;
  12. get<H extends HookName>(hookName: H): Array<Hooks[H]>;
  13. remove<H extends HookName>(hookName: H, callback: Hooks[H]): void;
  14. }
  15. const storeConfig: HookStoreDefinition = {
  16. hooks: {},
  17. init() {
  18. this.hooks = {};
  19. },
  20. add(hookName, callback) {
  21. if (this.hooks[hookName] === undefined) {
  22. this.hooks[hookName] = [];
  23. }
  24. this.hooks[hookName].push(callback);
  25. this.trigger(hookName, this.hooks[hookName]);
  26. },
  27. remove(hookName, callback) {
  28. if (this.hooks[hookName] === undefined) {
  29. return;
  30. }
  31. this.hooks[hookName] = this.hooks[hookName]!.filter(cb => cb !== callback);
  32. this.trigger(hookName, this.hooks[hookName]);
  33. },
  34. get(hookName) {
  35. return this.hooks[hookName]! || [];
  36. },
  37. };
  38. /**
  39. * HookStore is used to allow extensibility into Sentry's frontend via
  40. * registration of 'hook functions'.
  41. *
  42. * This functionality is primarily used by the SASS sentry.io product.
  43. */
  44. const HookStore = createStore(makeSafeRefluxStore(storeConfig));
  45. export default HookStore;