index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import type {Dispatch, SetStateAction} from 'react';
  2. import {Fragment, useCallback, useEffect, useMemo} from 'react';
  3. import styled from '@emotion/styled';
  4. import Feature from 'sentry/components/acl/feature';
  5. import {getInterval} from 'sentry/components/charts/utils';
  6. import {CompactSelect} from 'sentry/components/compactSelect';
  7. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  8. import {Tooltip} from 'sentry/components/tooltip';
  9. import {CHART_PALETTE} from 'sentry/constants/chartPalette';
  10. import {IconClock, IconGraph, IconSubscribed} from 'sentry/icons';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {dedupeArray} from 'sentry/utils/dedupeArray';
  14. import {
  15. aggregateOutputType,
  16. formatParsedFunction,
  17. parseFunction,
  18. } from 'sentry/utils/discover/fields';
  19. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import usePageFilters from 'sentry/utils/usePageFilters';
  22. import useProjects from 'sentry/utils/useProjects';
  23. import {formatVersion} from 'sentry/utils/versions/formatVersion';
  24. import {Dataset} from 'sentry/views/alerts/rules/metric/types';
  25. import {useChartInterval} from 'sentry/views/explore/hooks/useChartInterval';
  26. import {useDataset} from 'sentry/views/explore/hooks/useDataset';
  27. import {useVisualizes} from 'sentry/views/explore/hooks/useVisualizes';
  28. import Chart, {
  29. ChartType,
  30. useSynchronizeCharts,
  31. } from 'sentry/views/insights/common/components/chart';
  32. import ChartPanel from 'sentry/views/insights/common/components/chartPanel';
  33. import {useSortedTimeSeries} from 'sentry/views/insights/common/queries/useSortedTimeSeries';
  34. import {getAlertsUrl} from 'sentry/views/insights/common/utils/getAlertsUrl';
  35. import {CHART_HEIGHT} from 'sentry/views/insights/database/settings';
  36. import {useGroupBys} from '../hooks/useGroupBys';
  37. import {useResultMode} from '../hooks/useResultsMode';
  38. import {useSorts} from '../hooks/useSorts';
  39. import {TOP_EVENTS_LIMIT, useTopEvents} from '../hooks/useTopEvents';
  40. import {formatSort} from '../tables/aggregatesTable';
  41. interface ExploreChartsProps {
  42. query: string;
  43. setError: Dispatch<SetStateAction<string>>;
  44. }
  45. const exploreChartTypeOptions = [
  46. {
  47. value: ChartType.LINE,
  48. label: t('Line'),
  49. },
  50. {
  51. value: ChartType.AREA,
  52. label: t('Area'),
  53. },
  54. {
  55. value: ChartType.BAR,
  56. label: t('Bar'),
  57. },
  58. ];
  59. export const EXPLORE_CHART_GROUP = 'explore-charts_group';
  60. // TODO: Update to support aggregate mode and multiple queries / visualizations
  61. export function ExploreCharts({query, setError}: ExploreChartsProps) {
  62. const pageFilters = usePageFilters();
  63. const organization = useOrganization();
  64. const {projects} = useProjects();
  65. const [dataset] = useDataset();
  66. const [visualizes, setVisualizes] = useVisualizes();
  67. const [interval, setInterval, intervalOptions] = useChartInterval();
  68. const {groupBys} = useGroupBys();
  69. const [resultMode] = useResultMode();
  70. const topEvents = useTopEvents();
  71. const fields: string[] = useMemo(() => {
  72. if (resultMode === 'samples') {
  73. return [];
  74. }
  75. return [...groupBys, ...visualizes.flatMap(visualize => visualize.yAxes)].filter(
  76. Boolean
  77. );
  78. }, [resultMode, groupBys, visualizes]);
  79. const [sorts] = useSorts({fields});
  80. const orderby: string | string[] | undefined = useMemo(() => {
  81. if (!sorts.length) {
  82. return undefined;
  83. }
  84. return sorts.map(formatSort);
  85. }, [sorts]);
  86. const yAxes = useMemo(() => {
  87. const deduped = dedupeArray(visualizes.flatMap(visualize => visualize.yAxes));
  88. deduped.sort();
  89. return deduped;
  90. }, [visualizes]);
  91. const search = new MutableSearch(query);
  92. // Filtering out all spans with op like 'ui.interaction*' which aren't
  93. // embedded under transactions. The trace view does not support rendering
  94. // such spans yet.
  95. search.addFilterValues('!transaction.span_id', ['00']);
  96. const timeSeriesResult = useSortedTimeSeries(
  97. {
  98. search,
  99. yAxis: yAxes,
  100. interval: interval ?? getInterval(pageFilters.selection.datetime, 'metrics'),
  101. fields,
  102. orderby,
  103. topEvents,
  104. },
  105. 'api.explorer.stats',
  106. dataset
  107. );
  108. useEffect(() => {
  109. setError(timeSeriesResult.error?.message ?? '');
  110. }, [setError, timeSeriesResult.error?.message]);
  111. const getSeries = useCallback(
  112. (dedupedYAxes: string[]) => {
  113. return dedupedYAxes.flatMap(yAxis => {
  114. const series = timeSeriesResult.data[yAxis];
  115. return series !== undefined ? series : [];
  116. });
  117. },
  118. [timeSeriesResult]
  119. );
  120. const handleChartTypeChange = useCallback(
  121. (chartType: ChartType, index: number) => {
  122. const newVisualizes = visualizes.slice();
  123. newVisualizes[index] = {...newVisualizes[index], chartType};
  124. setVisualizes(newVisualizes);
  125. },
  126. [visualizes, setVisualizes]
  127. );
  128. useSynchronizeCharts(
  129. visualizes.length,
  130. !timeSeriesResult.isPending,
  131. EXPLORE_CHART_GROUP
  132. );
  133. const shouldRenderLabel = visualizes.length > 1;
  134. return (
  135. <Fragment>
  136. {visualizes.map((visualize, index) => {
  137. const dedupedYAxes = dedupeArray(visualize.yAxes);
  138. const formattedYAxes = dedupedYAxes
  139. .map(yaxis => {
  140. const func = parseFunction(yaxis);
  141. return func ? formatParsedFunction(func) : undefined;
  142. })
  143. .filter(Boolean);
  144. const {chartType, label, yAxes: visualizeYAxes} = visualize;
  145. const chartIcon =
  146. chartType === ChartType.LINE
  147. ? 'line'
  148. : chartType === ChartType.AREA
  149. ? 'area'
  150. : 'bar';
  151. const project =
  152. projects.length === 1
  153. ? projects[0]
  154. : projects.find(p => p.id === `${pageFilters.selection.projects[0]}`);
  155. const singleProject =
  156. (pageFilters.selection.projects.length === 1 || projects.length === 1) &&
  157. project;
  158. const alertsUrls = singleProject
  159. ? visualizeYAxes.map(yAxis => ({
  160. key: yAxis,
  161. label: yAxis,
  162. to: getAlertsUrl({
  163. project,
  164. query,
  165. pageFilters: pageFilters.selection,
  166. aggregate: yAxis,
  167. orgSlug: organization.slug,
  168. dataset: Dataset.EVENTS_ANALYTICS_PLATFORM,
  169. interval,
  170. }),
  171. }))
  172. : undefined;
  173. return (
  174. <ChartContainer key={index}>
  175. <ChartPanel>
  176. <ChartHeader>
  177. {shouldRenderLabel && <ChartLabel>{label}</ChartLabel>}
  178. <ChartTitle>{formattedYAxes.join(', ')}</ChartTitle>
  179. <Tooltip
  180. title={t('Type of chart displayed in this visualization (ex. line)')}
  181. >
  182. <CompactSelect
  183. triggerProps={{
  184. icon: <IconGraph type={chartIcon} />,
  185. borderless: true,
  186. showChevron: false,
  187. size: 'sm',
  188. }}
  189. value={chartType}
  190. menuTitle="Type"
  191. options={exploreChartTypeOptions}
  192. onChange={option => handleChartTypeChange(option.value, index)}
  193. />
  194. </Tooltip>
  195. <Tooltip
  196. title={t('Time interval displayed in this visualization (ex. 5m)')}
  197. >
  198. <CompactSelect
  199. value={interval}
  200. onChange={({value}) => setInterval(value)}
  201. triggerProps={{
  202. icon: <IconClock />,
  203. borderless: true,
  204. showChevron: false,
  205. size: 'sm',
  206. }}
  207. menuTitle="Interval"
  208. options={intervalOptions}
  209. />
  210. </Tooltip>
  211. <Feature features="organizations:alerts-eap">
  212. <Tooltip
  213. title={
  214. singleProject
  215. ? t('Create an alert for this chart')
  216. : t('Cannot create an alert when multiple projects are selected')
  217. }
  218. >
  219. <DropdownMenu
  220. triggerProps={{
  221. 'aria-label': t('Create Alert'),
  222. size: 'sm',
  223. borderless: true,
  224. showChevron: false,
  225. icon: <IconSubscribed />,
  226. }}
  227. position="bottom-end"
  228. items={alertsUrls ?? []}
  229. menuTitle={t('Create an alert for')}
  230. isDisabled={!alertsUrls || alertsUrls.length === 0}
  231. />
  232. </Tooltip>
  233. </Feature>
  234. </ChartHeader>
  235. <Chart
  236. height={CHART_HEIGHT}
  237. grid={{
  238. left: '0',
  239. right: '0',
  240. top: '8px',
  241. bottom: '0',
  242. }}
  243. legendFormatter={value => formatVersion(value)}
  244. data={getSeries(dedupedYAxes)}
  245. error={timeSeriesResult.error}
  246. loading={timeSeriesResult.isPending}
  247. chartGroup={EXPLORE_CHART_GROUP}
  248. // TODO Abdullah: Make chart colors dynamic, with changing topN events count and overlay count.
  249. chartColors={CHART_PALETTE[TOP_EVENTS_LIMIT - 1]}
  250. type={chartType}
  251. // for now, use the first y axis unit
  252. aggregateOutputFormat={aggregateOutputType(dedupedYAxes[0])}
  253. />
  254. </ChartPanel>
  255. </ChartContainer>
  256. );
  257. })}
  258. </Fragment>
  259. );
  260. }
  261. const ChartContainer = styled('div')`
  262. display: grid;
  263. gap: 0;
  264. grid-template-columns: 1fr;
  265. margin-bottom: ${space(2)};
  266. `;
  267. const ChartHeader = styled('div')`
  268. display: flex;
  269. justify-content: space-between;
  270. `;
  271. const ChartTitle = styled('div')`
  272. ${p => p.theme.text.cardTitle}
  273. line-height: 32px;
  274. flex: 1;
  275. `;
  276. const ChartLabel = styled('div')`
  277. background-color: ${p => p.theme.purple100};
  278. border-radius: ${p => p.theme.borderRadius};
  279. text-align: center;
  280. min-width: 32px;
  281. color: ${p => p.theme.purple400};
  282. white-space: nowrap;
  283. font-weight: ${p => p.theme.fontWeightBold};
  284. align-content: center;
  285. margin-right: ${space(1)};
  286. `;