Graph.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import $ from 'jquery';
  2. import React, { PureComponent } from 'react';
  3. import moment from 'moment';
  4. import { AutoSizer } from 'react-virtualized';
  5. import 'vendor/flot/jquery.flot';
  6. import 'vendor/flot/jquery.flot.time';
  7. import 'vendor/flot/jquery.flot.selection';
  8. import 'vendor/flot/jquery.flot.stack';
  9. import { RawTimeRange } from '@grafana/ui';
  10. import * as dateMath from 'app/core/utils/datemath';
  11. import TimeSeries from 'app/core/time_series2';
  12. import Legend from './Legend';
  13. import { equal, intersect } from './utils/set';
  14. const MAX_NUMBER_OF_TIME_SERIES = 20;
  15. // Copied from graph.ts
  16. function time_format(ticks, min, max) {
  17. if (min && max && ticks) {
  18. const range = max - min;
  19. const secPerTick = range / ticks / 1000;
  20. const oneDay = 86400000;
  21. const oneYear = 31536000000;
  22. if (secPerTick <= 45) {
  23. return '%H:%M:%S';
  24. }
  25. if (secPerTick <= 7200 || range <= oneDay) {
  26. return '%H:%M';
  27. }
  28. if (secPerTick <= 80000) {
  29. return '%m/%d %H:%M';
  30. }
  31. if (secPerTick <= 2419200 || range <= oneYear) {
  32. return '%m/%d';
  33. }
  34. return '%Y-%m';
  35. }
  36. return '%H:%M';
  37. }
  38. const FLOT_OPTIONS = {
  39. legend: {
  40. show: false,
  41. },
  42. series: {
  43. lines: {
  44. linewidth: 1,
  45. zero: false,
  46. },
  47. shadowSize: 0,
  48. },
  49. grid: {
  50. minBorderMargin: 0,
  51. markings: [],
  52. backgroundColor: null,
  53. borderWidth: 0,
  54. // hoverable: true,
  55. clickable: true,
  56. color: '#a1a1a1',
  57. margin: { left: 0, right: 0 },
  58. labelMarginX: 0,
  59. },
  60. selection: {
  61. mode: 'x',
  62. color: '#666',
  63. },
  64. // crosshair: {
  65. // mode: 'x',
  66. // },
  67. };
  68. interface GraphProps {
  69. data: any[];
  70. height?: string; // e.g., '200px'
  71. id?: string;
  72. range: RawTimeRange;
  73. split?: boolean;
  74. userOptions?: any;
  75. onChangeTime?: (range: RawTimeRange) => void;
  76. onToggleSeries?: (alias: string, hiddenSeries: Set<string>) => void;
  77. }
  78. interface SizedGraphProps extends GraphProps {
  79. size: { width: number; height: number };
  80. }
  81. interface GraphState {
  82. /**
  83. * Type parameter refers to the `alias` property of a `TimeSeries`.
  84. * Consequently, all series sharing the same alias will share visibility state.
  85. */
  86. hiddenSeries: Set<string>;
  87. showAllTimeSeries: boolean;
  88. }
  89. export class Graph extends PureComponent<SizedGraphProps, GraphState> {
  90. $el: any;
  91. dynamicOptions = null;
  92. state = {
  93. hiddenSeries: new Set(),
  94. showAllTimeSeries: false,
  95. };
  96. getGraphData() {
  97. const { data } = this.props;
  98. return this.state.showAllTimeSeries ? data : data.slice(0, MAX_NUMBER_OF_TIME_SERIES);
  99. }
  100. componentDidMount() {
  101. this.draw();
  102. this.$el = $(`#${this.props.id}`);
  103. this.$el.bind('plotselected', this.onPlotSelected);
  104. }
  105. componentDidUpdate(prevProps: SizedGraphProps, prevState: GraphState) {
  106. if (
  107. prevProps.data !== this.props.data ||
  108. prevProps.range !== this.props.range ||
  109. prevProps.split !== this.props.split ||
  110. prevProps.height !== this.props.height ||
  111. (prevProps.size && prevProps.size.width !== this.props.size.width) ||
  112. !equal(prevState.hiddenSeries, this.state.hiddenSeries)
  113. ) {
  114. this.draw();
  115. }
  116. }
  117. componentWillUnmount() {
  118. this.$el.unbind('plotselected', this.onPlotSelected);
  119. }
  120. onPlotSelected = (event, ranges) => {
  121. if (this.props.onChangeTime) {
  122. const range = {
  123. from: moment(ranges.xaxis.from),
  124. to: moment(ranges.xaxis.to),
  125. };
  126. this.props.onChangeTime(range);
  127. }
  128. };
  129. getDynamicOptions() {
  130. const { range, size } = this.props;
  131. const ticks = (size.width || 0) / 100;
  132. let { from, to } = range;
  133. if (!moment.isMoment(from)) {
  134. from = dateMath.parse(from, false);
  135. }
  136. if (!moment.isMoment(to)) {
  137. to = dateMath.parse(to, true);
  138. }
  139. const min = from.valueOf();
  140. const max = to.valueOf();
  141. return {
  142. xaxis: {
  143. mode: 'time',
  144. min: min,
  145. max: max,
  146. label: 'Datetime',
  147. ticks: ticks,
  148. timezone: 'browser',
  149. timeformat: time_format(ticks, min, max),
  150. },
  151. };
  152. }
  153. onShowAllTimeSeries = () => {
  154. this.setState(
  155. {
  156. showAllTimeSeries: true,
  157. },
  158. this.draw
  159. );
  160. };
  161. onToggleSeries = (series: TimeSeries, exclusive: boolean) => {
  162. this.setState((state, props) => {
  163. const { data, onToggleSeries } = props;
  164. const { hiddenSeries } = state;
  165. // Deduplicate series as visibility tracks the alias property
  166. const oneSeriesVisible = hiddenSeries.size === new Set(data.map(d => d.alias)).size - 1;
  167. let nextHiddenSeries = new Set();
  168. if (exclusive) {
  169. if (hiddenSeries.has(series.alias) || !oneSeriesVisible) {
  170. nextHiddenSeries = new Set(data.filter(d => d.alias !== series.alias).map(d => d.alias));
  171. }
  172. } else {
  173. // Prune hidden series no longer part of those available from the most recent query
  174. const availableSeries = new Set(data.map(d => d.alias));
  175. nextHiddenSeries = intersect(new Set(hiddenSeries), availableSeries);
  176. if (nextHiddenSeries.has(series.alias)) {
  177. nextHiddenSeries.delete(series.alias);
  178. } else {
  179. nextHiddenSeries.add(series.alias);
  180. }
  181. }
  182. if (onToggleSeries) {
  183. onToggleSeries(series.alias, nextHiddenSeries);
  184. }
  185. return {
  186. hiddenSeries: nextHiddenSeries,
  187. };
  188. }, this.draw);
  189. };
  190. draw() {
  191. const { userOptions = {} } = this.props;
  192. const { hiddenSeries } = this.state;
  193. const data = this.getGraphData();
  194. const $el = $(`#${this.props.id}`);
  195. let series = [{ data: [[0, 0]] }];
  196. if (data && data.length > 0) {
  197. series = data.filter((ts: TimeSeries) => !hiddenSeries.has(ts.alias)).map((ts: TimeSeries) => ({
  198. color: ts.color,
  199. label: ts.label,
  200. data: ts.getFlotPairs('null'),
  201. }));
  202. }
  203. this.dynamicOptions = this.getDynamicOptions();
  204. const options = {
  205. ...FLOT_OPTIONS,
  206. ...this.dynamicOptions,
  207. ...userOptions,
  208. };
  209. $.plot($el, series, options);
  210. }
  211. render() {
  212. const { height = '100px', id = 'graph' } = this.props;
  213. const { hiddenSeries } = this.state;
  214. const data = this.getGraphData();
  215. return (
  216. <>
  217. {this.props.data &&
  218. this.props.data.length > MAX_NUMBER_OF_TIME_SERIES &&
  219. !this.state.showAllTimeSeries && (
  220. <div className="time-series-disclaimer">
  221. <i className="fa fa-fw fa-warning disclaimer-icon" />
  222. {`Showing only ${MAX_NUMBER_OF_TIME_SERIES} time series. `}
  223. <span className="show-all-time-series" onClick={this.onShowAllTimeSeries}>{`Show all ${
  224. this.props.data.length
  225. }`}</span>
  226. </div>
  227. )}
  228. <div id={id} className="explore-graph" style={{ height }} />
  229. <Legend data={data} hiddenSeries={hiddenSeries} onToggleSeries={this.onToggleSeries} />
  230. </>
  231. );
  232. }
  233. }
  234. export default (props: GraphProps) => (
  235. <div>{/* div needed for AutoSizer to calculate, https://github.com/bvaughn/react-virtualized/blob/master/docs/usingAutoSizer.md#observation */}
  236. <AutoSizer disableHeight>
  237. {({width, height}) => (
  238. <div style={{width}}>
  239. {width > 0 && <Graph
  240. size={{
  241. width: width,
  242. height: height
  243. }}
  244. {...props}
  245. />}
  246. </div>
  247. )}
  248. </AutoSizer>
  249. </div>
  250. );