chartZoom.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import {Component} from 'react';
  2. import {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 {DateString} from 'sentry/types';
  16. import {
  17. EChartChartReadyHandler,
  18. EChartDataZoomHandler,
  19. EChartFinishedHandler,
  20. EChartRestoreHandler,
  21. } from 'sentry/types/echarts';
  22. import {callIfFunction} from 'sentry/utils/callIfFunction';
  23. import {getUtcDateString, getUtcToLocalDateObject} from 'sentry/utils/dates';
  24. const getDate = date =>
  25. date ? moment.utc(date).format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS) : null;
  26. type Period = {
  27. end: DateString;
  28. period: string | null;
  29. start: DateString;
  30. };
  31. const ZoomPropKeys = [
  32. 'period',
  33. 'xAxis',
  34. 'onChartReady',
  35. 'onDataZoom',
  36. 'onRestore',
  37. 'onFinished',
  38. ] as const;
  39. export type ZoomRenderProps = Pick<Props, typeof ZoomPropKeys[number]> & {
  40. dataZoom?: DataZoomComponentOption[];
  41. end?: Date;
  42. isGroupedByDate?: boolean;
  43. showTimeInTooltip?: boolean;
  44. start?: Date;
  45. toolBox?: ToolboxComponentOption;
  46. utc?: boolean;
  47. };
  48. type Props = {
  49. children: (props: ZoomRenderProps) => React.ReactNode;
  50. chartZoomOptions?: DataZoomComponentOption;
  51. disabled?: boolean;
  52. end?: DateString;
  53. onChartReady?: EChartChartReadyHandler;
  54. onDataZoom?: EChartDataZoomHandler;
  55. onFinished?: EChartFinishedHandler;
  56. onRestore?: EChartRestoreHandler;
  57. onZoom?: (period: Period) => void;
  58. period?: string | null;
  59. router?: InjectedRouter;
  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} = 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. );
  159. }
  160. this.saveCurrentPeriod({period, start, end});
  161. };
  162. };
  163. /**
  164. * Enable zoom immediately instead of having to toggle to zoom
  165. */
  166. handleChartReady = chart => {
  167. this.props.onChartReady?.(chart);
  168. };
  169. /**
  170. * Restores the chart to initial viewport/zoom level
  171. *
  172. * Updates URL state to reflect initial params
  173. */
  174. handleZoomRestore = (evt, chart) => {
  175. if (!this.history.length) {
  176. return;
  177. }
  178. this.setPeriod(this.history[0]);
  179. // reset history
  180. this.history = [];
  181. this.props.onRestore?.(evt, chart);
  182. };
  183. handleDataZoom = (evt, chart) => {
  184. const model = chart.getModel();
  185. const {startValue, endValue} = model._payload.batch[0];
  186. // if `rangeStart` and `rangeEnd` are null, then we are going back
  187. if (startValue === null && endValue === null) {
  188. const previousPeriod = this.history.pop();
  189. if (!previousPeriod) {
  190. return;
  191. }
  192. this.setPeriod(previousPeriod);
  193. } else {
  194. const start = moment.utc(startValue);
  195. // Add a day so we go until the end of the day (e.g. next day at midnight)
  196. const end = moment.utc(endValue);
  197. this.setPeriod({period: null, start, end}, true);
  198. }
  199. this.props.onDataZoom?.(evt, chart);
  200. };
  201. /**
  202. * Chart event when *any* rendering+animation finishes
  203. *
  204. * `this.zooming` acts as a callback function so that
  205. * we can let the native zoom animation on the chart complete
  206. * before we update URL state and re-render
  207. */
  208. handleChartFinished = (_props, chart) => {
  209. if (typeof this.zooming === 'function') {
  210. this.zooming();
  211. this.zooming = null;
  212. }
  213. // This attempts to activate the area zoom toolbox feature
  214. const zoom = chart._componentsViews?.find(c => c._features && c._features.dataZoom);
  215. if (zoom && !zoom._features.dataZoom._isZoomActive) {
  216. // Calling dispatchAction will re-trigger handleChartFinished
  217. chart.dispatchAction({
  218. type: 'takeGlobalCursor',
  219. key: 'dataZoomSelect',
  220. dataZoomSelectActive: true,
  221. });
  222. }
  223. callIfFunction(this.props.onFinished);
  224. };
  225. render() {
  226. const {
  227. utc: _utc,
  228. start: _start,
  229. end: _end,
  230. disabled,
  231. children,
  232. xAxisIndex,
  233. router: _router,
  234. onZoom: _onZoom,
  235. onRestore: _onRestore,
  236. onChartReady: _onChartReady,
  237. onDataZoom: _onDataZoom,
  238. onFinished: _onFinished,
  239. showSlider,
  240. chartZoomOptions,
  241. ...props
  242. } = this.props;
  243. const utc = _utc ?? undefined;
  244. const start = _start ? getUtcToLocalDateObject(_start) : undefined;
  245. const end = _end ? getUtcToLocalDateObject(_end) : undefined;
  246. if (disabled) {
  247. return children({
  248. utc,
  249. start,
  250. end,
  251. ...props,
  252. });
  253. }
  254. const renderProps = {
  255. // Zooming only works when grouped by date
  256. isGroupedByDate: true,
  257. onChartReady: this.handleChartReady,
  258. utc,
  259. start,
  260. end,
  261. dataZoom: showSlider
  262. ? [
  263. ...DataZoomSlider({xAxisIndex, ...chartZoomOptions}),
  264. ...DataZoomInside({
  265. xAxisIndex,
  266. ...(chartZoomOptions as InsideDataZoomComponentOption),
  267. }),
  268. ]
  269. : DataZoomInside({
  270. xAxisIndex,
  271. ...(chartZoomOptions as InsideDataZoomComponentOption),
  272. }),
  273. showTimeInTooltip: true,
  274. toolBox: ToolBox(
  275. {},
  276. {
  277. dataZoom: {
  278. title: {
  279. zoom: '',
  280. back: '',
  281. },
  282. iconStyle: {
  283. borderWidth: 0,
  284. color: 'transparent',
  285. opacity: 0,
  286. },
  287. },
  288. }
  289. ),
  290. onDataZoom: this.handleDataZoom,
  291. onFinished: this.handleChartFinished,
  292. onRestore: this.handleZoomRestore,
  293. ...props,
  294. };
  295. return children(renderProps);
  296. }
  297. }
  298. export default ChartZoom;