initDashboard.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. // Libraries
  2. import { ThunkDispatch } from 'redux-thunk';
  3. // Services & Utils
  4. import { createErrorNotification } from 'app/core/copy/appNotification';
  5. import { getBackendSrv } from 'app/core/services/backend_srv';
  6. import { DashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
  7. import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
  8. import { AnnotationsSrv } from 'app/features/annotations/annotations_srv';
  9. import { VariableSrv } from 'app/features/templating/variable_srv';
  10. import { KeybindingSrv } from 'app/core/services/keybindingSrv';
  11. import { config } from 'app/core/config';
  12. // Actions
  13. import { updateLocation } from 'app/core/actions';
  14. import { notifyApp } from 'app/core/actions';
  15. import locationUtil from 'app/core/utils/location_util';
  16. import { setDashboardLoadingState, ThunkResult, setDashboardModel, setDashboardLoadingSlow } from './actions';
  17. // Types
  18. import { DashboardLoadingState, DashboardRouteInfo, StoreState } from 'app/types';
  19. import { DashboardModel } from './DashboardModel';
  20. export type Dispatch = ThunkDispatch<StoreState, undefined, any>;
  21. export interface InitDashboardArgs {
  22. $injector: any;
  23. $scope: any;
  24. urlUid?: string;
  25. urlSlug?: string;
  26. urlType?: string;
  27. urlFolderId?: string;
  28. routeInfo: DashboardRouteInfo;
  29. fixUrl: boolean;
  30. }
  31. async function redirectToNewUrl(slug: string, dispatch: Dispatch, currentPath: string) {
  32. const res = await getBackendSrv().getDashboardBySlug(slug);
  33. if (res) {
  34. let newUrl = res.meta.url;
  35. // fix solo route urls
  36. if (currentPath.indexOf('dashboard-solo') !== -1) {
  37. newUrl = newUrl.replace('/d/', '/d-solo/');
  38. }
  39. const url = locationUtil.stripBaseFromUrl(newUrl);
  40. dispatch(updateLocation({ path: url, partial: true, replace: true }));
  41. }
  42. }
  43. async function fetchDashboard(args: InitDashboardArgs, dispatch: Dispatch, getState: () => StoreState): Promise<any> {
  44. try {
  45. switch (args.routeInfo) {
  46. case DashboardRouteInfo.Home: {
  47. // load home dash
  48. const dashDTO = await getBackendSrv().get('/api/dashboards/home');
  49. // if user specified a custom home dashboard redirect to that
  50. if (dashDTO.redirectUri) {
  51. const newUrl = locationUtil.stripBaseFromUrl(dashDTO.redirectUri);
  52. dispatch(updateLocation({ path: newUrl, replace: true }));
  53. return;
  54. }
  55. // disable some actions on the default home dashboard
  56. dashDTO.meta.canSave = false;
  57. dashDTO.meta.canShare = false;
  58. dashDTO.meta.canStar = false;
  59. return dashDTO;
  60. }
  61. case DashboardRouteInfo.Normal: {
  62. // for old db routes we redirect
  63. if (args.urlType === 'db') {
  64. redirectToNewUrl(args.urlSlug, dispatch, getState().location.path);
  65. return null;
  66. }
  67. const loaderSrv = args.$injector.get('dashboardLoaderSrv');
  68. const dashDTO = await loaderSrv.loadDashboard(args.urlType, args.urlSlug, args.urlUid);
  69. if (args.fixUrl && dashDTO.meta.url) {
  70. // check if the current url is correct (might be old slug)
  71. const dashboardUrl = locationUtil.stripBaseFromUrl(dashDTO.meta.url);
  72. const currentPath = getState().location.path;
  73. if (dashboardUrl !== currentPath) {
  74. // replace url to not create additional history items and then return so that initDashboard below isn't executed multiple times.
  75. dispatch(updateLocation({ path: dashboardUrl, partial: true, replace: true }));
  76. return null;
  77. }
  78. }
  79. return dashDTO;
  80. }
  81. case DashboardRouteInfo.New: {
  82. return getNewDashboardModelData(args.urlFolderId);
  83. }
  84. }
  85. } catch (err) {
  86. dispatch(setDashboardLoadingState(DashboardLoadingState.Error));
  87. dispatch(notifyApp(createErrorNotification('Dashboard fetch failed', err)));
  88. console.log(err);
  89. return null;
  90. }
  91. }
  92. /**
  93. * This action (or saga) does everything needed to bootstrap a dashboard & dashboard model.
  94. * First it handles the process of fetching the dashboard, correcting the url if required (causing redirects/url updates)
  95. *
  96. * This is used both for single dashboard & solo panel routes, home & new dashboard routes.
  97. *
  98. * Then it handles the initializing of the old angular services that the dashboard components & panels still depend on
  99. *
  100. */
  101. export function initDashboard(args: InitDashboardArgs): ThunkResult<void> {
  102. return async (dispatch, getState) => {
  103. // set fetching state
  104. dispatch(setDashboardLoadingState(DashboardLoadingState.Fetching));
  105. // Detect slow loading / initializing and set state flag
  106. // This is in order to not show loading indication for fast loading dashboards as it creates blinking/flashing
  107. setTimeout(() => {
  108. if (getState().dashboard.model === null) {
  109. dispatch(setDashboardLoadingSlow());
  110. }
  111. }, 500);
  112. // fetch dashboard data
  113. const dashDTO = await fetchDashboard(args, dispatch, getState);
  114. // returns null if there was a redirect or error
  115. if (!dashDTO) {
  116. return;
  117. }
  118. // set initializing state
  119. dispatch(setDashboardLoadingState(DashboardLoadingState.Initializing));
  120. // create model
  121. let dashboard: DashboardModel;
  122. try {
  123. dashboard = new DashboardModel(dashDTO.dashboard, dashDTO.meta);
  124. } catch (err) {
  125. dispatch(setDashboardLoadingState(DashboardLoadingState.Error));
  126. dispatch(notifyApp(createErrorNotification('Dashboard model initializing failure', err)));
  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 = args.$injector.get('timeSrv');
  136. const annotationsSrv: AnnotationsSrv = args.$injector.get('annotationsSrv');
  137. const variableSrv: VariableSrv = args.$injector.get('variableSrv');
  138. const keybindingSrv: KeybindingSrv = args.$injector.get('keybindingSrv');
  139. const unsavedChangesSrv = args.$injector.get('unsavedChangesSrv');
  140. const dashboardSrv: DashboardSrv = args.$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', err)));
  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, args.$scope);
  161. keybindingSrv.setupDashboardBindings(args.$scope, dashboard);
  162. } catch (err) {
  163. dispatch(notifyApp(createErrorNotification('Dashboard init failed', err)));
  164. console.log(err);
  165. }
  166. // legacy srv state
  167. dashboardSrv.setCurrent(dashboard);
  168. // set model in redux (even though it's mutable)
  169. dispatch(setDashboardModel(dashboard));
  170. };
  171. }
  172. function getNewDashboardModelData(urlFolderId?: string): any {
  173. const data = {
  174. meta: {
  175. canStar: false,
  176. canShare: false,
  177. isNew: true,
  178. folderId: 0,
  179. },
  180. dashboard: {
  181. title: 'New dashboard',
  182. panels: [
  183. {
  184. type: 'add-panel',
  185. gridPos: { x: 0, y: 0, w: 12, h: 9 },
  186. title: 'Panel Title',
  187. },
  188. ],
  189. },
  190. };
  191. if (urlFolderId) {
  192. data.meta.folderId = parseInt(urlFolderId, 10);
  193. }
  194. return data;
  195. }