utils.tsx 20 KB

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