ReactContainer.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. import { ErrorBoundaryAlert } from '@grafana/ui';
  11. function WrapInProvider(store: any, Component: any, props: any) {
  12. return (
  13. <Provider store={store}>
  14. <ErrorBoundaryAlert style="page">
  15. <Component {...props} />
  16. </ErrorBoundaryAlert>
  17. </Provider>
  18. );
  19. }
  20. /** @ngInject */
  21. export function reactContainer($route: any, $location: any, $injector: any, $rootScope: any, contextSrv: ContextSrv) {
  22. return {
  23. restrict: 'E',
  24. template: '',
  25. link(scope: any, elem: JQuery) {
  26. // Check permissions for this component
  27. const roles: string[] = $route.current.locals.roles;
  28. if (roles && roles.length) {
  29. if (!roles.some(r => contextSrv.hasRole(r))) {
  30. $location.url('/');
  31. }
  32. }
  33. let { component } = $route.current.locals;
  34. // Dynamic imports return whole module, need to extract default export
  35. if (component.default) {
  36. component = component.default;
  37. }
  38. const props = {
  39. $injector: $injector,
  40. $rootScope: $rootScope,
  41. $scope: scope,
  42. $contextSrv: contextSrv,
  43. routeInfo: $route.current.$$route.routeInfo,
  44. };
  45. document.body.classList.add('is-react');
  46. ReactDOM.render(WrapInProvider(store, provideTheme(component), props), elem[0]);
  47. scope.$on('$destroy', () => {
  48. document.body.classList.remove('is-react');
  49. ReactDOM.unmountComponentAtNode(elem[0]);
  50. });
  51. },
  52. };
  53. }
  54. coreModule.directive('reactContainer', reactContainer);