chartZoom.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import * as React from 'react';
  2. import {InjectedRouter} from 'react-router';
  3. import type {
  4. DataZoomComponentOption,
  5. ToolboxComponentOption,
  6. XAXisComponentOption,
  7. } from 'echarts';
  8. import moment from 'moment';
  9. import * as qs from 'query-string';
  10. import {updateDateTime} from 'sentry/actionCreators/pageFilters';
  11. import DataZoomInside from 'sentry/components/charts/components/dataZoomInside';
  12. import ToolBox from 'sentry/components/charts/components/toolBox';
  13. import {DateString} from 'sentry/types';
  14. import {
  15. EChartChartReadyHandler,
  16. EChartDataZoomHandler,
  17. EChartFinishedHandler,
  18. EChartRestoreHandler,
  19. } from 'sentry/types/echarts';
  20. import {callIfFunction} from 'sentry/utils/callIfFunction';
  21. import {getUtcDateString, getUtcToLocalDateObject} from 'sentry/utils/dates';
  22. const getDate = date =>
  23. date ? moment.utc(date).format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS) : null;
  24. type Period = {
  25. period: string | null;
  26. start: DateString;
  27. end: DateString;
  28. };
  29. const ZoomPropKeys = [
  30. 'period',
  31. 'xAxis',
  32. 'onChartReady',
  33. 'onDataZoom',
  34. 'onRestore',
  35. 'onFinished',
  36. ] as const;
  37. export type ZoomRenderProps = Pick<Props, typeof ZoomPropKeys[number]> & {
  38. utc?: boolean;
  39. start?: Date;
  40. end?: Date;
  41. isGroupedByDate?: boolean;
  42. showTimeInTooltip?: boolean;
  43. dataZoom?: DataZoomComponentOption[];
  44. toolBox?: ToolboxComponentOption;
  45. };
  46. type Props = {
  47. children: (props: ZoomRenderProps) => React.ReactNode;
  48. router?: InjectedRouter;
  49. disabled?: boolean;
  50. xAxis?: XAXisComponentOption;
  51. xAxisIndex?: number | number[];
  52. start?: DateString;
  53. end?: DateString;
  54. period?: string | null;
  55. utc?: boolean | null;
  56. onChartReady?: EChartChartReadyHandler;
  57. onDataZoom?: EChartDataZoomHandler;
  58. onFinished?: EChartFinishedHandler;
  59. onRestore?: EChartRestoreHandler;
  60. onZoom?: (period: Period) => void;
  61. usePageDate?: boolean;
  62. };
  63. /**
  64. * This is a very opinionated component that takes a render prop through `children`. It
  65. * will provide props to be passed to `BaseChart` to enable support of zooming without
  66. * eCharts' clunky zoom toolboxes.
  67. *
  68. * This also is very tightly coupled with the Global Selection Header. We can make it more
  69. * generic if need be in the future.
  70. */
  71. class ChartZoom extends React.Component<Props> {
  72. constructor(props: Props) {
  73. super(props);
  74. // Zoom history
  75. this.history = [];
  76. // Initialize current period instance state for zoom history
  77. this.saveCurrentPeriod(props);
  78. }
  79. componentDidUpdate() {
  80. if (this.props.disabled) {
  81. return;
  82. }
  83. // When component updates, make sure we sync current period state
  84. // for use in zoom history
  85. this.saveCurrentPeriod(this.props);
  86. }
  87. history: Period[];
  88. currentPeriod?: Period;
  89. zooming: (() => void) | null = null;
  90. /**
  91. * Save current period state from period in props to be used
  92. * in handling chart's zoom history state
  93. */
  94. saveCurrentPeriod = props => {
  95. this.currentPeriod = {
  96. period: props.period,
  97. start: getDate(props.start),
  98. end: getDate(props.end),
  99. };
  100. };
  101. /**
  102. * Sets the new period due to a zoom related action
  103. *
  104. * Saves the current period to an instance property so that we
  105. * can control URL state when zoom history is being manipulated
  106. * by the chart controls.
  107. *
  108. * Saves a callback function to be called after chart animation is completed
  109. */
  110. setPeriod = ({period, start, end}, saveHistory = false) => {
  111. const {router, onZoom, usePageDate} = this.props;
  112. const startFormatted = getDate(start);
  113. const endFormatted = getDate(end);
  114. // Save period so that we can revert back to it when using echarts "back" navigation
  115. if (saveHistory) {
  116. this.history.push(this.currentPeriod!);
  117. }
  118. // Callback to let parent component know zoom has changed
  119. // This is required for some more perceived responsiveness since
  120. // we delay updating URL state so that chart animation can finish
  121. //
  122. // Parent container can use this to change into a loading state before
  123. // URL parameters are changed
  124. callIfFunction(onZoom, {
  125. period,
  126. start: startFormatted,
  127. end: endFormatted,
  128. });
  129. this.zooming = () => {
  130. if (usePageDate && router) {
  131. const newQuery = {
  132. ...router.location.query,
  133. pageStart: start ? getUtcDateString(start) : undefined,
  134. pageEnd: end ? getUtcDateString(end) : undefined,
  135. pageStatsPeriod: period ?? undefined,
  136. };
  137. // Only push new location if query params has changed because this will cause a heavy re-render
  138. if (qs.stringify(newQuery) !== qs.stringify(router.location.query)) {
  139. router.push({
  140. pathname: router.location.pathname,
  141. query: newQuery,
  142. });
  143. }
  144. } else {
  145. updateDateTime(
  146. {
  147. period,
  148. start: startFormatted
  149. ? getUtcToLocalDateObject(startFormatted)
  150. : startFormatted,
  151. end: endFormatted ? getUtcToLocalDateObject(endFormatted) : endFormatted,
  152. },
  153. router
  154. );
  155. }
  156. this.saveCurrentPeriod({period, start, end});
  157. };
  158. };
  159. /**
  160. * Enable zoom immediately instead of having to toggle to zoom
  161. */
  162. handleChartReady = chart => {
  163. callIfFunction(this.props.onChartReady, chart);
  164. };
  165. /**
  166. * Restores the chart to initial viewport/zoom level
  167. *
  168. * Updates URL state to reflect initial params
  169. */
  170. handleZoomRestore = (evt, chart) => {
  171. if (!this.history.length) {
  172. return;
  173. }
  174. this.setPeriod(this.history[0]);
  175. // reset history
  176. this.history = [];
  177. callIfFunction(this.props.onRestore, evt, chart);
  178. };
  179. handleDataZoom = (evt, chart) => {
  180. const model = chart.getModel();
  181. const {startValue, endValue} = model._payload.batch[0];
  182. // if `rangeStart` and `rangeEnd` are null, then we are going back
  183. if (startValue === null && endValue === null) {
  184. const previousPeriod = this.history.pop();
  185. if (!previousPeriod) {
  186. return;
  187. }
  188. this.setPeriod(previousPeriod);
  189. } else {
  190. const start = moment.utc(startValue);
  191. // Add a day so we go until the end of the day (e.g. next day at midnight)
  192. const end = moment.utc(endValue);
  193. this.setPeriod({period: null, start, end}, true);
  194. }
  195. callIfFunction(this.props.onDataZoom, evt, chart);
  196. };
  197. /**
  198. * Chart event when *any* rendering+animation finishes
  199. *
  200. * `this.zooming` acts as a callback function so that
  201. * we can let the native zoom animation on the chart complete
  202. * before we update URL state and re-render
  203. */
  204. handleChartFinished = (_props, chart) => {
  205. if (typeof this.zooming === 'function') {
  206. this.zooming();
  207. this.zooming = null;
  208. }
  209. // This attempts to activate the area zoom toolbox feature
  210. const zoom = chart._componentsViews?.find(c => c._features && c._features.dataZoom);
  211. if (zoom && !zoom._features.dataZoom._isZoomActive) {
  212. // Calling dispatchAction will re-trigger handleChartFinished
  213. chart.dispatchAction({
  214. type: 'takeGlobalCursor',
  215. key: 'dataZoomSelect',
  216. dataZoomSelectActive: true,
  217. });
  218. }
  219. callIfFunction(this.props.onFinished);
  220. };
  221. render() {
  222. const {
  223. utc: _utc,
  224. start: _start,
  225. end: _end,
  226. disabled,
  227. children,
  228. xAxisIndex,
  229. router: _router,
  230. onZoom: _onZoom,
  231. onRestore: _onRestore,
  232. onChartReady: _onChartReady,
  233. onDataZoom: _onDataZoom,
  234. onFinished: _onFinished,
  235. ...props
  236. } = this.props;
  237. const utc = _utc ?? undefined;
  238. const start = _start ? getUtcToLocalDateObject(_start) : undefined;
  239. const end = _end ? getUtcToLocalDateObject(_end) : undefined;
  240. if (disabled) {
  241. return children({
  242. utc,
  243. start,
  244. end,
  245. ...props,
  246. });
  247. }
  248. const renderProps = {
  249. // Zooming only works when grouped by date
  250. isGroupedByDate: true,
  251. onChartReady: this.handleChartReady,
  252. utc,
  253. start,
  254. end,
  255. dataZoom: DataZoomInside({xAxisIndex}),
  256. showTimeInTooltip: true,
  257. toolBox: ToolBox(
  258. {},
  259. {
  260. dataZoom: {
  261. title: {
  262. zoom: '',
  263. back: '',
  264. },
  265. iconStyle: {
  266. borderWidth: 0,
  267. color: 'transparent',
  268. opacity: 0,
  269. },
  270. },
  271. }
  272. ),
  273. onDataZoom: this.handleDataZoom,
  274. onFinished: this.handleChartFinished,
  275. onRestore: this.handleZoomRestore,
  276. ...props,
  277. };
  278. return children(renderProps);
  279. }
  280. }
  281. export default ChartZoom;