PanelChrome.tsx 8.7 KB

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