chart.tsx 6.6 KB

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