chart.tsx 14 KB

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