chart.tsx 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. import {useEffect, useRef} from 'react';
  2. import {Theme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {useHover} from '@react-aria/interactions';
  5. import {AreaChart} from 'sentry/components/charts/areaChart';
  6. import {BarChart} from 'sentry/components/charts/barChart';
  7. import ChartZoom from 'sentry/components/charts/chartZoom';
  8. import Legend from 'sentry/components/charts/components/legend';
  9. import {LineChart} from 'sentry/components/charts/lineChart';
  10. import ReleaseSeries from 'sentry/components/charts/releaseSeries';
  11. import {RELEASE_LINES_THRESHOLD} from 'sentry/components/charts/utils';
  12. import {t} from 'sentry/locale';
  13. import {DateString, PageFilters} from 'sentry/types';
  14. import {ReactEchartsRef} from 'sentry/types/echarts';
  15. import {
  16. formatMetricsUsingUnitAndOp,
  17. getNameFromMRI,
  18. MetricDisplayType,
  19. } from 'sentry/utils/metrics';
  20. import theme from 'sentry/utils/theme';
  21. import useRouter from 'sentry/utils/useRouter';
  22. import {DDM_CHART_GROUP} from 'sentry/views/ddm/constants';
  23. import {getFormatter} from '../../components/charts/components/tooltip';
  24. import {Series} from './widget';
  25. type ChartProps = {
  26. displayType: MetricDisplayType;
  27. environments: PageFilters['environments'];
  28. projects: PageFilters['projects'];
  29. series: Series[];
  30. end?: string;
  31. onZoom?: (start: DateString, end: DateString) => void;
  32. operation?: string;
  33. period?: string;
  34. start?: string;
  35. utc?: boolean;
  36. };
  37. export function MetricChart({
  38. series,
  39. displayType,
  40. start,
  41. end,
  42. period,
  43. utc,
  44. operation,
  45. projects,
  46. environments,
  47. onZoom,
  48. }: ChartProps) {
  49. const chartRef = useRef<ReactEchartsRef>(null);
  50. const router = useRouter();
  51. const {hoverProps, isHovered} = useHover({
  52. isDisabled: false,
  53. });
  54. // TODO(ddm): Try to do this in a more elegant way
  55. useEffect(() => {
  56. const echartsInstance = chartRef?.current?.getEchartsInstance();
  57. if (echartsInstance && !echartsInstance.group) {
  58. echartsInstance.group = DDM_CHART_GROUP;
  59. }
  60. });
  61. const unit = series[0]?.unit;
  62. const seriesToShow = series.filter(s => !s.hidden);
  63. // TODO(ddm): This assumes that all series have the same bucket size
  64. const bucketSize = seriesToShow[0]?.data[1]?.name - seriesToShow[0]?.data[0]?.name;
  65. const isSubMinuteBucket = bucketSize < 60_000;
  66. const seriesLength = seriesToShow[0]?.data.length;
  67. const formatters = {
  68. valueFormatter: (value: number) =>
  69. formatMetricsUsingUnitAndOp(value, unit, operation),
  70. nameFormatter: mri => getNameFromMRI(mri),
  71. isGroupedByDate: true,
  72. bucketSize,
  73. showTimeInTooltip: true,
  74. addSecondsToTimeFormat: isSubMinuteBucket,
  75. };
  76. const displayFogOfWar = operation && ['sum', 'count'].includes(operation);
  77. const chartProps = {
  78. forwardedRef: chartRef,
  79. isGroupedByDate: true,
  80. height: 300,
  81. colors: seriesToShow.map(s => s.color),
  82. grid: {top: 20, bottom: 20, left: 15, right: 25},
  83. tooltip: {
  84. formatter: (params, asyncTicket) => {
  85. const hoveredEchartElement = Array.from(document.querySelectorAll(':hover')).find(
  86. element => {
  87. return element.classList.contains('echarts-for-react');
  88. }
  89. );
  90. if (hoveredEchartElement === chartRef?.current?.ele) {
  91. return getFormatter(formatters)(params, asyncTicket);
  92. }
  93. return '';
  94. },
  95. },
  96. yAxis: {
  97. axisLabel: {
  98. formatter: (value: number) => {
  99. return formatMetricsUsingUnitAndOp(value, unit, operation);
  100. },
  101. },
  102. },
  103. };
  104. return (
  105. <ChartWrapper {...hoverProps}>
  106. <ChartZoom
  107. router={router}
  108. period={period}
  109. start={start}
  110. end={end}
  111. utc={utc}
  112. onZoom={zoomPeriod => {
  113. onZoom?.(zoomPeriod.start, zoomPeriod.end);
  114. }}
  115. >
  116. {zoomRenderProps => (
  117. <ReleaseSeries
  118. utc={utc}
  119. period={period}
  120. start={zoomRenderProps.start!}
  121. end={zoomRenderProps.end!}
  122. projects={projects}
  123. environments={environments}
  124. preserveQueryParams
  125. >
  126. {({releaseSeries}) => {
  127. const releaseSeriesData = releaseSeries?.[0]?.markLine?.data ?? [];
  128. const selected =
  129. releaseSeriesData?.length >= RELEASE_LINES_THRESHOLD
  130. ? {[t('Releases')]: false}
  131. : {};
  132. const legend = releaseSeriesData?.length
  133. ? Legend({
  134. itemGap: 20,
  135. top: 0,
  136. right: 20,
  137. data: releaseSeries.map(s => s.seriesName),
  138. theme: theme as Theme,
  139. selected,
  140. })
  141. : undefined;
  142. // Zoom render props are slowing down the chart rendering,
  143. // so we only pass them when the chart is hovered over
  144. const zoomProps = isHovered ? zoomRenderProps : {};
  145. const allProps = {
  146. ...chartProps,
  147. ...zoomProps,
  148. series: [...seriesToShow, ...releaseSeries],
  149. legend,
  150. };
  151. return displayType === MetricDisplayType.LINE ? (
  152. <LineChart {...allProps} />
  153. ) : displayType === MetricDisplayType.AREA ? (
  154. <AreaChart {...allProps} />
  155. ) : (
  156. <BarChart stacked animation={false} {...allProps} />
  157. );
  158. }}
  159. </ReleaseSeries>
  160. )}
  161. </ChartZoom>
  162. {displayFogOfWar && (
  163. <FogOfWar bucketSize={bucketSize} seriesLength={seriesLength} />
  164. )}
  165. </ChartWrapper>
  166. );
  167. }
  168. function FogOfWar({
  169. bucketSize,
  170. seriesLength,
  171. }: {
  172. bucketSize?: number;
  173. seriesLength?: number;
  174. }) {
  175. if (!bucketSize || !seriesLength) {
  176. return null;
  177. }
  178. const widthFactor = getWidthFactor(bucketSize);
  179. const fogOfWarWidth = widthFactor * bucketSize + 30_000;
  180. const seriesWidth = bucketSize * seriesLength;
  181. // If either of these are undefiend, NaN or 0 the result will be invalid
  182. if (!fogOfWarWidth || !seriesWidth) {
  183. return null;
  184. }
  185. const width = (fogOfWarWidth / seriesWidth) * 100;
  186. return <FogOfWarOverlay width={width ?? 0} />;
  187. }
  188. function getWidthFactor(bucketSize: number) {
  189. // In general, fog of war should cover the last bucket
  190. if (bucketSize > 30 * 60_000) {
  191. return 1;
  192. }
  193. // for 10s timeframe we want to show a fog of war that spans last 10 buckets
  194. // because on average, we are missing last 90 seconds of data
  195. if (bucketSize <= 10_000) {
  196. return 10;
  197. }
  198. // For smaller time frames we want to show a wider fog of war
  199. return 2;
  200. }
  201. const ChartWrapper = styled('div')`
  202. position: relative;
  203. height: 300px;
  204. `;
  205. const FogOfWarOverlay = styled('div')<{width?: number}>`
  206. height: 244px;
  207. width: ${p => p.width}%;
  208. position: absolute;
  209. right: 21px;
  210. top: 18px;
  211. pointer-events: none;
  212. background: linear-gradient(
  213. 90deg,
  214. ${p => p.theme.background}00 0%,
  215. ${p => p.theme.background}FF 70%,
  216. ${p => p.theme.background}FF 100%
  217. );
  218. `;