chartZoom.tsx 9.1 KB

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