DashboardPrompt.tsx 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import * as H from 'history';
  2. import { each, find } from 'lodash';
  3. import React, { useContext, useEffect, useState } from 'react';
  4. import { useDispatch } from 'react-redux';
  5. import { Prompt } from 'react-router-dom';
  6. import { locationService } from '@grafana/runtime';
  7. import { ModalsContext } from '@grafana/ui';
  8. import { appEvents } from 'app/core/app_events';
  9. import { contextSrv } from 'app/core/services/context_srv';
  10. import { SaveLibraryPanelModal } from 'app/features/library-panels/components/SaveLibraryPanelModal/SaveLibraryPanelModal';
  11. import { PanelModelWithLibraryPanel } from 'app/features/library-panels/types';
  12. import { DashboardSavedEvent } from 'app/types/events';
  13. import { DashboardModel } from '../../state/DashboardModel';
  14. import { discardPanelChanges, exitPanelEditor } from '../PanelEditor/state/actions';
  15. import { UnsavedChangesModal } from '../SaveDashboard/UnsavedChangesModal';
  16. export interface Props {
  17. dashboard: DashboardModel;
  18. }
  19. interface State {
  20. original: object | null;
  21. originalPath?: string;
  22. }
  23. export const DashboardPrompt = React.memo(({ dashboard }: Props) => {
  24. const [state, setState] = useState<State>({ original: null });
  25. const dispatch = useDispatch();
  26. const { original, originalPath } = state;
  27. const { showModal, hideModal } = useContext(ModalsContext);
  28. useEffect(() => {
  29. // This timeout delay is to wait for panels to load and migrate scheme before capturing the original state
  30. // This is to minimize unsaved changes warnings due to automatic schema migrations
  31. const timeoutId = setTimeout(() => {
  32. const originalPath = locationService.getLocation().pathname;
  33. const original = dashboard.getSaveModelClone();
  34. setState({ originalPath, original });
  35. }, 1000);
  36. const savedEventUnsub = appEvents.subscribe(DashboardSavedEvent, () => {
  37. const original = dashboard.getSaveModelClone();
  38. setState({ originalPath, original });
  39. });
  40. return () => {
  41. clearTimeout(timeoutId);
  42. savedEventUnsub.unsubscribe();
  43. };
  44. }, [dashboard, originalPath]);
  45. useEffect(() => {
  46. const handleUnload = (event: BeforeUnloadEvent) => {
  47. if (ignoreChanges(dashboard, original)) {
  48. return;
  49. }
  50. if (hasChanges(dashboard, original)) {
  51. event.preventDefault();
  52. // No browser actually displays this message anymore.
  53. // But Chrome requires it to be defined else the popup won't show.
  54. event.returnValue = '';
  55. }
  56. };
  57. window.addEventListener('beforeunload', handleUnload);
  58. return () => window.removeEventListener('beforeunload', handleUnload);
  59. }, [dashboard, original]);
  60. const onHistoryBlock = (location: H.Location) => {
  61. const panelInEdit = dashboard.panelInEdit;
  62. const search = new URLSearchParams(location.search);
  63. // Are we leaving panel edit & library panel?
  64. if (panelInEdit && panelInEdit.libraryPanel && panelInEdit.hasChanged && !search.has('editPanel')) {
  65. showModal(SaveLibraryPanelModal, {
  66. isUnsavedPrompt: true,
  67. panel: dashboard.panelInEdit as PanelModelWithLibraryPanel,
  68. folderId: dashboard.meta.folderId as number,
  69. onConfirm: () => {
  70. hideModal();
  71. moveToBlockedLocationAfterReactStateUpdate(location);
  72. },
  73. onDiscard: () => {
  74. dispatch(discardPanelChanges());
  75. moveToBlockedLocationAfterReactStateUpdate(location);
  76. hideModal();
  77. },
  78. onDismiss: hideModal,
  79. });
  80. return false;
  81. }
  82. // Are we still on the same dashboard?
  83. if (originalPath === location.pathname || !original) {
  84. // This is here due to timing reasons we want the exit panel editor state changes to happen before router update
  85. if (panelInEdit && !search.has('editPanel')) {
  86. dispatch(exitPanelEditor());
  87. }
  88. return true;
  89. }
  90. if (ignoreChanges(dashboard, original)) {
  91. return true;
  92. }
  93. if (!hasChanges(dashboard, original)) {
  94. return true;
  95. }
  96. showModal(UnsavedChangesModal, {
  97. dashboard: dashboard,
  98. onSaveSuccess: () => {
  99. hideModal();
  100. moveToBlockedLocationAfterReactStateUpdate(location);
  101. },
  102. onDiscard: () => {
  103. setState({ ...state, original: null });
  104. hideModal();
  105. moveToBlockedLocationAfterReactStateUpdate(location);
  106. },
  107. onDismiss: hideModal,
  108. });
  109. return false;
  110. };
  111. return <Prompt when={true} message={onHistoryBlock} />;
  112. });
  113. DashboardPrompt.displayName = 'DashboardPrompt';
  114. function moveToBlockedLocationAfterReactStateUpdate(location?: H.Location | null) {
  115. if (location) {
  116. setTimeout(() => locationService.push(location), 10);
  117. }
  118. }
  119. /**
  120. * For some dashboards and users changes should be ignored *
  121. */
  122. export function ignoreChanges(current: DashboardModel, original: object | null) {
  123. if (!original) {
  124. return true;
  125. }
  126. // Ignore changes if the user has been signed out
  127. if (!contextSrv.isSignedIn) {
  128. return true;
  129. }
  130. if (!current || !current.meta) {
  131. return true;
  132. }
  133. const { canSave, fromScript, fromFile } = current.meta;
  134. if (!contextSrv.isEditor && !canSave) {
  135. return true;
  136. }
  137. return !canSave || fromScript || fromFile;
  138. }
  139. /**
  140. * Remove stuff that should not count in diff
  141. */
  142. function cleanDashboardFromIgnoredChanges(dashData: any) {
  143. // need to new up the domain model class to get access to expand / collapse row logic
  144. const model = new DashboardModel(dashData);
  145. // Expand all rows before making comparison. This is required because row expand / collapse
  146. // change order of panel array and panel positions.
  147. model.expandRows();
  148. const dash = model.getSaveModelClone();
  149. // ignore time and refresh
  150. dash.time = 0;
  151. dash.refresh = 0;
  152. dash.schemaVersion = 0;
  153. dash.timezone = 0;
  154. dash.panels = [];
  155. // ignore template variable values
  156. each(dash.getVariables(), (variable: any) => {
  157. variable.current = null;
  158. variable.options = null;
  159. variable.filters = null;
  160. });
  161. return dash;
  162. }
  163. export function hasChanges(current: DashboardModel, original: any) {
  164. if (current.hasUnsavedChanges()) {
  165. return true;
  166. }
  167. const currentClean = cleanDashboardFromIgnoredChanges(current.getSaveModelClone());
  168. const originalClean = cleanDashboardFromIgnoredChanges(original);
  169. const currentTimepicker: any = find((currentClean as any).nav, { type: 'timepicker' });
  170. const originalTimepicker: any = find((originalClean as any).nav, { type: 'timepicker' });
  171. if (currentTimepicker && originalTimepicker) {
  172. currentTimepicker.now = originalTimepicker.now;
  173. }
  174. const currentJson = JSON.stringify(currentClean, null);
  175. const originalJson = JSON.stringify(originalClean, null);
  176. return currentJson !== originalJson;
  177. }