eventGraph.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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']: false,
  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. inactiveColor: theme.gray200,
  193. });
  194. const onLegendSelectChanged = useMemo(
  195. () =>
  196. ({name, selected: record}) => {
  197. const newValue = record[name];
  198. setLegendSelected(prevState => ({
  199. ...prevState,
  200. [name]: newValue,
  201. }));
  202. },
  203. [setLegendSelected]
  204. );
  205. if (error) {
  206. return (
  207. <GraphAlert type="error" showIcon {...styleProps}>
  208. {tct('Graph Query Error: [message]', {message: error.message})}
  209. </GraphAlert>
  210. );
  211. }
  212. if (isLoadingStats || isPendingUniqueUsersCount) {
  213. return (
  214. <GraphWrapper {...styleProps}>
  215. <SummaryContainer>
  216. <GraphButton
  217. isActive={visibleSeries === EventGraphSeries.EVENT}
  218. disabled
  219. label={t('Events')}
  220. />
  221. <GraphButton
  222. isActive={visibleSeries === EventGraphSeries.USER}
  223. disabled
  224. label={t('Users')}
  225. />
  226. </SummaryContainer>
  227. <LoadingChartContainer>
  228. <Placeholder height="96px" testId="event-graph-loading" />
  229. </LoadingChartContainer>
  230. </GraphWrapper>
  231. );
  232. }
  233. return (
  234. <GraphWrapper {...styleProps}>
  235. <SummaryContainer>
  236. <GraphButton
  237. onClick={() =>
  238. visibleSeries === EventGraphSeries.USER &&
  239. setVisibleSeries(EventGraphSeries.EVENT)
  240. }
  241. isActive={visibleSeries === EventGraphSeries.EVENT}
  242. disabled={visibleSeries === EventGraphSeries.EVENT}
  243. label={tn('Event', 'Events', eventCount)}
  244. count={String(eventCount)}
  245. />
  246. <GraphButton
  247. onClick={() =>
  248. visibleSeries === EventGraphSeries.EVENT &&
  249. setVisibleSeries(EventGraphSeries.USER)
  250. }
  251. isActive={visibleSeries === EventGraphSeries.USER}
  252. disabled={visibleSeries === EventGraphSeries.USER}
  253. label={tn('User', 'Users', userCount)}
  254. count={String(userCount)}
  255. />
  256. </SummaryContainer>
  257. <ChartContainer role="figure">
  258. <BarChart
  259. height={100}
  260. series={series}
  261. legend={legend}
  262. onLegendSelectChanged={onLegendSelectChanged}
  263. showTimeInTooltip
  264. grid={{
  265. left: 8,
  266. right: 8,
  267. top: 20,
  268. bottom: 0,
  269. }}
  270. tooltip={{
  271. formatAxisLabel: (
  272. value,
  273. isTimestamp,
  274. utc,
  275. showTimeInTooltip,
  276. addSecondsToTimeFormat,
  277. _bucketSize,
  278. _seriesParamsOrParam
  279. ) =>
  280. String(
  281. defaultFormatAxisLabel(
  282. value,
  283. isTimestamp,
  284. utc,
  285. showTimeInTooltip,
  286. addSecondsToTimeFormat,
  287. bucketSize
  288. )
  289. ),
  290. }}
  291. yAxis={{
  292. splitNumber: 2,
  293. minInterval: 1,
  294. axisLabel: {
  295. formatter: (value: number) => {
  296. return formatAbbreviatedNumber(value);
  297. },
  298. },
  299. }}
  300. {...chartZoomProps}
  301. />
  302. </ChartContainer>
  303. </GraphWrapper>
  304. );
  305. }
  306. function GraphButton({
  307. isActive,
  308. label,
  309. count,
  310. ...props
  311. }: {isActive: boolean; label: string; count?: string} & Partial<ButtonProps>) {
  312. return (
  313. <Callout
  314. isActive={isActive}
  315. aria-label={`${t('Toggle graph series')} - ${label}`}
  316. {...props}
  317. >
  318. <InteractionStateLayer hidden={isActive} />
  319. <Flex column>
  320. <Label isActive={isActive}>{label}</Label>
  321. <Count isActive={isActive}>{count ? formatAbbreviatedNumber(count) : '-'}</Count>
  322. </Flex>
  323. </Callout>
  324. );
  325. }
  326. const GraphWrapper = styled('div')`
  327. display: grid;
  328. grid-template-columns: auto 1fr;
  329. `;
  330. const SummaryContainer = styled('div')`
  331. display: flex;
  332. gap: ${space(0.5)};
  333. flex-direction: column;
  334. margin: ${space(1)} ${space(1)} ${space(1)} 0;
  335. border-radius: ${p => p.theme.borderRadiusLeft};
  336. `;
  337. const Callout = styled(Button)<{isActive: boolean}>`
  338. cursor: ${p => (p.isActive ? 'initial' : 'pointer')};
  339. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  340. background: ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  341. padding: ${space(0.5)} ${space(2)};
  342. box-shadow: none;
  343. height: unset;
  344. overflow: hidden;
  345. &:disabled {
  346. opacity: 1;
  347. }
  348. &:hover {
  349. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  350. }
  351. `;
  352. const Label = styled('div')<{isActive: boolean}>`
  353. line-height: 1;
  354. font-size: ${p => p.theme.fontSizeSmall};
  355. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.subText)};
  356. `;
  357. const Count = styled('div')<{isActive: boolean}>`
  358. line-height: 1;
  359. margin-top: ${space(0.5)};
  360. font-size: 20px;
  361. font-weight: ${p => p.theme.fontWeightNormal};
  362. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.textColor)};
  363. `;
  364. const ChartContainer = styled('div')`
  365. position: relative;
  366. padding: ${space(0.75)} ${space(1)} ${space(0.75)} 0;
  367. `;
  368. const LoadingChartContainer = styled('div')`
  369. position: relative;
  370. padding: ${space(1)} ${space(1)};
  371. `;
  372. const GraphAlert = styled(Alert)`
  373. padding-left: 24px;
  374. margin: 0 0 0 -24px;
  375. border: 0;
  376. border-radius: 0;
  377. `;