utils.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. import {browserHistory} from 'react-router';
  2. import {Theme} from '@emotion/react';
  3. import {Location} from 'history';
  4. import MarkArea from 'sentry/components/charts/components/markArea';
  5. import MarkLine from 'sentry/components/charts/components/markLine';
  6. import {LineChartSeries} from 'sentry/components/charts/lineChart';
  7. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  8. import {backend, frontend, mobile} from 'sentry/data/platformCategories';
  9. import {t} from 'sentry/locale';
  10. import {
  11. NewQuery,
  12. Organization,
  13. OrganizationSummary,
  14. PageFilters,
  15. Project,
  16. ReleaseProject,
  17. } from 'sentry/types';
  18. import {Series} from 'sentry/types/echarts';
  19. import {trackAnalytics} from 'sentry/utils/analytics';
  20. import {statsPeriodToDays} from 'sentry/utils/dates';
  21. import {tooltipFormatter} from 'sentry/utils/discover/charts';
  22. import EventView, {EventData} from 'sentry/utils/discover/eventView';
  23. import {TRACING_FIELDS} from 'sentry/utils/discover/fields';
  24. import {getDuration} from 'sentry/utils/formatters';
  25. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  26. import {useQuery} from 'sentry/utils/queryClient';
  27. import {decodeScalar} from 'sentry/utils/queryString';
  28. import toArray from 'sentry/utils/toArray';
  29. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  30. import useApi from 'sentry/utils/useApi';
  31. import useOrganization from 'sentry/utils/useOrganization';
  32. import useProjects from 'sentry/utils/useProjects';
  33. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  34. import {
  35. NormalizedTrendsTransaction,
  36. TrendChangeType,
  37. } from 'sentry/views/performance/trends/types';
  38. import {DEFAULT_MAX_DURATION, getSelectedQueryKey} from './trends/utils';
  39. export const QUERY_KEYS = [
  40. 'environment',
  41. 'project',
  42. 'query',
  43. 'start',
  44. 'end',
  45. 'statsPeriod',
  46. ] as const;
  47. export const UNPARAMETERIZED_TRANSACTION = '<< unparameterized >>'; // Represents 'other' transactions with high cardinality names that were dropped on the metrics dataset.
  48. const UNPARAMETRIZED_TRANSACTION = '<< unparametrized >>'; // Old spelling. Can be deleted in the future when all data for this transaction name is gone.
  49. export const EXCLUDE_METRICS_UNPARAM_CONDITIONS = `(!transaction:"${UNPARAMETERIZED_TRANSACTION}" AND !transaction:"${UNPARAMETRIZED_TRANSACTION}")`;
  50. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  51. const DEFAULT_CHART_HEIGHT = 200;
  52. const X_AXIS_MARGIN_OFFSET = 23;
  53. export enum DiscoverQueryPageSource {
  54. PERFORMANCE = 'performance',
  55. DISCOVER = 'discover',
  56. }
  57. export function createUnnamedTransactionsDiscoverTarget(props: {
  58. location: Location;
  59. organization: Organization;
  60. source?: DiscoverQueryPageSource;
  61. }) {
  62. const fields =
  63. props.source === DiscoverQueryPageSource.DISCOVER
  64. ? ['transaction', 'project', 'transaction.source', 'epm()']
  65. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  66. const query: NewQuery = {
  67. id: undefined,
  68. name:
  69. props.source === DiscoverQueryPageSource.DISCOVER
  70. ? t('Unparameterized Transactions')
  71. : t('Performance - Unparameterized Transactions'),
  72. query: 'event.type:transaction transaction.source:"url"',
  73. projects: [],
  74. fields,
  75. version: 2,
  76. };
  77. const discoverEventView = EventView.fromNewQueryWithLocation(
  78. query,
  79. props.location
  80. ).withSorts([{field: 'epm', kind: 'desc'}]);
  81. const target = discoverEventView.getResultsViewUrlTarget(props.organization.slug);
  82. target.query[SHOW_UNPARAM_BANNER] = 'true';
  83. return target;
  84. }
  85. /**
  86. * Performance type can used to determine a default view or which specific field should be used by default on pages
  87. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  88. */
  89. export enum ProjectPerformanceType {
  90. ANY = 'any', // Fallback to transaction duration
  91. FRONTEND = 'frontend',
  92. BACKEND = 'backend',
  93. FRONTEND_OTHER = 'frontend_other',
  94. MOBILE = 'mobile',
  95. }
  96. // The native SDK is equally used on clients and end-devices as on
  97. // backend, the default view should be "All Transactions".
  98. const FRONTEND_PLATFORMS: string[] = frontend.filter(
  99. platform =>
  100. // Next, Remix and Sveltekit have both, frontend and backend transactions.
  101. !['javascript-nextjs', 'javascript-remix', 'javascript-sveltekit'].includes(platform)
  102. );
  103. const BACKEND_PLATFORMS: string[] = backend.filter(platform => platform !== 'native');
  104. const MOBILE_PLATFORMS: string[] = [...mobile];
  105. export function platformToPerformanceType(
  106. projects: (Project | ReleaseProject)[],
  107. projectIds: readonly number[]
  108. ) {
  109. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  110. return ProjectPerformanceType.ANY;
  111. }
  112. const selectedProjects = projects.filter(p =>
  113. projectIds.includes(parseInt(`${p.id}`, 10))
  114. );
  115. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  116. return ProjectPerformanceType.ANY;
  117. }
  118. const projectPerformanceTypes = new Set<ProjectPerformanceType>();
  119. selectedProjects.forEach(project => {
  120. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  121. projectPerformanceTypes.add(ProjectPerformanceType.FRONTEND);
  122. }
  123. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  124. projectPerformanceTypes.add(ProjectPerformanceType.BACKEND);
  125. }
  126. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  127. projectPerformanceTypes.add(ProjectPerformanceType.MOBILE);
  128. }
  129. });
  130. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  131. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  132. return ProjectPerformanceType.ANY;
  133. }
  134. const [PlatformKey] = projectPerformanceTypes;
  135. return PlatformKey;
  136. }
  137. /**
  138. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  139. */
  140. export function platformAndConditionsToPerformanceType(
  141. projects: Project[],
  142. eventView: EventView
  143. ) {
  144. const performanceType = platformToPerformanceType(projects, eventView.project);
  145. if (performanceType === ProjectPerformanceType.FRONTEND) {
  146. const conditions = new MutableSearch(eventView.query);
  147. const ops = conditions.getFilterValues('!transaction.op');
  148. if (ops.some(op => op === 'pageload')) {
  149. return ProjectPerformanceType.FRONTEND_OTHER;
  150. }
  151. }
  152. return performanceType;
  153. }
  154. /**
  155. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  156. */
  157. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  158. return (
  159. platformAndConditionsToPerformanceType(projects, eventView) ===
  160. ProjectPerformanceType.FRONTEND
  161. );
  162. }
  163. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  164. return (
  165. platformAndConditionsToPerformanceType(projects, eventView) ===
  166. ProjectPerformanceType.FRONTEND ||
  167. platformAndConditionsToPerformanceType(projects, eventView) ===
  168. ProjectPerformanceType.FRONTEND_OTHER
  169. );
  170. }
  171. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  172. return `/organizations/${organization.slug}/performance/`;
  173. }
  174. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  175. return `/organizations/${organization.slug}/performance/trends/`;
  176. }
  177. export function getTransactionSearchQuery(location: Location, query: string = '') {
  178. return decodeScalar(location.query.query, query).trim();
  179. }
  180. export function handleTrendsClick({
  181. location,
  182. organization,
  183. projectPlatforms,
  184. }: {
  185. location: Location;
  186. organization: Organization;
  187. projectPlatforms: string;
  188. }) {
  189. trackAnalytics('performance_views.change_view', {
  190. organization,
  191. view_name: 'TRENDS',
  192. project_platforms: projectPlatforms,
  193. });
  194. const target = trendsTargetRoute({location, organization});
  195. browserHistory.push(normalizeUrl(target));
  196. }
  197. export function trendsTargetRoute({
  198. location,
  199. organization,
  200. initialConditions,
  201. additionalQuery,
  202. }: {
  203. location: Location;
  204. organization: Organization;
  205. additionalQuery?: {[x: string]: string};
  206. initialConditions?: MutableSearch;
  207. }) {
  208. const newQuery = {
  209. ...location.query,
  210. ...additionalQuery,
  211. };
  212. const query = decodeScalar(location.query.query, '');
  213. const conditions = new MutableSearch(query);
  214. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  215. // Trends on metrics don't need these conditions
  216. if (!organization.features.includes('performance-new-trends')) {
  217. // No need to carry over tpm filters to transaction summary
  218. if (conditions.hasFilter('tpm()')) {
  219. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  220. } else {
  221. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  222. }
  223. if (conditions.hasFilter('transaction.duration')) {
  224. modifiedConditions.setFilterValues(
  225. 'transaction.duration',
  226. conditions.getFilterValues('transaction.duration')
  227. );
  228. } else {
  229. modifiedConditions.setFilterValues('transaction.duration', [
  230. '>0',
  231. `<${DEFAULT_MAX_DURATION}`,
  232. ]);
  233. }
  234. }
  235. newQuery.query = modifiedConditions.formatString();
  236. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  237. }
  238. export function removeTracingKeysFromSearch(
  239. currentFilter: MutableSearch,
  240. options: {excludeTagKeys: Set<string>} = {
  241. excludeTagKeys: new Set([
  242. // event type can be "transaction" but we're searching for issues
  243. 'event.type',
  244. // the project is already determined by the transaction,
  245. // and issue search does not support the project filter
  246. 'project',
  247. ]),
  248. }
  249. ) {
  250. currentFilter.getFilterKeys().forEach(tagKey => {
  251. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  252. // Remove aggregates and transaction event fields
  253. if (
  254. // aggregates
  255. searchKey.match(/\w+\(.*\)/) ||
  256. // transaction event fields
  257. TRACING_FIELDS.includes(searchKey) ||
  258. // tags that we don't want to pass to pass to issue search
  259. options.excludeTagKeys.has(searchKey)
  260. ) {
  261. currentFilter.removeFilter(tagKey);
  262. }
  263. });
  264. return currentFilter;
  265. }
  266. export function addRoutePerformanceContext(selection: PageFilters) {
  267. const transaction = getCurrentSentryReactTransaction();
  268. const days = statsPeriodToDays(
  269. selection.datetime.period,
  270. selection.datetime.start,
  271. selection.datetime.end
  272. );
  273. const oneDay = 86400;
  274. const seconds = Math.floor(days * oneDay);
  275. transaction?.setTag('query.period', seconds.toString());
  276. let groupedPeriod = '>30d';
  277. if (seconds <= oneDay) {
  278. groupedPeriod = '<=1d';
  279. } else if (seconds <= oneDay * 7) {
  280. groupedPeriod = '<=7d';
  281. } else if (seconds <= oneDay * 14) {
  282. groupedPeriod = '<=14d';
  283. } else if (seconds <= oneDay * 30) {
  284. groupedPeriod = '<=30d';
  285. }
  286. transaction?.setTag('query.period.grouped', groupedPeriod);
  287. }
  288. export function getTransactionName(location: Location): string | undefined {
  289. const {transaction} = location.query;
  290. return decodeScalar(transaction);
  291. }
  292. export function getPerformanceDuration(milliseconds: number) {
  293. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  294. }
  295. export function getIsMultiProject(projects: readonly number[] | number[]) {
  296. if (!projects.length) {
  297. return true; // My projects
  298. }
  299. if (projects.length === 1 && projects[0] === ALL_ACCESS_PROJECTS) {
  300. return true; // All projects
  301. }
  302. return false;
  303. }
  304. export function getSelectedProjectPlatformsArray(
  305. location: Location,
  306. projects: Project[]
  307. ) {
  308. const projectQuery = location.query.project;
  309. const selectedProjectIdSet = new Set(toArray(projectQuery));
  310. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  311. if (selectedProjectIdSet.has(project.id)) {
  312. acc.push(project.platform ?? 'undefined');
  313. }
  314. return acc;
  315. }, []);
  316. return selectedProjectPlatforms;
  317. }
  318. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  319. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  320. return selectedProjectPlatforms.join(', ');
  321. }
  322. export function getProject(
  323. eventData: EventData,
  324. projects: Project[]
  325. ): Project | undefined {
  326. const projectSlug = (eventData?.project as string) || undefined;
  327. if (typeof projectSlug === undefined) {
  328. return undefined;
  329. }
  330. return projects.find(currentProject => currentProject.slug === projectSlug);
  331. }
  332. export function getProjectID(
  333. eventData: EventData,
  334. projects: Project[]
  335. ): string | undefined {
  336. return getProject(eventData, projects)?.id;
  337. }
  338. export function transformTransaction(
  339. transaction: NormalizedTrendsTransaction
  340. ): NormalizedTrendsTransaction {
  341. if (transaction && transaction.breakpoint) {
  342. return {
  343. ...transaction,
  344. breakpoint: transaction.breakpoint * 1000,
  345. };
  346. }
  347. return transaction;
  348. }
  349. export function getIntervalLine(
  350. theme: Theme,
  351. series: Series[],
  352. intervalRatio: number,
  353. label: boolean,
  354. transaction?: NormalizedTrendsTransaction,
  355. useRegressionFormat?: boolean
  356. ): LineChartSeries[] {
  357. if (!transaction || !series.length || !series[0].data || !series[0].data.length) {
  358. return [];
  359. }
  360. const transformedTransaction = transformTransaction(transaction);
  361. const seriesStart = parseInt(series[0].data[0].name as string, 10);
  362. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 10);
  363. if (seriesEnd < seriesStart) {
  364. return [];
  365. }
  366. const periodLine: LineChartSeries = {
  367. data: [],
  368. color: theme.textColor,
  369. markLine: {
  370. data: [],
  371. label: {},
  372. lineStyle: {
  373. color: theme.textColor,
  374. type: 'dashed',
  375. width: label ? 1 : 2,
  376. },
  377. symbol: ['none', 'none'],
  378. tooltip: {
  379. show: false,
  380. },
  381. },
  382. seriesName: 'Baseline',
  383. };
  384. const periodLineLabel = {
  385. fontSize: 11,
  386. show: label,
  387. color: theme.textColor,
  388. silent: label,
  389. };
  390. const previousPeriod = {
  391. ...periodLine,
  392. markLine: {...periodLine.markLine},
  393. seriesName: 'Baseline',
  394. };
  395. const currentPeriod = {
  396. ...periodLine,
  397. markLine: {...periodLine.markLine},
  398. seriesName: 'Baseline',
  399. };
  400. const periodDividingLine = {
  401. ...periodLine,
  402. markLine: {...periodLine.markLine},
  403. seriesName: 'Baseline',
  404. };
  405. const seriesDiff = seriesEnd - seriesStart;
  406. const seriesLine = seriesDiff * intervalRatio + seriesStart;
  407. const {breakpoint} = transformedTransaction;
  408. const divider = breakpoint || seriesLine;
  409. previousPeriod.markLine.data = [
  410. [
  411. {value: 'Past', coord: [seriesStart, transformedTransaction.aggregate_range_1]},
  412. {coord: [divider, transformedTransaction.aggregate_range_1]},
  413. ],
  414. ];
  415. previousPeriod.markLine.tooltip = {
  416. formatter: () => {
  417. return [
  418. '<div class="tooltip-series tooltip-series-solo">',
  419. '<div>',
  420. `<span class="tooltip-label"><strong>${t('Past Baseline')}</strong></span>`,
  421. // p50() coerces the axis to be time based
  422. tooltipFormatter(transformedTransaction.aggregate_range_1, 'duration'),
  423. '</div>',
  424. '</div>',
  425. '<div class="tooltip-arrow"></div>',
  426. ].join('');
  427. },
  428. };
  429. currentPeriod.markLine.data = [
  430. [
  431. {value: 'Present', coord: [divider, transformedTransaction.aggregate_range_2]},
  432. {coord: [seriesEnd, transformedTransaction.aggregate_range_2]},
  433. ],
  434. ];
  435. currentPeriod.markLine.tooltip = {
  436. formatter: () => {
  437. return [
  438. '<div class="tooltip-series tooltip-series-solo">',
  439. '<div>',
  440. `<span class="tooltip-label"><strong>${t('Present Baseline')}</strong></span>`,
  441. // p50() coerces the axis to be time based
  442. tooltipFormatter(transformedTransaction.aggregate_range_2, 'duration'),
  443. '</div>',
  444. '</div>',
  445. '<div class="tooltip-arrow"></div>',
  446. ].join('');
  447. },
  448. };
  449. periodDividingLine.markLine = {
  450. data: [
  451. {
  452. xAxis: divider,
  453. },
  454. ],
  455. label: {show: false},
  456. lineStyle: {
  457. color: theme.textColor,
  458. type: 'solid',
  459. width: 2,
  460. },
  461. symbol: ['none', 'none'],
  462. tooltip: {
  463. show: false,
  464. },
  465. silent: true,
  466. };
  467. previousPeriod.markLine.label = {
  468. ...periodLineLabel,
  469. formatter: 'Past',
  470. position: 'insideStartBottom',
  471. };
  472. currentPeriod.markLine.label = {
  473. ...periodLineLabel,
  474. formatter: 'Present',
  475. position: 'insideEndBottom',
  476. };
  477. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  478. // Apply new styles for statistical detector regression issue
  479. if (useRegressionFormat) {
  480. previousPeriod.markLine.label = {
  481. ...periodLineLabel,
  482. formatter: `Baseline ${getPerformanceDuration(
  483. transformedTransaction.aggregate_range_1
  484. )}`,
  485. position: 'insideStartBottom',
  486. };
  487. periodDividingLine.markLine.lineStyle = {
  488. ...periodDividingLine.markLine.lineStyle,
  489. color: theme.red300,
  490. };
  491. currentPeriod.markLine.lineStyle = {
  492. ...currentPeriod.markLine.lineStyle,
  493. color: theme.red300,
  494. };
  495. currentPeriod.markLine.label = {
  496. ...periodLineLabel,
  497. formatter: `Regressed ${getPerformanceDuration(
  498. transformedTransaction.aggregate_range_2
  499. )}`,
  500. position: 'insideEndBottom',
  501. color: theme.red300,
  502. };
  503. additionalLineSeries.push({
  504. seriesName: 'Regression Area',
  505. markLine: {},
  506. markArea: MarkArea({
  507. silent: true,
  508. itemStyle: {
  509. color: theme.red300,
  510. opacity: 0.2,
  511. },
  512. data: [
  513. [
  514. {
  515. xAxis: divider,
  516. },
  517. {xAxis: seriesEnd},
  518. ],
  519. ],
  520. }),
  521. data: [],
  522. });
  523. additionalLineSeries.push({
  524. seriesName: 'Baseline Axis Line',
  525. type: 'line',
  526. markLine:
  527. MarkLine({
  528. silent: true,
  529. label: {
  530. show: false,
  531. },
  532. lineStyle: {color: theme.green400, type: 'solid', width: 4},
  533. data: [
  534. // The line needs to be hard-coded to a pixel coordinate because
  535. // the lowest y-value is dynamic and 'min' doesn't work here
  536. [
  537. {xAxis: 'min', y: DEFAULT_CHART_HEIGHT - X_AXIS_MARGIN_OFFSET},
  538. {xAxis: breakpoint, y: DEFAULT_CHART_HEIGHT - X_AXIS_MARGIN_OFFSET},
  539. ],
  540. ],
  541. }) ?? {},
  542. data: [],
  543. });
  544. additionalLineSeries.push({
  545. seriesName: 'Regression Axis Line',
  546. type: 'line',
  547. markLine:
  548. MarkLine({
  549. silent: true,
  550. label: {
  551. show: false,
  552. },
  553. lineStyle: {color: theme.red300, type: 'solid', width: 4},
  554. data: [
  555. // The line needs to be hard-coded to a pixel coordinate because
  556. // the lowest y-value is dynamic and 'min' doesn't work here
  557. [
  558. {xAxis: breakpoint, y: DEFAULT_CHART_HEIGHT - X_AXIS_MARGIN_OFFSET},
  559. {xAxis: 'max', y: DEFAULT_CHART_HEIGHT - X_AXIS_MARGIN_OFFSET},
  560. ],
  561. ],
  562. }) ?? {},
  563. data: [],
  564. });
  565. }
  566. return additionalLineSeries;
  567. }
  568. export function getSelectedTransaction(
  569. location: Location,
  570. trendChangeType: TrendChangeType,
  571. transactions?: NormalizedTrendsTransaction[]
  572. ): NormalizedTrendsTransaction | undefined {
  573. const queryKey = getSelectedQueryKey(trendChangeType);
  574. const selectedTransactionName = decodeScalar(location.query[queryKey]);
  575. if (!transactions) {
  576. return undefined;
  577. }
  578. const selectedTransaction = transactions.find(
  579. transaction =>
  580. `${transaction.transaction}-${transaction.project}` === selectedTransactionName
  581. );
  582. if (selectedTransaction) {
  583. return selectedTransaction;
  584. }
  585. return transactions.length > 0 ? transactions[0] : undefined;
  586. }
  587. export function usePerformanceGeneralProjectSettings(projectId?: number) {
  588. const api = useApi();
  589. const organization = useOrganization();
  590. const {projects} = useProjects();
  591. const stringProjectId = projectId?.toString();
  592. const project = projects.find(p => p.id === stringProjectId);
  593. return useQuery(['settings', 'general', projectId], {
  594. enabled: Boolean(project),
  595. queryFn: () =>
  596. api.requestPromise(
  597. `/api/0/projects/${organization.slug}/${project?.slug}/performance/configure/`
  598. ) as Promise<{enable_images: boolean}>,
  599. });
  600. }