DashboardPage.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. import { css } from '@emotion/css';
  2. import classnames from 'classnames';
  3. import React, { PureComponent } from 'react';
  4. import { connect, ConnectedProps } from 'react-redux';
  5. import { GrafanaTheme2, TimeRange } from '@grafana/data';
  6. import { selectors } from '@grafana/e2e-selectors';
  7. import { locationService } from '@grafana/runtime';
  8. import { CustomScrollbar, stylesFactory, Themeable2, withTheme2 } from '@grafana/ui';
  9. import { notifyApp } from 'app/core/actions';
  10. import { Branding } from 'app/core/components/Branding/Branding';
  11. import { createErrorNotification } from 'app/core/copy/appNotification';
  12. import { getKioskMode } from 'app/core/navigation/kiosk';
  13. import { GrafanaRouteComponentProps } from 'app/core/navigation/types';
  14. import { PanelModel } from 'app/features/dashboard/state';
  15. import { dashboardWatcher } from 'app/features/live/dashboard/dashboardWatcher';
  16. import { KioskMode, StoreState } from 'app/types';
  17. import { PanelEditEnteredEvent, PanelEditExitedEvent } from 'app/types/events';
  18. import { cancelVariables, templateVarsChangedInUrl } from '../../variables/state/actions';
  19. import { findTemplateVarChanges } from '../../variables/utils';
  20. import { DashNav } from '../components/DashNav';
  21. import { DashboardFailed } from '../components/DashboardLoading/DashboardFailed';
  22. import { DashboardLoading } from '../components/DashboardLoading/DashboardLoading';
  23. import { DashboardPrompt } from '../components/DashboardPrompt/DashboardPrompt';
  24. import { DashboardSettings } from '../components/DashboardSettings';
  25. import { PanelInspector } from '../components/Inspector/PanelInspector';
  26. import { PanelEditor } from '../components/PanelEditor/PanelEditor';
  27. import { SubMenu } from '../components/SubMenu/SubMenu';
  28. import { DashboardGrid } from '../dashgrid/DashboardGrid';
  29. import { liveTimer } from '../dashgrid/liveTimer';
  30. import { getTimeSrv } from '../services/TimeSrv';
  31. import { cleanUpDashboardAndVariables } from '../state/actions';
  32. import { initDashboard } from '../state/initDashboard';
  33. export interface DashboardPageRouteParams {
  34. uid?: string;
  35. type?: string;
  36. slug?: string;
  37. }
  38. type DashboardPageRouteSearchParams = {
  39. tab?: string;
  40. folderId?: string;
  41. editPanel?: string;
  42. viewPanel?: string;
  43. editview?: string;
  44. inspect?: string;
  45. from?: string;
  46. to?: string;
  47. refresh?: string;
  48. };
  49. export const mapStateToProps = (state: StoreState) => ({
  50. initPhase: state.dashboard.initPhase,
  51. initError: state.dashboard.initError,
  52. dashboard: state.dashboard.getModel(),
  53. });
  54. const mapDispatchToProps = {
  55. initDashboard,
  56. cleanUpDashboardAndVariables,
  57. notifyApp,
  58. cancelVariables,
  59. templateVarsChangedInUrl,
  60. };
  61. const connector = connect(mapStateToProps, mapDispatchToProps);
  62. export type Props = Themeable2 &
  63. GrafanaRouteComponentProps<DashboardPageRouteParams, DashboardPageRouteSearchParams> &
  64. ConnectedProps<typeof connector>;
  65. export interface State {
  66. editPanel: PanelModel | null;
  67. viewPanel: PanelModel | null;
  68. updateScrollTop?: number;
  69. rememberScrollTop: number;
  70. showLoadingState: boolean;
  71. panelNotFound: boolean;
  72. editPanelAccessDenied: boolean;
  73. scrollElement?: HTMLDivElement;
  74. }
  75. export class UnthemedDashboardPage extends PureComponent<Props, State> {
  76. private forceRouteReloadCounter = 0;
  77. state: State = this.getCleanState();
  78. getCleanState(): State {
  79. return {
  80. editPanel: null,
  81. viewPanel: null,
  82. showLoadingState: false,
  83. rememberScrollTop: 0,
  84. panelNotFound: false,
  85. editPanelAccessDenied: false,
  86. };
  87. }
  88. componentDidMount() {
  89. this.initDashboard();
  90. this.forceRouteReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter || 0;
  91. }
  92. componentWillUnmount() {
  93. this.closeDashboard();
  94. }
  95. closeDashboard() {
  96. this.props.cleanUpDashboardAndVariables();
  97. this.setState(this.getCleanState());
  98. }
  99. initDashboard() {
  100. const { dashboard, match, queryParams } = this.props;
  101. if (dashboard) {
  102. this.closeDashboard();
  103. }
  104. this.props.initDashboard({
  105. urlSlug: match.params.slug,
  106. urlUid: match.params.uid,
  107. urlType: match.params.type,
  108. urlFolderId: queryParams.folderId,
  109. routeName: this.props.route.routeName,
  110. fixUrl: true,
  111. });
  112. // small delay to start live updates
  113. setTimeout(this.updateLiveTimer, 250);
  114. }
  115. componentDidUpdate(prevProps: Props, prevState: State) {
  116. const { dashboard, match, templateVarsChangedInUrl } = this.props;
  117. const routeReloadCounter = (this.props.history.location.state as any)?.routeReloadCounter;
  118. if (!dashboard) {
  119. return;
  120. }
  121. // if we just got dashboard update title
  122. if (prevProps.dashboard !== dashboard) {
  123. document.title = dashboard.title + ' - ' + Branding.AppTitle;
  124. }
  125. if (
  126. prevProps.match.params.uid !== match.params.uid ||
  127. (routeReloadCounter !== undefined && this.forceRouteReloadCounter !== routeReloadCounter)
  128. ) {
  129. this.initDashboard();
  130. this.forceRouteReloadCounter = routeReloadCounter;
  131. return;
  132. }
  133. if (prevProps.location.search !== this.props.location.search) {
  134. const prevUrlParams = prevProps.queryParams;
  135. const urlParams = this.props.queryParams;
  136. if (urlParams?.from !== prevUrlParams?.from || urlParams?.to !== prevUrlParams?.to) {
  137. getTimeSrv().updateTimeRangeFromUrl();
  138. this.updateLiveTimer();
  139. }
  140. if (!prevUrlParams?.refresh && urlParams?.refresh) {
  141. getTimeSrv().setAutoRefresh(urlParams.refresh);
  142. }
  143. const templateVarChanges = findTemplateVarChanges(this.props.queryParams, prevProps.queryParams);
  144. if (templateVarChanges) {
  145. templateVarsChangedInUrl(dashboard.uid, templateVarChanges);
  146. }
  147. }
  148. // entering edit mode
  149. if (this.state.editPanel && !prevState.editPanel) {
  150. dashboardWatcher.setEditingState(true);
  151. // Some panels need to be notified when entering edit mode
  152. this.props.dashboard?.events.publish(new PanelEditEnteredEvent(this.state.editPanel.id));
  153. }
  154. // leaving edit mode
  155. if (!this.state.editPanel && prevState.editPanel) {
  156. dashboardWatcher.setEditingState(false);
  157. // Some panels need kicked when leaving edit mode
  158. this.props.dashboard?.events.publish(new PanelEditExitedEvent(prevState.editPanel.id));
  159. }
  160. if (this.state.editPanelAccessDenied) {
  161. this.props.notifyApp(createErrorNotification('Permission to edit panel denied'));
  162. locationService.partial({ editPanel: null });
  163. }
  164. if (this.state.panelNotFound) {
  165. this.props.notifyApp(createErrorNotification(`Panel not found`));
  166. locationService.partial({ editPanel: null, viewPanel: null });
  167. }
  168. }
  169. updateLiveTimer = () => {
  170. let tr: TimeRange | undefined = undefined;
  171. if (this.props.dashboard?.liveNow) {
  172. tr = getTimeSrv().timeRange();
  173. }
  174. liveTimer.setLiveTimeRange(tr);
  175. };
  176. static getDerivedStateFromProps(props: Props, state: State) {
  177. const { dashboard, queryParams } = props;
  178. const urlEditPanelId = queryParams.editPanel;
  179. const urlViewPanelId = queryParams.viewPanel;
  180. if (!dashboard) {
  181. return state;
  182. }
  183. // Entering edit mode
  184. if (!state.editPanel && urlEditPanelId) {
  185. const panel = dashboard.getPanelByUrlId(urlEditPanelId);
  186. if (!panel) {
  187. return { ...state, panelNotFound: true };
  188. }
  189. if (dashboard.canEditPanel(panel)) {
  190. return { ...state, editPanel: panel, rememberScrollTop: state.scrollElement?.scrollTop };
  191. } else {
  192. return { ...state, editPanelAccessDenied: true };
  193. }
  194. }
  195. // Leaving edit mode
  196. else if (state.editPanel && !urlEditPanelId) {
  197. return { ...state, editPanel: null, updateScrollTop: state.rememberScrollTop };
  198. }
  199. // Entering view mode
  200. if (!state.viewPanel && urlViewPanelId) {
  201. const panel = dashboard.getPanelByUrlId(urlViewPanelId);
  202. if (!panel) {
  203. return { ...state, panelNotFound: urlEditPanelId };
  204. }
  205. // This mutable state feels wrong to have in getDerivedStateFromProps
  206. // Should move this state out of dashboard in the future
  207. dashboard.initViewPanel(panel);
  208. return { ...state, viewPanel: panel, rememberScrollTop: state.scrollElement?.scrollTop, updateScrollTop: 0 };
  209. }
  210. // Leaving view mode
  211. else if (state.viewPanel && !urlViewPanelId) {
  212. // This mutable state feels wrong to have in getDerivedStateFromProps
  213. // Should move this state out of dashboard in the future
  214. dashboard.exitViewPanel(state.viewPanel);
  215. return { ...state, viewPanel: null, updateScrollTop: state.rememberScrollTop };
  216. }
  217. // if we removed url edit state, clear any panel not found state
  218. if (state.panelNotFound || (state.editPanelAccessDenied && !urlEditPanelId)) {
  219. return { ...state, panelNotFound: false, editPanelAccessDenied: false };
  220. }
  221. return state;
  222. }
  223. onAddPanel = () => {
  224. const { dashboard } = this.props;
  225. if (!dashboard) {
  226. return;
  227. }
  228. // Return if the "Add panel" exists already
  229. if (dashboard.panels.length > 0 && dashboard.panels[0].type === 'add-panel') {
  230. return;
  231. }
  232. dashboard.addPanel({
  233. type: 'add-panel',
  234. gridPos: { x: 0, y: 0, w: 12, h: 8 },
  235. title: 'Panel Title',
  236. });
  237. // scroll to top after adding panel
  238. this.setState({ updateScrollTop: 0 });
  239. };
  240. setScrollRef = (scrollElement: HTMLDivElement): void => {
  241. this.setState({ scrollElement });
  242. };
  243. getInspectPanel() {
  244. const { dashboard, queryParams } = this.props;
  245. const inspectPanelId = queryParams.inspect;
  246. if (!dashboard || !inspectPanelId) {
  247. return null;
  248. }
  249. const inspectPanel = dashboard.getPanelById(parseInt(inspectPanelId, 10));
  250. // cannot inspect panels plugin is not already loaded
  251. if (!inspectPanel) {
  252. return null;
  253. }
  254. return inspectPanel;
  255. }
  256. render() {
  257. const { dashboard, initError, queryParams, theme } = this.props;
  258. const { editPanel, viewPanel, updateScrollTop } = this.state;
  259. const kioskMode = getKioskMode();
  260. const styles = getStyles(theme, kioskMode);
  261. if (!dashboard) {
  262. return <DashboardLoading initPhase={this.props.initPhase} />;
  263. }
  264. const inspectPanel = this.getInspectPanel();
  265. const containerClassNames = classnames(styles.dashboardContainer, {
  266. 'panel-in-fullscreen': viewPanel,
  267. });
  268. const showSubMenu = !editPanel && kioskMode === KioskMode.Off && !this.props.queryParams.editview;
  269. return (
  270. <div className={containerClassNames}>
  271. {kioskMode !== KioskMode.Full && (
  272. <header data-testid={selectors.pages.Dashboard.DashNav.navV2}>
  273. <DashNav
  274. dashboard={dashboard}
  275. title={dashboard.title}
  276. folderTitle={dashboard.meta.folderTitle}
  277. isFullscreen={!!viewPanel}
  278. onAddPanel={this.onAddPanel}
  279. kioskMode={kioskMode}
  280. hideTimePicker={dashboard.timepicker.hidden}
  281. />
  282. </header>
  283. )}
  284. <DashboardPrompt dashboard={dashboard} />
  285. <div className={styles.dashboardScroll}>
  286. <CustomScrollbar
  287. autoHeightMin="100%"
  288. scrollRefCallback={this.setScrollRef}
  289. scrollTop={updateScrollTop}
  290. hideHorizontalTrack={true}
  291. updateAfterMountMs={500}
  292. >
  293. <div className={styles.dashboardContent}>
  294. {initError && <DashboardFailed />}
  295. {showSubMenu && (
  296. <section aria-label={selectors.pages.Dashboard.SubMenu.submenu}>
  297. <SubMenu dashboard={dashboard} annotations={dashboard.annotations.list} links={dashboard.links} />
  298. </section>
  299. )}
  300. <DashboardGrid dashboard={dashboard} viewPanel={viewPanel} editPanel={editPanel} />
  301. </div>
  302. </CustomScrollbar>
  303. </div>
  304. {inspectPanel && <PanelInspector dashboard={dashboard} panel={inspectPanel} />}
  305. {editPanel && <PanelEditor dashboard={dashboard} sourcePanel={editPanel} tab={this.props.queryParams.tab} />}
  306. {queryParams.editview && <DashboardSettings dashboard={dashboard} editview={queryParams.editview} />}
  307. </div>
  308. );
  309. }
  310. }
  311. /*
  312. * Styles
  313. */
  314. export const getStyles = stylesFactory((theme: GrafanaTheme2, kioskMode: KioskMode) => {
  315. const contentPadding = kioskMode !== KioskMode.Full ? theme.spacing(0, 2, 2) : theme.spacing(2);
  316. return {
  317. dashboardContainer: css`
  318. width: 100%;
  319. height: 100%;
  320. display: flex;
  321. flex: 1 1 0;
  322. flex-direction: column;
  323. min-height: 0;
  324. `,
  325. dashboardScroll: css`
  326. width: 100%;
  327. flex-grow: 1;
  328. min-height: 0;
  329. display: flex;
  330. `,
  331. dashboardContent: css`
  332. padding: ${contentPadding};
  333. flex-basis: 100%;
  334. flex-grow: 1;
  335. `,
  336. };
  337. });
  338. export const DashboardPage = withTheme2(UnthemedDashboardPage);
  339. DashboardPage.displayName = 'DashboardPage';
  340. export default connector(DashboardPage);