eventGraph.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import {type CSSProperties, useMemo, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import Alert from 'sentry/components/alert';
  5. import {Button, type ButtonProps} from 'sentry/components/button';
  6. import {BarChart, type BarChartSeries} from 'sentry/components/charts/barChart';
  7. import Legend from 'sentry/components/charts/components/legend';
  8. import {defaultFormatAxisLabel} from 'sentry/components/charts/components/tooltip';
  9. import {useChartZoom} from 'sentry/components/charts/useChartZoom';
  10. import {Flex} from 'sentry/components/container/flex';
  11. import InteractionStateLayer from 'sentry/components/interactionStateLayer';
  12. import Placeholder from 'sentry/components/placeholder';
  13. import {t, tct, tn} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import type {SeriesDataUnit} from 'sentry/types/echarts';
  16. import type {Event} from 'sentry/types/event';
  17. import type {Group} from 'sentry/types/group';
  18. import type {EventsStats, MultiSeriesEventsStats} from 'sentry/types/organization';
  19. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  20. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  21. import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig';
  22. import {useApiQuery} from 'sentry/utils/queryClient';
  23. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  24. import {useLocation} from 'sentry/utils/useLocation';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import {getBucketSize} from 'sentry/views/dashboards/widgetCard/utils';
  27. import useFlagSeries from 'sentry/views/issueDetails/streamline/useFlagSeries';
  28. import {
  29. useIssueDetailsDiscoverQuery,
  30. useIssueDetailsEventView,
  31. } from 'sentry/views/issueDetails/streamline/useIssueDetailsDiscoverQuery';
  32. import {useReleaseMarkLineSeries} from 'sentry/views/issueDetails/streamline/useReleaseMarkLineSeries';
  33. export const enum EventGraphSeries {
  34. EVENT = 'event',
  35. USER = 'user',
  36. }
  37. interface EventGraphProps {
  38. event: Event | undefined;
  39. group: Group;
  40. className?: string;
  41. style?: CSSProperties;
  42. }
  43. function createSeriesAndCount(stats: EventsStats) {
  44. return stats?.data?.reduce(
  45. (result, [timestamp, countData]) => {
  46. const count = countData?.[0]?.count ?? 0;
  47. return {
  48. series: [
  49. ...result.series,
  50. {
  51. name: timestamp * 1000, // ms -> s
  52. value: count,
  53. },
  54. ],
  55. count: result.count + count,
  56. };
  57. },
  58. {series: [] as SeriesDataUnit[], count: 0}
  59. );
  60. }
  61. export function EventGraph({group, event, ...styleProps}: EventGraphProps) {
  62. const theme = useTheme();
  63. const organization = useOrganization();
  64. const location = useLocation();
  65. const [visibleSeries, setVisibleSeries] = useState<EventGraphSeries>(
  66. EventGraphSeries.EVENT
  67. );
  68. const eventView = useIssueDetailsEventView({group});
  69. const hasFeatureFlagFeature = organization.features.includes('feature-flag-ui');
  70. const config = getConfigForIssueType(group, group.project);
  71. const {
  72. data: groupStats = {},
  73. isPending: isLoadingStats,
  74. error,
  75. } = useIssueDetailsDiscoverQuery<MultiSeriesEventsStats>({
  76. params: {
  77. route: 'events-stats',
  78. eventView,
  79. referrer: 'issue_details.streamline_graph',
  80. },
  81. });
  82. const {data: uniqueUsersCount, isPending: isPendingUniqueUsersCount} = useApiQuery<{
  83. data: Array<{count_unique: number}>;
  84. }>(
  85. [
  86. `/organizations/${organization.slug}/events/`,
  87. {
  88. query: {
  89. ...eventView.getEventsAPIPayload(location),
  90. dataset: config.usesIssuePlatform
  91. ? DiscoverDatasets.ISSUE_PLATFORM
  92. : DiscoverDatasets.ERRORS,
  93. field: 'count_unique(user)',
  94. per_page: 50,
  95. project: group.project.id,
  96. query: eventView.query,
  97. referrer: 'issue_details.streamline_graph',
  98. },
  99. },
  100. ],
  101. {
  102. staleTime: 60_000,
  103. }
  104. );
  105. const userCount = uniqueUsersCount?.data[0]?.['count_unique(user)'] ?? 0;
  106. const {series: eventSeries, count: eventCount} = useMemo(() => {
  107. if (!groupStats['count()']) {
  108. return {series: [], count: 0};
  109. }
  110. return createSeriesAndCount(groupStats['count()']);
  111. }, [groupStats]);
  112. const userSeries = useMemo(() => {
  113. if (!groupStats['count_unique(user)']) {
  114. return [];
  115. }
  116. return createSeriesAndCount(groupStats['count_unique(user)']).series;
  117. }, [groupStats]);
  118. const chartZoomProps = useChartZoom({
  119. saveOnZoom: true,
  120. });
  121. const releaseSeries = useReleaseMarkLineSeries({group});
  122. const flagSeries = useFlagSeries({
  123. query: {
  124. start: eventView.start,
  125. end: eventView.end,
  126. statsPeriod: eventView.statsPeriod,
  127. },
  128. event,
  129. });
  130. const series = useMemo((): BarChartSeries[] => {
  131. const seriesData: BarChartSeries[] = [];
  132. if (visibleSeries === EventGraphSeries.USER) {
  133. seriesData.push({
  134. seriesName: t('Users'),
  135. itemStyle: {
  136. borderRadius: [2, 2, 0, 0],
  137. borderColor: theme.translucentGray200,
  138. color: theme.purple200,
  139. },
  140. stack: 'stats',
  141. data: userSeries,
  142. animation: false,
  143. });
  144. }
  145. if (visibleSeries === EventGraphSeries.EVENT) {
  146. seriesData.push({
  147. seriesName: t('Events'),
  148. itemStyle: {
  149. borderRadius: [2, 2, 0, 0],
  150. borderColor: theme.translucentGray200,
  151. color: theme.gray200,
  152. },
  153. stack: 'stats',
  154. data: eventSeries,
  155. animation: false,
  156. });
  157. }
  158. if (releaseSeries.markLine) {
  159. seriesData.push(releaseSeries as BarChartSeries);
  160. }
  161. if (flagSeries.markLine && hasFeatureFlagFeature) {
  162. seriesData.push(flagSeries as BarChartSeries);
  163. }
  164. return seriesData;
  165. }, [
  166. visibleSeries,
  167. userSeries,
  168. eventSeries,
  169. releaseSeries,
  170. flagSeries,
  171. theme,
  172. hasFeatureFlagFeature,
  173. ]);
  174. const bucketSize = eventSeries ? getBucketSize(series) : undefined;
  175. const [legendSelected, setLegendSelected] = useLocalStorageState(
  176. 'issue-details-graph-legend',
  177. {
  178. ['Feature Flags']: true,
  179. ['Releases']: true,
  180. }
  181. );
  182. const legend = Legend({
  183. theme: theme,
  184. orient: 'horizontal',
  185. align: 'left',
  186. show: true,
  187. top: 4,
  188. right: 8,
  189. data: hasFeatureFlagFeature ? ['Feature Flags', 'Releases'] : ['Releases'],
  190. selected: legendSelected,
  191. zlevel: 10,
  192. });
  193. const onLegendSelectChanged = useMemo(
  194. () =>
  195. ({name, selected: record}) => {
  196. const newValue = record[name];
  197. setLegendSelected(prevState => ({
  198. ...prevState,
  199. [name]: newValue,
  200. }));
  201. },
  202. [setLegendSelected]
  203. );
  204. if (error) {
  205. return (
  206. <GraphAlert type="error" showIcon {...styleProps}>
  207. {tct('Graph Query Error: [message]', {message: error.message})}
  208. </GraphAlert>
  209. );
  210. }
  211. if (isLoadingStats || isPendingUniqueUsersCount) {
  212. return (
  213. <GraphWrapper {...styleProps}>
  214. <SummaryContainer>
  215. <GraphButton
  216. isActive={visibleSeries === EventGraphSeries.EVENT}
  217. disabled
  218. label={t('Events')}
  219. />
  220. <GraphButton
  221. isActive={visibleSeries === EventGraphSeries.USER}
  222. disabled
  223. label={t('Users')}
  224. />
  225. </SummaryContainer>
  226. <LoadingChartContainer>
  227. <Placeholder height="96px" testId="event-graph-loading" />
  228. </LoadingChartContainer>
  229. </GraphWrapper>
  230. );
  231. }
  232. return (
  233. <GraphWrapper {...styleProps}>
  234. <SummaryContainer>
  235. <GraphButton
  236. onClick={() =>
  237. visibleSeries === EventGraphSeries.USER &&
  238. setVisibleSeries(EventGraphSeries.EVENT)
  239. }
  240. isActive={visibleSeries === EventGraphSeries.EVENT}
  241. disabled={visibleSeries === EventGraphSeries.EVENT}
  242. label={tn('Event', 'Events', eventCount)}
  243. count={String(eventCount)}
  244. />
  245. <GraphButton
  246. onClick={() =>
  247. visibleSeries === EventGraphSeries.EVENT &&
  248. setVisibleSeries(EventGraphSeries.USER)
  249. }
  250. isActive={visibleSeries === EventGraphSeries.USER}
  251. disabled={visibleSeries === EventGraphSeries.USER}
  252. label={tn('User', 'Users', userCount)}
  253. count={String(userCount)}
  254. />
  255. </SummaryContainer>
  256. <ChartContainer role="figure">
  257. <BarChart
  258. height={100}
  259. series={series}
  260. legend={legend}
  261. onLegendSelectChanged={onLegendSelectChanged}
  262. showTimeInTooltip
  263. grid={{
  264. left: 8,
  265. right: 8,
  266. top: 20,
  267. bottom: 0,
  268. }}
  269. tooltip={{
  270. formatAxisLabel: (
  271. value,
  272. isTimestamp,
  273. utc,
  274. showTimeInTooltip,
  275. addSecondsToTimeFormat,
  276. _bucketSize,
  277. _seriesParamsOrParam
  278. ) =>
  279. String(
  280. defaultFormatAxisLabel(
  281. value,
  282. isTimestamp,
  283. utc,
  284. showTimeInTooltip,
  285. addSecondsToTimeFormat,
  286. bucketSize
  287. )
  288. ),
  289. }}
  290. yAxis={{
  291. splitNumber: 2,
  292. minInterval: 1,
  293. axisLabel: {
  294. formatter: (value: number) => {
  295. return formatAbbreviatedNumber(value);
  296. },
  297. },
  298. }}
  299. {...chartZoomProps}
  300. />
  301. </ChartContainer>
  302. </GraphWrapper>
  303. );
  304. }
  305. function GraphButton({
  306. isActive,
  307. label,
  308. count,
  309. ...props
  310. }: {isActive: boolean; label: string; count?: string} & Partial<ButtonProps>) {
  311. return (
  312. <Callout
  313. isActive={isActive}
  314. aria-label={`${t('Toggle graph series')} - ${label}`}
  315. {...props}
  316. >
  317. <InteractionStateLayer hidden={isActive} />
  318. <Flex column>
  319. <Label isActive={isActive}>{label}</Label>
  320. <Count isActive={isActive}>{count ? formatAbbreviatedNumber(count) : '-'}</Count>
  321. </Flex>
  322. </Callout>
  323. );
  324. }
  325. const GraphWrapper = styled('div')`
  326. display: grid;
  327. grid-template-columns: auto 1fr;
  328. `;
  329. const SummaryContainer = styled('div')`
  330. display: flex;
  331. gap: ${space(0.5)};
  332. flex-direction: column;
  333. margin: ${space(1)} ${space(1)} ${space(1)} 0;
  334. border-radius: ${p => p.theme.borderRadiusLeft};
  335. `;
  336. const Callout = styled(Button)<{isActive: boolean}>`
  337. cursor: ${p => (p.isActive ? 'initial' : 'pointer')};
  338. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  339. background: ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  340. padding: ${space(0.5)} ${space(2)};
  341. box-shadow: none;
  342. height: unset;
  343. overflow: hidden;
  344. &:disabled {
  345. opacity: 1;
  346. }
  347. &:hover {
  348. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  349. }
  350. `;
  351. const Label = styled('div')<{isActive: boolean}>`
  352. line-height: 1;
  353. font-size: ${p => p.theme.fontSizeSmall};
  354. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.subText)};
  355. `;
  356. const Count = styled('div')<{isActive: boolean}>`
  357. line-height: 1;
  358. margin-top: ${space(0.5)};
  359. font-size: 20px;
  360. font-weight: ${p => p.theme.fontWeightNormal};
  361. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.textColor)};
  362. `;
  363. const ChartContainer = styled('div')`
  364. position: relative;
  365. padding: ${space(0.75)} ${space(1)} ${space(0.75)} 0;
  366. `;
  367. const LoadingChartContainer = styled('div')`
  368. position: relative;
  369. padding: ${space(1)} ${space(1)};
  370. `;
  371. const GraphAlert = styled(Alert)`
  372. padding-left: 24px;
  373. margin: 0 0 0 -24px;
  374. border: 0;
  375. border-radius: 0;
  376. `;