Graph.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import $ from 'jquery';
  2. import React, { PureComponent } from 'react';
  3. import moment from 'moment';
  4. import { withSize } from 'react-sizeme';
  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. size?: { width: number; height: number };
  75. userOptions?: any;
  76. onChangeTime?: (range: RawTimeRange) => void;
  77. onToggleSeries?: (alias: string, hiddenSeries: Set<string>) => void;
  78. }
  79. interface GraphState {
  80. /**
  81. * Type parameter refers to the `alias` property of a `TimeSeries`.
  82. * Consequently, all series sharing the same alias will share visibility state.
  83. */
  84. hiddenSeries: Set<string>;
  85. showAllTimeSeries: boolean;
  86. }
  87. export class Graph extends PureComponent<GraphProps, GraphState> {
  88. $el: any;
  89. dynamicOptions = null;
  90. state = {
  91. hiddenSeries: new Set(),
  92. showAllTimeSeries: false,
  93. };
  94. getGraphData() {
  95. const { data } = this.props;
  96. return this.state.showAllTimeSeries ? data : data.slice(0, MAX_NUMBER_OF_TIME_SERIES);
  97. }
  98. componentDidMount() {
  99. this.draw();
  100. this.$el = $(`#${this.props.id}`);
  101. this.$el.bind('plotselected', this.onPlotSelected);
  102. }
  103. componentDidUpdate(prevProps: GraphProps, prevState: GraphState) {
  104. if (
  105. prevProps.data !== this.props.data ||
  106. prevProps.range !== this.props.range ||
  107. prevProps.split !== this.props.split ||
  108. prevProps.height !== this.props.height ||
  109. (prevProps.size && prevProps.size.width !== this.props.size.width) ||
  110. !equal(prevState.hiddenSeries, this.state.hiddenSeries)
  111. ) {
  112. this.draw();
  113. }
  114. }
  115. componentWillUnmount() {
  116. this.$el.unbind('plotselected', this.onPlotSelected);
  117. }
  118. onPlotSelected = (event, ranges) => {
  119. if (this.props.onChangeTime) {
  120. const range = {
  121. from: moment(ranges.xaxis.from),
  122. to: moment(ranges.xaxis.to),
  123. };
  124. this.props.onChangeTime(range);
  125. }
  126. };
  127. getDynamicOptions() {
  128. const { range, size } = this.props;
  129. const ticks = (size.width || 0) / 100;
  130. let { from, to } = range;
  131. if (!moment.isMoment(from)) {
  132. from = dateMath.parse(from, false);
  133. }
  134. if (!moment.isMoment(to)) {
  135. to = dateMath.parse(to, true);
  136. }
  137. const min = from.valueOf();
  138. const max = to.valueOf();
  139. return {
  140. xaxis: {
  141. mode: 'time',
  142. min: min,
  143. max: max,
  144. label: 'Datetime',
  145. ticks: ticks,
  146. timezone: 'browser',
  147. timeformat: time_format(ticks, min, max),
  148. },
  149. };
  150. }
  151. onShowAllTimeSeries = () => {
  152. this.setState(
  153. {
  154. showAllTimeSeries: true,
  155. },
  156. this.draw
  157. );
  158. };
  159. onToggleSeries = (series: TimeSeries, exclusive: boolean) => {
  160. this.setState((state, props) => {
  161. const { data, onToggleSeries } = props;
  162. const { hiddenSeries } = state;
  163. // Deduplicate series as visibility tracks the alias property
  164. const oneSeriesVisible = hiddenSeries.size === new Set(data.map(d => d.alias)).size - 1;
  165. let nextHiddenSeries = new Set();
  166. if (exclusive) {
  167. if (hiddenSeries.has(series.alias) || !oneSeriesVisible) {
  168. nextHiddenSeries = new Set(data.filter(d => d.alias !== series.alias).map(d => d.alias));
  169. }
  170. } else {
  171. // Prune hidden series no longer part of those available from the most recent query
  172. const availableSeries = new Set(data.map(d => d.alias));
  173. nextHiddenSeries = intersect(new Set(hiddenSeries), availableSeries);
  174. if (nextHiddenSeries.has(series.alias)) {
  175. nextHiddenSeries.delete(series.alias);
  176. } else {
  177. nextHiddenSeries.add(series.alias);
  178. }
  179. }
  180. if (onToggleSeries) {
  181. onToggleSeries(series.alias, nextHiddenSeries);
  182. }
  183. return {
  184. hiddenSeries: nextHiddenSeries,
  185. };
  186. }, this.draw);
  187. };
  188. draw() {
  189. const { userOptions = {} } = this.props;
  190. const { hiddenSeries } = this.state;
  191. const data = this.getGraphData();
  192. const $el = $(`#${this.props.id}`);
  193. let series = [{ data: [[0, 0]] }];
  194. if (data && data.length > 0) {
  195. series = data.filter((ts: TimeSeries) => !hiddenSeries.has(ts.alias)).map((ts: TimeSeries) => ({
  196. color: ts.color,
  197. label: ts.label,
  198. data: ts.getFlotPairs('null'),
  199. }));
  200. }
  201. this.dynamicOptions = this.getDynamicOptions();
  202. const options = {
  203. ...FLOT_OPTIONS,
  204. ...this.dynamicOptions,
  205. ...userOptions,
  206. };
  207. $.plot($el, series, options);
  208. }
  209. render() {
  210. const { height = '100px', id = 'graph' } = this.props;
  211. const { hiddenSeries } = this.state;
  212. const data = this.getGraphData();
  213. return (
  214. <>
  215. {this.props.data &&
  216. this.props.data.length > MAX_NUMBER_OF_TIME_SERIES &&
  217. !this.state.showAllTimeSeries && (
  218. <div className="time-series-disclaimer">
  219. <i className="fa fa-fw fa-warning disclaimer-icon" />
  220. {`Showing only ${MAX_NUMBER_OF_TIME_SERIES} time series. `}
  221. <span className="show-all-time-series" onClick={this.onShowAllTimeSeries}>{`Show all ${
  222. this.props.data.length
  223. }`}</span>
  224. </div>
  225. )}
  226. <div id={id} className="explore-graph" style={{ height }} />
  227. <Legend data={data} hiddenSeries={hiddenSeries} onToggleSeries={this.onToggleSeries} />
  228. </>
  229. );
  230. }
  231. }
  232. export default withSize()(Graph);