chartZoom.tsx 8.1 KB

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