initDashboard.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. // Services & Utils
  2. import { createErrorNotification } from 'app/core/copy/appNotification';
  3. import { getBackendSrv } from 'app/core/services/backend_srv';
  4. import { DashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
  5. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  6. import { AnnotationsSrv } from 'app/features/annotations/annotations_srv';
  7. import { VariableSrv } from 'app/features/templating/variable_srv';
  8. import { KeybindingSrv } from 'app/core/services/keybindingSrv';
  9. import { config } from 'app/core/config';
  10. // Actions
  11. import { updateLocation } from 'app/core/actions';
  12. import { notifyApp } from 'app/core/actions';
  13. import locationUtil from 'app/core/utils/location_util';
  14. import { setDashboardLoadingState, ThunkResult, setDashboardModel, setDashboardLoadingSlow } from './actions';
  15. import { removePanel } from '../utils/panel';
  16. // Types
  17. import { DashboardLoadingState, DashboardRouteInfo } from 'app/types';
  18. import { DashboardModel } from './DashboardModel';
  19. export interface InitDashboardArgs {
  20. $injector: any;
  21. $scope: any;
  22. urlUid?: string;
  23. urlSlug?: string;
  24. urlType?: string;
  25. urlFolderId?: string;
  26. routeInfo: string;
  27. fixUrl: boolean;
  28. }
  29. async function redirectToNewUrl(slug: string, dispatch: any, currentPath: string) {
  30. const res = await getBackendSrv().getDashboardBySlug(slug);
  31. if (res) {
  32. let newUrl = res.meta.url;
  33. // fix solo route urls
  34. if (currentPath.indexOf('dashboard-solo') !== -1) {
  35. newUrl = newUrl.replace('/d/', '/d-solo/');
  36. }
  37. const url = locationUtil.stripBaseFromUrl(newUrl);
  38. dispatch(updateLocation({ path: url, partial: true, replace: true }));
  39. }
  40. }
  41. /**
  42. * This action (or saga) does everything needed to bootstrap a dashboard & dashboard model.
  43. * First it handles the process of fetching the dashboard, correcting the url if required (causing redirects/url updates)
  44. *
  45. * This is used both for single dashboard & solo panel routes, home & new dashboard routes.
  46. *
  47. * Then it handles the initializing of the old angular services that the dashboard components & panels still depend on
  48. *
  49. */
  50. export function initDashboard({
  51. $injector,
  52. $scope,
  53. urlUid,
  54. urlSlug,
  55. urlType,
  56. urlFolderId,
  57. routeInfo,
  58. fixUrl,
  59. }: InitDashboardArgs): ThunkResult<void> {
  60. return async (dispatch, getState) => {
  61. let dashDTO = null;
  62. // set fetching state
  63. dispatch(setDashboardLoadingState(DashboardLoadingState.Fetching));
  64. // Detect slow loading / initializing and set state flag
  65. // This is in order to not show loading indication for fast loading dashboards as it creates blinking/flashing
  66. setTimeout(() => {
  67. if (getState().dashboard.model === null) {
  68. dispatch(setDashboardLoadingSlow());
  69. }
  70. }, 500);
  71. try {
  72. switch (routeInfo) {
  73. // handle old urls with no uid
  74. case DashboardRouteInfo.Home: {
  75. // load home dash
  76. dashDTO = await getBackendSrv().get('/api/dashboards/home');
  77. // if user specified a custom home dashboard redirect to that
  78. if (dashDTO.redirectUri) {
  79. const newUrl = locationUtil.stripBaseFromUrl(dashDTO.redirectUri);
  80. dispatch(updateLocation({ path: newUrl, replace: true }));
  81. return;
  82. }
  83. // disable some actions on the default home dashboard
  84. dashDTO.meta.canSave = false;
  85. dashDTO.meta.canShare = false;
  86. dashDTO.meta.canStar = false;
  87. break;
  88. }
  89. case DashboardRouteInfo.Normal: {
  90. // for old db routes we redirect
  91. if (urlType === 'db') {
  92. redirectToNewUrl(urlSlug, dispatch, getState().location.path);
  93. return;
  94. }
  95. const loaderSrv = $injector.get('dashboardLoaderSrv');
  96. dashDTO = await loaderSrv.loadDashboard(urlType, urlSlug, urlUid);
  97. if (fixUrl && dashDTO.meta.url) {
  98. // check if the current url is correct (might be old slug)
  99. const dashboardUrl = locationUtil.stripBaseFromUrl(dashDTO.meta.url);
  100. const currentPath = getState().location.path;
  101. if (dashboardUrl !== currentPath) {
  102. // replace url to not create additional history items and then return so that initDashboard below isn't executed multiple times.
  103. dispatch(updateLocation({ path: dashboardUrl, partial: true, replace: true }));
  104. return;
  105. }
  106. }
  107. break;
  108. }
  109. case DashboardRouteInfo.New: {
  110. dashDTO = getNewDashboardModelData(urlFolderId);
  111. break;
  112. }
  113. }
  114. } catch (err) {
  115. dispatch(setDashboardLoadingState(DashboardLoadingState.Error));
  116. console.log(err);
  117. return;
  118. }
  119. // set initializing state
  120. dispatch(setDashboardLoadingState(DashboardLoadingState.Initializing));
  121. // create model
  122. let dashboard: DashboardModel;
  123. try {
  124. dashboard = new DashboardModel(dashDTO.dashboard, dashDTO.meta);
  125. } catch (err) {
  126. dispatch(setDashboardLoadingState(DashboardLoadingState.Error));
  127. console.log(err);
  128. return;
  129. }
  130. // add missing orgId query param
  131. if (!getState().location.query.orgId) {
  132. dispatch(updateLocation({ query: { orgId: config.bootData.user.orgId }, partial: true, replace: true }));
  133. }
  134. // init services
  135. const timeSrv: TimeSrv = $injector.get('timeSrv');
  136. const annotationsSrv: AnnotationsSrv = $injector.get('annotationsSrv');
  137. const variableSrv: VariableSrv = $injector.get('variableSrv');
  138. const keybindingSrv: KeybindingSrv = $injector.get('keybindingSrv');
  139. const unsavedChangesSrv = $injector.get('unsavedChangesSrv');
  140. const dashboardSrv: DashboardSrv = $injector.get('dashboardSrv');
  141. timeSrv.init(dashboard);
  142. annotationsSrv.init(dashboard);
  143. // template values service needs to initialize completely before
  144. // the rest of the dashboard can load
  145. try {
  146. await variableSrv.init(dashboard);
  147. } catch (err) {
  148. dispatch(notifyApp(createErrorNotification('Templating init failed')));
  149. console.log(err);
  150. }
  151. try {
  152. dashboard.processRepeats();
  153. dashboard.updateSubmenuVisibility();
  154. // handle auto fix experimental feature
  155. const queryParams = getState().location.query;
  156. if (queryParams.autofitpanels) {
  157. dashboard.autoFitPanels(window.innerHeight, queryParams.kiosk);
  158. }
  159. // init unsaved changes tracking
  160. unsavedChangesSrv.init(dashboard, $scope);
  161. // dashboard keybindings should not live in core, this needs a bigger refactoring
  162. // So declaring this here so it can depend on the removePanel util function
  163. // Long term onRemovePanel should be handled via react prop callback
  164. const onRemovePanel = (panelId: number) => {
  165. removePanel(dashboard, dashboard.getPanelById(panelId), true);
  166. };
  167. keybindingSrv.setupDashboardBindings($scope, dashboard, onRemovePanel);
  168. } catch (err) {
  169. dispatch(notifyApp(createErrorNotification('Dashboard init failed', err.toString())));
  170. console.log(err);
  171. }
  172. // legacy srv state
  173. dashboardSrv.setCurrent(dashboard);
  174. // set model in redux (even though it's mutable)
  175. dispatch(setDashboardModel(dashboard));
  176. };
  177. }
  178. function getNewDashboardModelData(urlFolderId?: string): any {
  179. const data = {
  180. meta: {
  181. canStar: false,
  182. canShare: false,
  183. isNew: true,
  184. folderId: 0,
  185. },
  186. dashboard: {
  187. title: 'New dashboard',
  188. panels: [
  189. {
  190. type: 'add-panel',
  191. gridPos: { x: 0, y: 0, w: 12, h: 9 },
  192. title: 'Panel Title',
  193. },
  194. ],
  195. },
  196. };
  197. if (urlFolderId) {
  198. data.meta.folderId = parseInt(urlFolderId, 10);
  199. }
  200. return data;
  201. }