eventGraph.tsx 11 KB

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