ModalManager.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { textUtil } from '@grafana/data';
  4. import { CopyPanelEvent } from '@grafana/runtime';
  5. import { ConfirmModal, ConfirmModalProps } from '@grafana/ui';
  6. import appEvents from 'app/core/app_events';
  7. import { copyPanel } from 'app/features/dashboard/utils/panel';
  8. import { ShowConfirmModalEvent, ShowConfirmModalPayload, ShowModalReactEvent } from '../../types/events';
  9. import { AngularModalProxy } from '../components/modals/AngularModalProxy';
  10. import { provideTheme } from '../utils/ConfigProvider';
  11. export class ModalManager {
  12. reactModalRoot = document.body;
  13. reactModalNode = document.createElement('div');
  14. init() {
  15. appEvents.subscribe(ShowConfirmModalEvent, (e) => this.showConfirmModal(e.payload));
  16. appEvents.subscribe(ShowModalReactEvent, (e) => this.showModalReact(e.payload));
  17. appEvents.subscribe(CopyPanelEvent, (e) => copyPanel(e.payload));
  18. }
  19. showModalReact(options: any) {
  20. const { component, props } = options;
  21. const modalProps = {
  22. component,
  23. props: {
  24. ...props,
  25. isOpen: true,
  26. onDismiss: this.onReactModalDismiss,
  27. },
  28. };
  29. const elem = React.createElement(provideTheme(AngularModalProxy), modalProps);
  30. this.reactModalRoot.appendChild(this.reactModalNode);
  31. ReactDOM.render(elem, this.reactModalNode);
  32. }
  33. onReactModalDismiss = () => {
  34. ReactDOM.unmountComponentAtNode(this.reactModalNode);
  35. this.reactModalRoot.removeChild(this.reactModalNode);
  36. };
  37. showConfirmModal(payload: ShowConfirmModalPayload) {
  38. const {
  39. confirmText,
  40. onConfirm = () => undefined,
  41. text2,
  42. altActionText,
  43. onAltAction,
  44. noText,
  45. text,
  46. text2htmlBind,
  47. yesText = 'Yes',
  48. icon,
  49. title = 'Confirm',
  50. } = payload;
  51. const props: ConfirmModalProps = {
  52. confirmText: yesText,
  53. confirmationText: confirmText,
  54. icon,
  55. title,
  56. body: text,
  57. description: text2 && text2htmlBind ? textUtil.sanitize(text2) : text2,
  58. isOpen: true,
  59. dismissText: noText,
  60. onConfirm: () => {
  61. onConfirm();
  62. this.onReactModalDismiss();
  63. },
  64. onDismiss: this.onReactModalDismiss,
  65. onAlternative: onAltAction
  66. ? () => {
  67. onAltAction();
  68. this.onReactModalDismiss();
  69. }
  70. : undefined,
  71. alternativeText: altActionText,
  72. };
  73. const modalProps = {
  74. component: ConfirmModal,
  75. props,
  76. };
  77. const elem = React.createElement(provideTheme(AngularModalProxy), modalProps);
  78. this.reactModalRoot.appendChild(this.reactModalNode);
  79. ReactDOM.render(elem, this.reactModalNode);
  80. }
  81. }