chart.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import {RefObject, useEffect, useRef, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {LineSeriesOption} from 'echarts';
  5. import * as echarts from 'echarts/core';
  6. import {
  7. TooltipFormatterCallback,
  8. TopLevelFormatterParams,
  9. XAXisOption,
  10. YAXisOption,
  11. } from 'echarts/types/dist/shared';
  12. import max from 'lodash/max';
  13. import min from 'lodash/min';
  14. import moment from 'moment';
  15. import {AreaChart, AreaChartProps} from 'sentry/components/charts/areaChart';
  16. import {BarChart} from 'sentry/components/charts/barChart';
  17. import BaseChart from 'sentry/components/charts/baseChart';
  18. import ChartZoom from 'sentry/components/charts/chartZoom';
  19. import {
  20. FormatterOptions,
  21. getFormatter,
  22. } from 'sentry/components/charts/components/tooltip';
  23. import ErrorPanel from 'sentry/components/charts/errorPanel';
  24. import LineSeries from 'sentry/components/charts/series/lineSeries';
  25. import ScatterSeries from 'sentry/components/charts/series/scatterSeries';
  26. import TransitionChart from 'sentry/components/charts/transitionChart';
  27. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  28. import LoadingIndicator from 'sentry/components/loadingIndicator';
  29. import {IconWarning} from 'sentry/icons';
  30. import {
  31. EChartClickHandler,
  32. EChartDataZoomHandler,
  33. EChartEventHandler,
  34. EChartHighlightHandler,
  35. EChartMouseOutHandler,
  36. EChartMouseOverHandler,
  37. ReactEchartsRef,
  38. Series,
  39. } from 'sentry/types/echarts';
  40. import {
  41. axisLabelFormatter,
  42. getDurationUnit,
  43. tooltipFormatter,
  44. } from 'sentry/utils/discover/charts';
  45. import {
  46. aggregateOutputType,
  47. AggregationOutputType,
  48. RateUnits,
  49. } from 'sentry/utils/discover/fields';
  50. import usePageFilters from 'sentry/utils/usePageFilters';
  51. import useRouter from 'sentry/utils/useRouter';
  52. import {SpanMetricsField} from 'sentry/views/starfish/types';
  53. const STARFISH_CHART_GROUP = 'starfish_chart_group';
  54. export const STARFISH_FIELDS: Record<string, {outputType: AggregationOutputType}> = {
  55. [SpanMetricsField.SPAN_DURATION]: {
  56. outputType: 'duration',
  57. },
  58. [SpanMetricsField.SPAN_SELF_TIME]: {
  59. outputType: 'duration',
  60. },
  61. // local is only used with `time_spent_percentage` function
  62. local: {
  63. outputType: 'duration',
  64. },
  65. };
  66. type Props = {
  67. data: Series[];
  68. loading: boolean;
  69. utc: boolean;
  70. aggregateOutputFormat?: AggregationOutputType;
  71. chartColors?: string[];
  72. chartGroup?: string;
  73. dataMax?: number;
  74. definedAxisTicks?: number;
  75. disableXAxis?: boolean;
  76. durationUnit?: number;
  77. errored?: boolean;
  78. forwardedRef?: RefObject<ReactEchartsRef>;
  79. grid?: AreaChartProps['grid'];
  80. height?: number;
  81. hideYAxisSplitLine?: boolean;
  82. isBarChart?: boolean;
  83. isLineChart?: boolean;
  84. legendFormatter?: (name: string) => string;
  85. log?: boolean;
  86. onClick?: EChartClickHandler;
  87. onDataZoom?: EChartDataZoomHandler;
  88. onHighlight?: EChartHighlightHandler;
  89. onLegendSelectChanged?: EChartEventHandler<{
  90. name: string;
  91. selected: Record<string, boolean>;
  92. type: 'legendselectchanged';
  93. }>;
  94. onMouseOut?: EChartMouseOutHandler;
  95. onMouseOver?: EChartMouseOverHandler;
  96. previousData?: Series[];
  97. rateUnit?: RateUnits;
  98. scatterPlot?: Series[];
  99. showLegend?: boolean;
  100. stacked?: boolean;
  101. throughput?: {count: number; interval: string}[];
  102. tooltipFormatterOptions?: FormatterOptions;
  103. };
  104. function computeMax(data: Series[]) {
  105. const valuesDict = data.map(value => value.data.map(point => point.value));
  106. return max(valuesDict.map(max)) as number;
  107. }
  108. // adapted from https://stackoverflow.com/questions/11397239/rounding-up-for-a-graph-maximum
  109. export function computeAxisMax(data: Series[], stacked?: boolean) {
  110. // assumes min is 0
  111. let maxValue = 0;
  112. if (data.length > 1 && stacked) {
  113. for (let i = 0; i < data.length; i++) {
  114. maxValue += max(data[i].data.map(point => point.value)) as number;
  115. }
  116. } else {
  117. maxValue = computeMax(data);
  118. }
  119. if (maxValue <= 1) {
  120. return 1;
  121. }
  122. const power = Math.log10(maxValue);
  123. const magnitude = min([max([10 ** (power - Math.floor(power)), 0]), 10]) as number;
  124. let scale: number;
  125. if (magnitude <= 2.5) {
  126. scale = 0.2;
  127. } else if (magnitude <= 5) {
  128. scale = 0.5;
  129. } else if (magnitude <= 7.5) {
  130. scale = 1.0;
  131. } else {
  132. scale = 2.0;
  133. }
  134. const step = 10 ** Math.floor(power) * scale;
  135. return Math.ceil(Math.ceil(maxValue / step) * step);
  136. }
  137. function Chart({
  138. data,
  139. dataMax,
  140. previousData,
  141. utc,
  142. loading,
  143. height,
  144. grid,
  145. disableXAxis,
  146. definedAxisTicks,
  147. durationUnit,
  148. rateUnit,
  149. chartColors,
  150. isBarChart,
  151. isLineChart,
  152. stacked,
  153. log,
  154. hideYAxisSplitLine,
  155. showLegend,
  156. scatterPlot,
  157. throughput,
  158. aggregateOutputFormat,
  159. onClick,
  160. onMouseOver,
  161. onMouseOut,
  162. onHighlight,
  163. forwardedRef,
  164. chartGroup,
  165. tooltipFormatterOptions = {},
  166. errored,
  167. onLegendSelectChanged,
  168. onDataZoom,
  169. legendFormatter,
  170. }: Props) {
  171. const router = useRouter();
  172. const theme = useTheme();
  173. const pageFilters = usePageFilters();
  174. const {start, end, period} = pageFilters.selection.datetime;
  175. const defaultRef = useRef<ReactEchartsRef>(null);
  176. const chartRef = forwardedRef || defaultRef;
  177. const echartsInstance = chartRef?.current?.getEchartsInstance();
  178. if (echartsInstance && !echartsInstance.group) {
  179. echartsInstance.group = chartGroup ?? STARFISH_CHART_GROUP;
  180. }
  181. const colors = chartColors ?? theme.charts.getColorPalette(4);
  182. const durationOnly =
  183. aggregateOutputFormat === 'duration' ||
  184. data.every(value => aggregateOutputType(value.seriesName) === 'duration');
  185. const percentOnly =
  186. aggregateOutputFormat === 'percentage' ||
  187. data.every(value => aggregateOutputType(value.seriesName) === 'percentage');
  188. if (!dataMax) {
  189. dataMax = durationOnly
  190. ? computeAxisMax(
  191. [...data, ...(scatterPlot?.[0]?.data?.length ? scatterPlot : [])],
  192. stacked
  193. )
  194. : percentOnly
  195. ? computeMax([...data, ...(scatterPlot?.[0]?.data?.length ? scatterPlot : [])])
  196. : undefined;
  197. // Fix an issue where max == 1 for duration charts would look funky cause we round
  198. if (dataMax === 1 && durationOnly) {
  199. dataMax += 1;
  200. }
  201. }
  202. let transformedThroughput: LineSeriesOption[] | undefined = undefined;
  203. const additionalAxis: YAXisOption[] = [];
  204. if (throughput && throughput.length > 1) {
  205. transformedThroughput = [
  206. LineSeries({
  207. name: 'Throughput',
  208. data: throughput.map(({interval, count}) => [interval, count]),
  209. yAxisIndex: 1,
  210. lineStyle: {type: 'dashed', width: 1, opacity: 0.5},
  211. animation: false,
  212. animationThreshold: 1,
  213. animationDuration: 0,
  214. }),
  215. ];
  216. additionalAxis.push({
  217. minInterval: durationUnit ?? getDurationUnit(data),
  218. splitNumber: definedAxisTicks,
  219. max: dataMax,
  220. type: 'value',
  221. axisLabel: {
  222. color: theme.chartLabel,
  223. formatter(value: number) {
  224. return axisLabelFormatter(value, 'number', true);
  225. },
  226. },
  227. splitLine: hideYAxisSplitLine ? {show: false} : undefined,
  228. });
  229. }
  230. const yAxes = [
  231. {
  232. minInterval: durationUnit ?? getDurationUnit(data),
  233. splitNumber: definedAxisTicks,
  234. max: dataMax,
  235. type: log ? 'log' : 'value',
  236. axisLabel: {
  237. color: theme.chartLabel,
  238. formatter(value: number) {
  239. return axisLabelFormatter(
  240. value,
  241. aggregateOutputFormat ?? aggregateOutputType(data[0].seriesName),
  242. undefined,
  243. durationUnit ?? getDurationUnit(data),
  244. rateUnit
  245. );
  246. },
  247. },
  248. splitLine: hideYAxisSplitLine ? {show: false} : undefined,
  249. },
  250. ...additionalAxis,
  251. ];
  252. const formatter: TooltipFormatterCallback<TopLevelFormatterParams> = (
  253. params,
  254. asyncTicket
  255. ) => {
  256. // Kinda jank. Get hovered dom elements and check if any of them are the chart
  257. const hoveredEchartElement = Array.from(document.querySelectorAll(':hover')).find(
  258. element => {
  259. return element.classList.contains('echarts-for-react');
  260. }
  261. );
  262. if (hoveredEchartElement === chartRef?.current?.ele) {
  263. // Return undefined to use default formatter
  264. return getFormatter({
  265. isGroupedByDate: true,
  266. showTimeInTooltip: true,
  267. utc,
  268. valueFormatter: (value, seriesName) => {
  269. return tooltipFormatter(
  270. value,
  271. aggregateOutputFormat ?? aggregateOutputType(seriesName)
  272. );
  273. },
  274. ...tooltipFormatterOptions,
  275. })(params, asyncTicket);
  276. }
  277. // Return empty string, ie no tooltip
  278. return '';
  279. };
  280. const areaChartProps = {
  281. seriesOptions: {
  282. showSymbol: false,
  283. },
  284. grid,
  285. yAxes,
  286. utc,
  287. legend: showLegend
  288. ? {
  289. top: 0,
  290. right: 10,
  291. ...(legendFormatter ? {formatter: legendFormatter} : {}),
  292. }
  293. : undefined,
  294. isGroupedByDate: true,
  295. showTimeInTooltip: true,
  296. tooltip: {
  297. formatter,
  298. trigger: 'axis',
  299. axisPointer: {
  300. type: 'cross',
  301. label: {show: false},
  302. },
  303. valueFormatter: (value, seriesName) => {
  304. return tooltipFormatter(
  305. value,
  306. aggregateOutputFormat ??
  307. aggregateOutputType(data && data.length ? data[0].seriesName : seriesName)
  308. );
  309. },
  310. nameFormatter(value: string) {
  311. return value === 'epm()' ? 'tpm()' : value;
  312. },
  313. },
  314. } as Omit<AreaChartProps, 'series'>;
  315. const series: Series[] = data.map((values, _) => ({
  316. ...values,
  317. yAxisIndex: 0,
  318. xAxisIndex: 0,
  319. }));
  320. // Trims off the last data point because it's incomplete
  321. const trimmedSeries =
  322. period && !start && !end
  323. ? series.map(serie => {
  324. return {
  325. ...serie,
  326. data: serie.data.slice(0, -1),
  327. };
  328. })
  329. : series;
  330. const xAxis: XAXisOption = disableXAxis
  331. ? {
  332. show: false,
  333. axisLabel: {show: true, margin: 0},
  334. axisLine: {show: false},
  335. }
  336. : {
  337. min: moment(trimmedSeries[0]?.data[0]?.name).unix() * 1000,
  338. max:
  339. moment(trimmedSeries[0]?.data[trimmedSeries[0].data.length - 1]?.name).unix() *
  340. 1000,
  341. };
  342. function getChart() {
  343. if (errored) {
  344. return (
  345. <ErrorPanel>
  346. <IconWarning color="gray300" size="lg" />
  347. </ErrorPanel>
  348. );
  349. }
  350. return (
  351. <ChartZoom
  352. router={router}
  353. saveOnZoom
  354. period={period}
  355. start={start}
  356. end={end}
  357. utc={utc}
  358. onDataZoom={onDataZoom}
  359. >
  360. {zoomRenderProps => {
  361. if (isLineChart) {
  362. return (
  363. <BaseChart
  364. {...zoomRenderProps}
  365. ref={chartRef}
  366. height={height}
  367. previousPeriod={previousData}
  368. additionalSeries={transformedThroughput}
  369. xAxis={xAxis}
  370. yAxes={areaChartProps.yAxes}
  371. tooltip={areaChartProps.tooltip}
  372. colors={colors}
  373. grid={grid}
  374. legend={showLegend ? {top: 0, right: 10} : undefined}
  375. onClick={onClick}
  376. onMouseOut={onMouseOut}
  377. onMouseOver={onMouseOver}
  378. onHighlight={onHighlight}
  379. series={[
  380. ...trimmedSeries.map(({seriesName, data: seriesData, ...options}) =>
  381. LineSeries({
  382. ...options,
  383. name: seriesName,
  384. data: seriesData?.map(({value, name}) => [name, value]),
  385. animation: false,
  386. animationThreshold: 1,
  387. animationDuration: 0,
  388. })
  389. ),
  390. ...(scatterPlot ?? []).map(
  391. ({seriesName, data: seriesData, ...options}) =>
  392. ScatterSeries({
  393. ...options,
  394. name: seriesName,
  395. data: seriesData?.map(({value, name}) => [name, value]),
  396. animation: false,
  397. })
  398. ),
  399. ]}
  400. />
  401. );
  402. }
  403. if (isBarChart) {
  404. return (
  405. <BarChart
  406. height={height}
  407. series={trimmedSeries}
  408. xAxis={xAxis}
  409. additionalSeries={transformedThroughput}
  410. yAxes={areaChartProps.yAxes}
  411. tooltip={areaChartProps.tooltip}
  412. colors={colors}
  413. grid={grid}
  414. legend={showLegend ? {top: 0, right: 10} : undefined}
  415. onClick={onClick}
  416. />
  417. );
  418. }
  419. return (
  420. <AreaChart
  421. forwardedRef={chartRef}
  422. height={height}
  423. {...zoomRenderProps}
  424. series={trimmedSeries}
  425. previousPeriod={previousData}
  426. additionalSeries={transformedThroughput}
  427. xAxis={xAxis}
  428. stacked={stacked}
  429. onClick={onClick}
  430. {...areaChartProps}
  431. onLegendSelectChanged={onLegendSelectChanged}
  432. />
  433. );
  434. }}
  435. </ChartZoom>
  436. );
  437. }
  438. return (
  439. <TransitionChart
  440. loading={loading}
  441. reloading={loading}
  442. height={height ? `${height}px` : undefined}
  443. >
  444. <LoadingScreen loading={loading} />
  445. {getChart()}
  446. </TransitionChart>
  447. );
  448. }
  449. export default Chart;
  450. export function useSynchronizeCharts(deps: boolean[] = []) {
  451. const [synchronized, setSynchronized] = useState<boolean>(false);
  452. useEffect(() => {
  453. if (deps.every(Boolean)) {
  454. echarts.connect(STARFISH_CHART_GROUP);
  455. setSynchronized(true);
  456. }
  457. }, [deps, synchronized]);
  458. }
  459. const StyledTransparentLoadingMask = styled(props => (
  460. <TransparentLoadingMask {...props} maskBackgroundColor="transparent" />
  461. ))`
  462. display: flex;
  463. justify-content: center;
  464. align-items: center;
  465. `;
  466. function LoadingScreen({loading}: {loading: boolean}) {
  467. if (!loading) {
  468. return null;
  469. }
  470. return (
  471. <StyledTransparentLoadingMask visible={loading}>
  472. <LoadingIndicator mini />
  473. </StyledTransparentLoadingMask>
  474. );
  475. }