index.tsx 11 KB

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