Graph.tsx 7.1 KB

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