chartZoom.tsx 9.1 KB

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