Graph.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import $ from 'jquery';
  2. import React, { PureComponent } from 'react';
  3. import difference from 'lodash/difference';
  4. import 'vendor/flot/jquery.flot';
  5. import 'vendor/flot/jquery.flot.time';
  6. import 'vendor/flot/jquery.flot.selection';
  7. import 'vendor/flot/jquery.flot.stack';
  8. import { TimeZone, AbsoluteTimeRange, GraphLegend, LegendItem, LegendDisplayMode } from '@grafana/ui';
  9. import TimeSeries from 'app/core/time_series2';
  10. const MAX_NUMBER_OF_TIME_SERIES = 20;
  11. // Copied from graph.ts
  12. function time_format(ticks, min, max) {
  13. if (min && max && ticks) {
  14. const range = max - min;
  15. const secPerTick = range / ticks / 1000;
  16. const oneDay = 86400000;
  17. const oneYear = 31536000000;
  18. if (secPerTick <= 45) {
  19. return '%H:%M:%S';
  20. }
  21. if (secPerTick <= 7200 || range <= oneDay) {
  22. return '%H:%M';
  23. }
  24. if (secPerTick <= 80000) {
  25. return '%m/%d %H:%M';
  26. }
  27. if (secPerTick <= 2419200 || range <= oneYear) {
  28. return '%m/%d';
  29. }
  30. return '%Y-%m';
  31. }
  32. return '%H:%M';
  33. }
  34. const FLOT_OPTIONS = {
  35. legend: {
  36. show: false,
  37. },
  38. series: {
  39. lines: {
  40. linewidth: 1,
  41. zero: false,
  42. },
  43. shadowSize: 0,
  44. },
  45. grid: {
  46. minBorderMargin: 0,
  47. markings: [],
  48. backgroundColor: null,
  49. borderWidth: 0,
  50. // hoverable: true,
  51. clickable: true,
  52. color: '#a1a1a1',
  53. margin: { left: 0, right: 0 },
  54. labelMarginX: 0,
  55. },
  56. selection: {
  57. mode: 'x',
  58. color: '#666',
  59. },
  60. // crosshair: {
  61. // mode: 'x',
  62. // },
  63. };
  64. interface GraphProps {
  65. data: any[];
  66. height?: number;
  67. width?: number;
  68. id?: string;
  69. range: AbsoluteTimeRange;
  70. timeZone: TimeZone;
  71. split?: boolean;
  72. userOptions?: any;
  73. onChangeTime?: (range: AbsoluteTimeRange) => void;
  74. onToggleSeries?: (alias: string, hiddenSeries: Set<string>) => void;
  75. }
  76. interface GraphState {
  77. /**
  78. * Type parameter refers to the `alias` property of a `TimeSeries`.
  79. * Consequently, all series sharing the same alias will share visibility state.
  80. */
  81. hiddenSeries: string[];
  82. showAllTimeSeries: boolean;
  83. }
  84. export class Graph extends PureComponent<GraphProps, GraphState> {
  85. $el: any;
  86. dynamicOptions = null;
  87. state = {
  88. hiddenSeries: [],
  89. showAllTimeSeries: false,
  90. };
  91. getGraphData(): TimeSeries[] {
  92. const { data } = this.props;
  93. return this.state.showAllTimeSeries ? data : data.slice(0, MAX_NUMBER_OF_TIME_SERIES);
  94. }
  95. componentDidMount() {
  96. this.draw();
  97. this.$el = $(`#${this.props.id}`);
  98. this.$el.bind('plotselected', this.onPlotSelected);
  99. }
  100. componentDidUpdate(prevProps: GraphProps, prevState: GraphState) {
  101. if (
  102. prevProps.data !== this.props.data ||
  103. prevProps.range !== this.props.range ||
  104. prevProps.split !== this.props.split ||
  105. prevProps.height !== this.props.height ||
  106. prevProps.width !== this.props.width ||
  107. prevState.hiddenSeries !== this.state.hiddenSeries
  108. ) {
  109. this.draw();
  110. }
  111. }
  112. componentWillUnmount() {
  113. this.$el.unbind('plotselected', this.onPlotSelected);
  114. }
  115. onPlotSelected = (event, ranges) => {
  116. const { onChangeTime } = this.props;
  117. if (onChangeTime) {
  118. this.props.onChangeTime({
  119. from: ranges.xaxis.from,
  120. to: ranges.xaxis.to,
  121. });
  122. }
  123. };
  124. getDynamicOptions() {
  125. const { range, width, timeZone } = this.props;
  126. const ticks = (width || 0) / 100;
  127. const min = range.from;
  128. const max = range.to;
  129. return {
  130. xaxis: {
  131. mode: 'time',
  132. min: min,
  133. max: max,
  134. label: 'Datetime',
  135. ticks: ticks,
  136. timezone: timeZone.raw,
  137. timeformat: time_format(ticks, min, max),
  138. },
  139. };
  140. }
  141. onShowAllTimeSeries = () => {
  142. this.setState(
  143. {
  144. showAllTimeSeries: true,
  145. },
  146. this.draw
  147. );
  148. };
  149. draw() {
  150. const { userOptions = {} } = this.props;
  151. const { hiddenSeries } = this.state;
  152. const data = this.getGraphData();
  153. const $el = $(`#${this.props.id}`);
  154. let series = [{ data: [[0, 0]] }];
  155. if (data && data.length > 0) {
  156. series = data
  157. .filter((ts: TimeSeries) => hiddenSeries.indexOf(ts.alias) === -1)
  158. .map((ts: TimeSeries) => ({
  159. color: ts.color,
  160. label: ts.label,
  161. data: ts.getFlotPairs('null'),
  162. }));
  163. }
  164. this.dynamicOptions = this.getDynamicOptions();
  165. const options = {
  166. ...FLOT_OPTIONS,
  167. ...this.dynamicOptions,
  168. ...userOptions,
  169. };
  170. $.plot($el, series, options);
  171. }
  172. getLegendItems = (): LegendItem[] => {
  173. const { hiddenSeries } = this.state;
  174. const data = this.getGraphData();
  175. return data.map(series => {
  176. return {
  177. label: series.alias,
  178. color: series.color,
  179. isVisible: hiddenSeries.indexOf(series.alias) === -1,
  180. yAxis: 1,
  181. };
  182. });
  183. };
  184. onSeriesToggle(label: string, event: React.MouseEvent<HTMLElement>) {
  185. // This implementation is more or less a copy of GraphPanel's logic.
  186. // TODO: we need to use Graph's panel controller or split it into smaller
  187. // controllers to remove code duplication. Right now we cant easily use that, since Explore
  188. // is not using SeriesData for graph yet
  189. const exclusive = event.ctrlKey || event.metaKey || event.shiftKey;
  190. this.setState((state, props) => {
  191. const { data } = props;
  192. let nextHiddenSeries = [];
  193. if (exclusive) {
  194. // Toggling series with key makes the series itself to toggle
  195. if (state.hiddenSeries.indexOf(label) > -1) {
  196. nextHiddenSeries = state.hiddenSeries.filter(series => series !== label);
  197. } else {
  198. nextHiddenSeries = state.hiddenSeries.concat([label]);
  199. }
  200. } else {
  201. // Toggling series with out key toggles all the series but the clicked one
  202. const allSeriesLabels = data.map(series => series.label);
  203. if (state.hiddenSeries.length + 1 === allSeriesLabels.length) {
  204. nextHiddenSeries = [];
  205. } else {
  206. nextHiddenSeries = difference(allSeriesLabels, [label]);
  207. }
  208. }
  209. return {
  210. hiddenSeries: nextHiddenSeries,
  211. };
  212. });
  213. }
  214. render() {
  215. const { height = 100, id = 'graph' } = this.props;
  216. return (
  217. <>
  218. {this.props.data && this.props.data.length > MAX_NUMBER_OF_TIME_SERIES && !this.state.showAllTimeSeries && (
  219. <div className="time-series-disclaimer">
  220. <i className="fa fa-fw fa-warning disclaimer-icon" />
  221. {`Showing only ${MAX_NUMBER_OF_TIME_SERIES} time series. `}
  222. <span className="show-all-time-series" onClick={this.onShowAllTimeSeries}>{`Show all ${
  223. this.props.data.length
  224. }`}</span>
  225. </div>
  226. )}
  227. <div id={id} className="explore-graph" style={{ height }} />
  228. <GraphLegend
  229. items={this.getLegendItems()}
  230. displayMode={LegendDisplayMode.List}
  231. placement="under"
  232. onLabelClick={(item, event) => {
  233. this.onSeriesToggle(item.label, event);
  234. }}
  235. />
  236. </>
  237. );
  238. }
  239. }
  240. export default Graph;