PanelChrome.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Libraries
  2. import React, { PureComponent } from 'react';
  3. import classNames from 'classnames';
  4. import { Unsubscribable } from 'rxjs';
  5. // Components
  6. import { PanelHeader } from './PanelHeader/PanelHeader';
  7. import { ErrorBoundary, PanelData, PanelPlugin } from '@grafana/ui';
  8. // Utils & Services
  9. import { getTimeSrv, TimeSrv } from '../services/TimeSrv';
  10. import { applyPanelTimeOverrides, calculateInnerPanelHeight } from 'app/features/dashboard/utils/panel';
  11. import { profiler } from 'app/core/profiler';
  12. import { getProcessedDataFrames } from '../state/runRequest';
  13. import templateSrv from 'app/features/templating/template_srv';
  14. import config from 'app/core/config';
  15. // Types
  16. import { DashboardModel, PanelModel } from '../state';
  17. import { LoadingState, ScopedVars, AbsoluteTimeRange, toUtc, toDataFrameDTO } from '@grafana/data';
  18. const DEFAULT_PLUGIN_ERROR = 'Error in plugin';
  19. export interface Props {
  20. panel: PanelModel;
  21. dashboard: DashboardModel;
  22. plugin: PanelPlugin;
  23. isFullscreen: boolean;
  24. isInView: boolean;
  25. width: number;
  26. height: number;
  27. }
  28. export interface State {
  29. isFirstLoad: boolean;
  30. renderCounter: number;
  31. errorMessage: string | null;
  32. refreshWhenInView: boolean;
  33. // Current state of all events
  34. data: PanelData;
  35. }
  36. export class PanelChrome extends PureComponent<Props, State> {
  37. timeSrv: TimeSrv = getTimeSrv();
  38. querySubscription: Unsubscribable;
  39. constructor(props: Props) {
  40. super(props);
  41. this.state = {
  42. isFirstLoad: true,
  43. renderCounter: 0,
  44. errorMessage: null,
  45. refreshWhenInView: false,
  46. data: {
  47. state: LoadingState.NotStarted,
  48. series: [],
  49. },
  50. };
  51. }
  52. componentDidMount() {
  53. const { panel, dashboard } = this.props;
  54. panel.events.on('refresh', this.onRefresh);
  55. panel.events.on('render', this.onRender);
  56. dashboard.panelInitialized(this.props.panel);
  57. // Move snapshot data into the query response
  58. if (this.hasPanelSnapshot) {
  59. this.setState({
  60. data: {
  61. state: LoadingState.Done,
  62. series: getProcessedDataFrames(panel.snapshotData),
  63. },
  64. isFirstLoad: false,
  65. });
  66. } else if (!this.wantsQueryExecution) {
  67. this.setState({ isFirstLoad: false });
  68. }
  69. }
  70. componentWillUnmount() {
  71. this.props.panel.events.off('refresh', this.onRefresh);
  72. if (this.querySubscription) {
  73. this.querySubscription.unsubscribe();
  74. this.querySubscription = null;
  75. }
  76. }
  77. componentDidUpdate(prevProps: Props) {
  78. const { isInView } = this.props;
  79. // View state has changed
  80. if (isInView !== prevProps.isInView) {
  81. if (isInView) {
  82. // Check if we need a delayed refresh
  83. if (this.state.refreshWhenInView) {
  84. this.onRefresh();
  85. }
  86. } else if (this.querySubscription) {
  87. this.querySubscription.unsubscribe();
  88. this.querySubscription = null;
  89. }
  90. }
  91. }
  92. // Updates the response with information from the stream
  93. // The next is outside a react synthetic event so setState is not batched
  94. // So in this context we can only do a single call to setState
  95. panelDataObserver = {
  96. next: (data: PanelData) => {
  97. if (!this.props.isInView) {
  98. // Ignore events when not visible.
  99. // The call will be repeated when the panel comes into view
  100. return;
  101. }
  102. let { errorMessage, isFirstLoad } = this.state;
  103. if (data.state === LoadingState.Error) {
  104. const { error } = data;
  105. if (error) {
  106. if (errorMessage !== error.message) {
  107. errorMessage = error.message;
  108. }
  109. }
  110. } else {
  111. errorMessage = null;
  112. }
  113. if (data.state === LoadingState.Done) {
  114. // If we are doing a snapshot save data in panel model
  115. if (this.props.dashboard.snapshot) {
  116. this.props.panel.snapshotData = data.series.map(frame => toDataFrameDTO(frame));
  117. }
  118. if (isFirstLoad) {
  119. isFirstLoad = false;
  120. }
  121. }
  122. this.setState({ isFirstLoad, errorMessage, data });
  123. },
  124. };
  125. onRefresh = () => {
  126. const { panel, isInView, width } = this.props;
  127. if (!isInView) {
  128. console.log('Refresh when panel is visible', panel.id);
  129. this.setState({ refreshWhenInView: true });
  130. return;
  131. }
  132. const timeData = applyPanelTimeOverrides(panel, this.timeSrv.timeRange());
  133. // Issue Query
  134. if (this.wantsQueryExecution) {
  135. if (width < 0) {
  136. console.log('Refresh skippted, no width yet... wait till we know');
  137. return;
  138. }
  139. const queryRunner = panel.getQueryRunner();
  140. if (!this.querySubscription) {
  141. this.querySubscription = queryRunner.getData().subscribe(this.panelDataObserver);
  142. }
  143. queryRunner.run({
  144. datasource: panel.datasource,
  145. queries: panel.targets,
  146. panelId: panel.id,
  147. dashboardId: this.props.dashboard.id,
  148. timezone: this.props.dashboard.getTimezone(),
  149. timeRange: timeData.timeRange,
  150. timeInfo: timeData.timeInfo,
  151. widthPixels: width,
  152. maxDataPoints: panel.maxDataPoints,
  153. minInterval: panel.interval,
  154. scopedVars: panel.scopedVars,
  155. cacheTimeout: panel.cacheTimeout,
  156. transformations: panel.transformations,
  157. });
  158. }
  159. };
  160. onRender = () => {
  161. const stateUpdate = { renderCounter: this.state.renderCounter + 1 };
  162. this.setState(stateUpdate);
  163. };
  164. onOptionsChange = (options: any) => {
  165. this.props.panel.updateOptions(options);
  166. };
  167. replaceVariables = (value: string, extraVars?: ScopedVars, format?: string) => {
  168. let vars = this.props.panel.scopedVars;
  169. if (extraVars) {
  170. vars = vars ? { ...vars, ...extraVars } : extraVars;
  171. }
  172. return templateSrv.replace(value, vars, format);
  173. };
  174. onPanelError = (message: string) => {
  175. if (this.state.errorMessage !== message) {
  176. this.setState({ errorMessage: message });
  177. }
  178. };
  179. get hasPanelSnapshot() {
  180. const { panel } = this.props;
  181. return panel.snapshotData && panel.snapshotData.length;
  182. }
  183. get wantsQueryExecution() {
  184. return !(this.props.plugin.meta.skipDataQuery || this.hasPanelSnapshot);
  185. }
  186. onChangeTimeRange = (timeRange: AbsoluteTimeRange) => {
  187. this.timeSrv.setTime({
  188. from: toUtc(timeRange.from),
  189. to: toUtc(timeRange.to),
  190. });
  191. };
  192. renderPanel(width: number, height: number): JSX.Element {
  193. const { panel, plugin } = this.props;
  194. const { renderCounter, data, isFirstLoad } = this.state;
  195. const { theme } = config;
  196. // This is only done to increase a counter that is used by backend
  197. // image rendering (phantomjs/headless chrome) to know when to capture image
  198. const loading = data.state;
  199. if (loading === LoadingState.Done) {
  200. profiler.renderingCompleted();
  201. }
  202. // do not render component until we have first data
  203. if (isFirstLoad && (loading === LoadingState.Loading || loading === LoadingState.NotStarted)) {
  204. return this.renderLoadingState();
  205. }
  206. const PanelComponent = plugin.panel;
  207. const innerPanelHeight = calculateInnerPanelHeight(panel, height);
  208. return (
  209. <>
  210. {loading === LoadingState.Loading && this.renderLoadingState()}
  211. <div className="panel-content">
  212. <PanelComponent
  213. id={panel.id}
  214. data={data}
  215. timeRange={data.request ? data.request.range : this.timeSrv.timeRange()}
  216. timeZone={this.props.dashboard.getTimezone()}
  217. options={panel.getOptions()}
  218. transparent={panel.transparent}
  219. width={width - theme.panelPadding * 2}
  220. height={innerPanelHeight}
  221. renderCounter={renderCounter}
  222. replaceVariables={this.replaceVariables}
  223. onOptionsChange={this.onOptionsChange}
  224. onChangeTimeRange={this.onChangeTimeRange}
  225. />
  226. </div>
  227. </>
  228. );
  229. }
  230. private renderLoadingState(): JSX.Element {
  231. return (
  232. <div className="panel-loading">
  233. <i className="fa fa-spinner fa-spin" />
  234. </div>
  235. );
  236. }
  237. render() {
  238. const { dashboard, panel, isFullscreen, width, height } = this.props;
  239. const { errorMessage, data } = this.state;
  240. const { transparent } = panel;
  241. const containerClassNames = classNames({
  242. 'panel-container': true,
  243. 'panel-container--absolute': true,
  244. 'panel-container--no-title': !panel.hasTitle(),
  245. 'panel-transparent': transparent,
  246. });
  247. return (
  248. <div className={containerClassNames}>
  249. <PanelHeader
  250. panel={panel}
  251. dashboard={dashboard}
  252. timeInfo={data.request ? data.request.timeInfo : null}
  253. title={panel.title}
  254. description={panel.description}
  255. scopedVars={panel.scopedVars}
  256. links={panel.links}
  257. error={errorMessage}
  258. isFullscreen={isFullscreen}
  259. />
  260. <ErrorBoundary>
  261. {({ error, errorInfo }) => {
  262. if (errorInfo) {
  263. this.onPanelError(error.message || DEFAULT_PLUGIN_ERROR);
  264. return null;
  265. }
  266. return this.renderPanel(width, height);
  267. }}
  268. </ErrorBoundary>
  269. </div>
  270. );
  271. }
  272. }