withGlobalSelection.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import * as React from 'react';
  2. import createReactClass from 'create-react-class';
  3. import Reflux from 'reflux';
  4. import GlobalSelectionStore from 'app/stores/globalSelectionStore';
  5. import {GlobalSelection} from 'app/types';
  6. import getDisplayName from 'app/utils/getDisplayName';
  7. type InjectedGlobalSelectionProps = {
  8. selection?: GlobalSelection;
  9. isGlobalSelectionReady?: boolean;
  10. };
  11. type State = {
  12. selection: GlobalSelection;
  13. isReady?: boolean;
  14. };
  15. /**
  16. * Higher order component that uses GlobalSelectionStore and provides the
  17. * active project
  18. */
  19. const withGlobalSelection = <P extends InjectedGlobalSelectionProps>(
  20. WrappedComponent: React.ComponentType<P>
  21. ) =>
  22. createReactClass<
  23. Omit<P, keyof InjectedGlobalSelectionProps> & Partial<InjectedGlobalSelectionProps>,
  24. State
  25. >({
  26. displayName: `withGlobalSelection(${getDisplayName(WrappedComponent)})`,
  27. mixins: [Reflux.listenTo(GlobalSelectionStore, 'onUpdate') as any],
  28. getInitialState() {
  29. return GlobalSelectionStore.get();
  30. },
  31. onUpdate(selection: State) {
  32. if (this.state !== selection) {
  33. this.setState(selection);
  34. }
  35. },
  36. render() {
  37. const {isReady, selection} = this.state;
  38. return (
  39. <WrappedComponent
  40. selection={selection as GlobalSelection}
  41. isGlobalSelectionReady={isReady}
  42. {...(this.props as P)}
  43. />
  44. );
  45. },
  46. });
  47. export default withGlobalSelection;