chartZoom.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. import {Component} from 'react';
  2. import type {
  3. DataZoomComponentOption,
  4. ECharts,
  5. InsideDataZoomComponentOption,
  6. ToolboxComponentOption,
  7. XAXisComponentOption,
  8. } from 'echarts';
  9. import moment from 'moment-timezone';
  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 type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  23. import {getUtcDateString, getUtcToLocalDateObject} from 'sentry/utils/dates';
  24. import withSentryRouter from 'sentry/utils/withSentryRouter';
  25. const getDate = date =>
  26. date ? moment.utc(date).format(moment.HTML5_FMT.DATETIME_LOCAL_SECONDS) : null;
  27. type Period = {
  28. end: DateString;
  29. period: string | null;
  30. start: DateString;
  31. };
  32. type ZoomPropKeys =
  33. | 'period'
  34. | 'xAxis'
  35. | 'onChartReady'
  36. | 'onDataZoom'
  37. | 'onRestore'
  38. | 'onFinished';
  39. export interface ZoomRenderProps extends Pick<Props, ZoomPropKeys> {
  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. componentWillUnmount(): void {
  93. document.body.removeEventListener('keydown', this.handleKeyDown);
  94. document.body.removeEventListener('mouseup', this.handleMouseUp);
  95. this.$chart?.removeEventListener('mousedown', this.handleMouseDown);
  96. }
  97. chart?: ECharts;
  98. $chart?: HTMLElement;
  99. isCancellingZoom?: boolean;
  100. history: Period[];
  101. currentPeriod?: Period;
  102. zooming: (() => void) | null = null;
  103. /**
  104. * Save current period state from period in props to be used
  105. * in handling chart's zoom history state
  106. */
  107. saveCurrentPeriod = props => {
  108. this.currentPeriod = {
  109. period: props.period,
  110. start: getDate(props.start),
  111. end: getDate(props.end),
  112. };
  113. };
  114. /**
  115. * Sets the new period due to a zoom related action
  116. *
  117. * Saves the current period to an instance property so that we
  118. * can control URL state when zoom history is being manipulated
  119. * by the chart controls.
  120. *
  121. * Saves a callback function to be called after chart animation is completed
  122. */
  123. setPeriod = ({period, start, end}, saveHistory = false) => {
  124. const {router, onZoom, usePageDate, saveOnZoom} = this.props;
  125. const startFormatted = getDate(start);
  126. const endFormatted = getDate(end);
  127. // Save period so that we can revert back to it when using echarts "back" navigation
  128. if (saveHistory) {
  129. this.history.push(this.currentPeriod!);
  130. }
  131. // Callback to let parent component know zoom has changed
  132. // This is required for some more perceived responsiveness since
  133. // we delay updating URL state so that chart animation can finish
  134. //
  135. // Parent container can use this to change into a loading state before
  136. // URL parameters are changed
  137. onZoom?.({
  138. period,
  139. start: startFormatted,
  140. end: endFormatted,
  141. });
  142. this.zooming = () => {
  143. if (usePageDate && router) {
  144. const newQuery = {
  145. ...router.location.query,
  146. pageStart: start ? getUtcDateString(start) : undefined,
  147. pageEnd: end ? getUtcDateString(end) : undefined,
  148. pageStatsPeriod: period ?? undefined,
  149. };
  150. // Only push new location if query params has changed because this will cause a heavy re-render
  151. if (qs.stringify(newQuery) !== qs.stringify(router.location.query)) {
  152. router.push({
  153. pathname: router.location.pathname,
  154. query: newQuery,
  155. });
  156. }
  157. } else {
  158. updateDateTime(
  159. {
  160. period,
  161. start: startFormatted
  162. ? getUtcToLocalDateObject(startFormatted)
  163. : startFormatted,
  164. end: endFormatted ? getUtcToLocalDateObject(endFormatted) : endFormatted,
  165. },
  166. router,
  167. {save: saveOnZoom}
  168. );
  169. }
  170. this.saveCurrentPeriod({period, start, end});
  171. };
  172. };
  173. /**
  174. * Enable zoom immediately instead of having to toggle to zoom
  175. */
  176. handleChartReady = (chart: ECharts) => {
  177. this.props.onChartReady?.(chart);
  178. this.chart = chart;
  179. this.$chart = chart.getDom();
  180. this.$chart.addEventListener('mousedown', this.handleMouseDown);
  181. };
  182. handleKeyDown = evt => {
  183. if (!this.chart) {
  184. return;
  185. }
  186. // This handler only exists if mouse down was caught inside the chart.
  187. // Therefore, no need to check any other state.
  188. if (evt.key === 'Escape') {
  189. evt.stopPropagation();
  190. // Mark the component as currently cancelling a zoom selection. This allows
  191. // us to prevent "restore" handlers from running
  192. this.isCancellingZoom = true;
  193. // "restore" removes the current chart zoom selection
  194. this.chart.dispatchAction({
  195. type: 'restore',
  196. });
  197. }
  198. };
  199. /**
  200. * Restores the chart to initial viewport/zoom level
  201. *
  202. * Updates URL state to reflect initial params
  203. */
  204. handleZoomRestore = (evt, chart) => {
  205. if (this.isCancellingZoom) {
  206. // If this restore is caused by a zoom cancel, do not run handlers!
  207. // The regular handler restores to the earliest point in the zoom history
  208. // and we do not want that. We want to cancel the selection and do nothing
  209. // else. Reset `isCancellingZoom` here in case the dispatch was async
  210. this.isCancellingZoom = false;
  211. return;
  212. }
  213. if (!this.history.length) {
  214. return;
  215. }
  216. this.setPeriod(this.history[0]);
  217. // reset history
  218. this.history = [];
  219. this.props.onRestore?.(evt, chart);
  220. };
  221. handleMouseDown = () => {
  222. // Register `mouseup` and `keydown` listeners on mouse down
  223. // This ensures that there is only one live listener at a time
  224. // regardless of how many charts are rendered. NOTE: It's
  225. // important to set `useCapture: true` in the `"keydown"` handler
  226. // otherwise the Escape will close whatever modal or panel the
  227. // chart is in. Those elements register their handlers _earlier_.
  228. document.body.addEventListener('mouseup', this.handleMouseUp);
  229. document.body.addEventListener('keydown', this.handleKeyDown, true);
  230. };
  231. handleMouseUp = () => {
  232. document.body.removeEventListener('mouseup', this.handleMouseUp);
  233. document.body.removeEventListener('keydown', this.handleKeyDown, true);
  234. };
  235. handleDataZoom = (evt, chart) => {
  236. const model = chart.getModel();
  237. const {startValue, endValue} = model._payload.batch[0];
  238. // if `rangeStart` and `rangeEnd` are null, then we are going back
  239. if (startValue === null && endValue === null) {
  240. const previousPeriod = this.history.pop();
  241. if (!previousPeriod) {
  242. return;
  243. }
  244. this.setPeriod(previousPeriod);
  245. } else {
  246. const start = moment.utc(startValue);
  247. // Add a day so we go until the end of the day (e.g. next day at midnight)
  248. const end = moment.utc(endValue);
  249. this.setPeriod({period: null, start, end}, true);
  250. }
  251. this.props.onDataZoom?.(evt, chart);
  252. };
  253. /**
  254. * Chart event when *any* rendering+animation finishes
  255. *
  256. * `this.zooming` acts as a callback function so that
  257. * we can let the native zoom animation on the chart complete
  258. * before we update URL state and re-render
  259. */
  260. handleChartFinished = (_props, chart) => {
  261. if (typeof this.zooming === 'function') {
  262. this.zooming();
  263. this.zooming = null;
  264. }
  265. // This attempts to activate the area zoom toolbox feature
  266. const zoom = chart._componentsViews?.find(c => c._features?.dataZoom);
  267. if (zoom && !zoom._features.dataZoom._isZoomActive) {
  268. // Calling dispatchAction will re-trigger handleChartFinished
  269. chart.dispatchAction({
  270. type: 'takeGlobalCursor',
  271. key: 'dataZoomSelect',
  272. dataZoomSelectActive: true,
  273. });
  274. }
  275. if (typeof this.props.onFinished === 'function') {
  276. this.props.onFinished(_props, chart);
  277. }
  278. };
  279. render() {
  280. const {
  281. utc: _utc,
  282. start: _start,
  283. end: _end,
  284. disabled,
  285. children,
  286. xAxisIndex,
  287. router: _router,
  288. onZoom: _onZoom,
  289. onRestore: _onRestore,
  290. onChartReady: _onChartReady,
  291. onDataZoom: _onDataZoom,
  292. onFinished: _onFinished,
  293. showSlider,
  294. chartZoomOptions,
  295. ...props
  296. } = this.props;
  297. const utc = _utc ?? undefined;
  298. const start = _start ? getUtcToLocalDateObject(_start) : undefined;
  299. const end = _end ? getUtcToLocalDateObject(_end) : undefined;
  300. if (disabled) {
  301. return children({
  302. utc,
  303. start,
  304. end,
  305. ...props,
  306. });
  307. }
  308. const renderProps = {
  309. // Zooming only works when grouped by date
  310. isGroupedByDate: true,
  311. onChartReady: this.handleChartReady,
  312. utc,
  313. start,
  314. end,
  315. dataZoom: showSlider
  316. ? [
  317. ...DataZoomSlider({xAxisIndex, ...chartZoomOptions}),
  318. ...DataZoomInside({
  319. xAxisIndex,
  320. ...(chartZoomOptions as InsideDataZoomComponentOption),
  321. }),
  322. ]
  323. : DataZoomInside({
  324. xAxisIndex,
  325. ...(chartZoomOptions as InsideDataZoomComponentOption),
  326. }),
  327. showTimeInTooltip: true,
  328. toolBox: ToolBox(
  329. {},
  330. {
  331. dataZoom: {
  332. title: {
  333. zoom: '',
  334. back: '',
  335. },
  336. iconStyle: {
  337. borderWidth: 0,
  338. color: 'transparent',
  339. opacity: 0,
  340. },
  341. },
  342. }
  343. ),
  344. onDataZoom: this.handleDataZoom,
  345. onFinished: this.handleChartFinished,
  346. onRestore: this.handleZoomRestore,
  347. ...props,
  348. };
  349. return children(renderProps);
  350. }
  351. }
  352. export default withSentryRouter(ChartZoom);