useChartZoom.tsx 8.9 KB

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