ReactContainer.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Libraries
  2. import React from 'react';
  3. import ReactDOM from 'react-dom';
  4. import { Provider } from 'react-redux';
  5. // Utils and services
  6. import coreModule from 'app/core/core_module';
  7. import { store } from 'app/store/store';
  8. import { ContextSrv } from 'app/core/services/context_srv';
  9. import { provideTheme } from 'app/core/utils/ConfigProvider';
  10. function WrapInProvider(store: any, Component: any, props: any) {
  11. return (
  12. <Provider store={store}>
  13. <Component {...props} />
  14. </Provider>
  15. );
  16. }
  17. /** @ngInject */
  18. export function reactContainer($route: any, $location: any, $injector: any, $rootScope: any, contextSrv: ContextSrv) {
  19. return {
  20. restrict: 'E',
  21. template: '',
  22. link(scope: any, elem: JQuery) {
  23. // Check permissions for this component
  24. const roles: string[] = $route.current.locals.roles;
  25. if (roles && roles.length) {
  26. if (!roles.some(r => contextSrv.hasRole(r))) {
  27. $location.url('/');
  28. }
  29. }
  30. let { component } = $route.current.locals;
  31. // Dynamic imports return whole module, need to extract default export
  32. if (component.default) {
  33. component = component.default;
  34. }
  35. const props = {
  36. $injector: $injector,
  37. $rootScope: $rootScope,
  38. $scope: scope,
  39. $contextSrv: contextSrv,
  40. routeInfo: $route.current.$$route.routeInfo,
  41. };
  42. document.body.classList.add('is-react');
  43. ReactDOM.render(WrapInProvider(store, provideTheme(component), props), elem[0]);
  44. scope.$on('$destroy', () => {
  45. document.body.classList.remove('is-react');
  46. ReactDOM.unmountComponentAtNode(elem[0]);
  47. });
  48. },
  49. };
  50. }
  51. coreModule.directive('reactContainer', reactContainer);