pageLayout.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import {useCallback, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import {isString} from '@sentry/utils';
  4. import type {Location} from 'history';
  5. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  6. import Feature from 'sentry/components/acl/feature';
  7. import {Alert} from 'sentry/components/alert';
  8. import {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  9. import * as Layout from 'sentry/components/layouts/thirds';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  12. import PickProjectToContinue from 'sentry/components/pickProjectToContinue';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {Tabs} from 'sentry/components/tabs';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {Organization} from 'sentry/types/organization';
  18. import type {Project} from 'sentry/types/project';
  19. import {defined} from 'sentry/utils';
  20. import {trackAnalytics} from 'sentry/utils/analytics';
  21. import {browserHistory} from 'sentry/utils/browserHistory';
  22. import DiscoverQuery from 'sentry/utils/discover/discoverQuery';
  23. import type EventView from 'sentry/utils/discover/eventView';
  24. import {
  25. MetricsCardinalityProvider,
  26. useMetricsCardinalityContext,
  27. } from 'sentry/utils/performance/contexts/metricsCardinality';
  28. import {PerformanceEventViewProvider} from 'sentry/utils/performance/contexts/performanceEventViewContext';
  29. import {decodeScalar} from 'sentry/utils/queryString';
  30. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  31. import useRouter from 'sentry/utils/useRouter';
  32. import {useDomainViewFilters} from 'sentry/views/insights/pages/useFilters';
  33. import {aggregateWaterfallRouteWithQuery} from 'sentry/views/performance/transactionSummary/aggregateSpanWaterfall/utils';
  34. import {
  35. getPerformanceBaseUrl,
  36. getSelectedProjectPlatforms,
  37. getTransactionName,
  38. } from '../utils';
  39. import {eventsRouteWithQuery} from './transactionEvents/utils';
  40. import {profilesRouteWithQuery} from './transactionProfiles/utils';
  41. import {replaysRouteWithQuery} from './transactionReplays/utils';
  42. import {spansRouteWithQuery} from './transactionSpans/utils';
  43. import {tagsRouteWithQuery} from './transactionTags/utils';
  44. import {vitalsRouteWithQuery} from './transactionVitals/utils';
  45. import TransactionHeader, {type Props as TransactionHeaderProps} from './header';
  46. import Tab from './tabs';
  47. import type {TransactionThresholdMetric} from './transactionThresholdModal';
  48. import {generateTransactionSummaryRoute, transactionSummaryRouteWithQuery} from './utils';
  49. type TabEvents =
  50. | 'performance_views.vitals.vitals_tab_clicked'
  51. | 'performance_views.tags.tags_tab_clicked'
  52. | 'performance_views.events.events_tab_clicked'
  53. | 'performance_views.spans.spans_tab_clicked';
  54. export const TAB_ANALYTICS: Partial<Record<Tab, TabEvents>> = {
  55. [Tab.WEB_VITALS]: 'performance_views.vitals.vitals_tab_clicked',
  56. [Tab.TAGS]: 'performance_views.tags.tags_tab_clicked',
  57. [Tab.EVENTS]: 'performance_views.events.events_tab_clicked',
  58. [Tab.SPANS]: 'performance_views.spans.spans_tab_clicked',
  59. };
  60. export type ChildProps = {
  61. eventView: EventView;
  62. location: Location;
  63. organization: Organization;
  64. projectId: string;
  65. projects: Project[];
  66. setError: React.Dispatch<React.SetStateAction<string | undefined>>;
  67. transactionName: string;
  68. // These are used to trigger a reload when the threshold/metric changes.
  69. transactionThreshold?: number;
  70. transactionThresholdMetric?: TransactionThresholdMetric;
  71. };
  72. type Props = {
  73. childComponent: (props: ChildProps) => JSX.Element;
  74. generateEventView: (props: {
  75. location: Location;
  76. organization: Organization;
  77. transactionName: string;
  78. }) => EventView;
  79. getDocumentTitle: (name: string) => string;
  80. location: Location;
  81. organization: Organization;
  82. projects: Project[];
  83. tab: Tab;
  84. features?: string[];
  85. fillSpace?: boolean;
  86. };
  87. function PageLayout(props: Props) {
  88. const {
  89. location,
  90. organization,
  91. projects,
  92. tab,
  93. getDocumentTitle,
  94. generateEventView,
  95. childComponent: ChildComponent,
  96. features = [],
  97. } = props;
  98. let projectId: string | undefined;
  99. const filterProjects = location.query.project;
  100. if (isString(filterProjects) && filterProjects !== '-1') {
  101. projectId = filterProjects;
  102. }
  103. const router = useRouter();
  104. const transactionName = getTransactionName(location);
  105. const [error, setError] = useState<string | undefined>();
  106. const metricsCardinality = useMetricsCardinalityContext();
  107. const [transactionThreshold, setTransactionThreshold] = useState<number | undefined>();
  108. const [transactionThresholdMetric, setTransactionThresholdMetric] = useState<
  109. TransactionThresholdMetric | undefined
  110. >();
  111. const {isInDomainView} = useDomainViewFilters();
  112. const getNewRoute = useCallback(
  113. (newTab: Tab) => {
  114. if (!transactionName) {
  115. return {};
  116. }
  117. const routeQuery = {
  118. orgSlug: organization.slug,
  119. transaction: transactionName,
  120. projectID: projectId,
  121. query: location.query,
  122. };
  123. switch (newTab) {
  124. case Tab.TAGS:
  125. return tagsRouteWithQuery(routeQuery);
  126. case Tab.EVENTS:
  127. return eventsRouteWithQuery(routeQuery);
  128. case Tab.SPANS:
  129. return spansRouteWithQuery(routeQuery);
  130. case Tab.REPLAYS:
  131. return replaysRouteWithQuery(routeQuery);
  132. case Tab.PROFILING: {
  133. return profilesRouteWithQuery(routeQuery);
  134. }
  135. case Tab.AGGREGATE_WATERFALL:
  136. return aggregateWaterfallRouteWithQuery(routeQuery);
  137. case Tab.WEB_VITALS:
  138. return vitalsRouteWithQuery({
  139. orgSlug: organization.slug,
  140. transaction: transactionName,
  141. projectID: decodeScalar(location.query.project),
  142. query: location.query,
  143. });
  144. case Tab.TRANSACTION_SUMMARY:
  145. default:
  146. return transactionSummaryRouteWithQuery(routeQuery);
  147. }
  148. },
  149. [location.query, organization.slug, projectId, transactionName]
  150. );
  151. const onTabChange = useCallback(
  152. (newTab: Tab) => {
  153. // Prevent infinite rerenders
  154. if (newTab === tab) {
  155. return;
  156. }
  157. const analyticsKey = TAB_ANALYTICS[newTab];
  158. if (analyticsKey) {
  159. trackAnalytics(analyticsKey, {
  160. organization,
  161. project_platforms: getSelectedProjectPlatforms(location, projects),
  162. });
  163. }
  164. browserHistory.push(normalizeUrl(getNewRoute(newTab)));
  165. },
  166. [getNewRoute, tab, organization, location, projects]
  167. );
  168. if (!defined(transactionName)) {
  169. redirectToPerformanceHomepage(organization, location);
  170. return null;
  171. }
  172. const eventView = generateEventView({location, transactionName, organization});
  173. if (!defined(projectId)) {
  174. // Using a discover query to get the projects associated
  175. // with a transaction name
  176. const nextView = eventView.clone();
  177. nextView.query = `transaction:"${transactionName}"`;
  178. nextView.fields = [
  179. {
  180. field: 'project',
  181. width: COL_WIDTH_UNDEFINED,
  182. },
  183. {
  184. field: 'count()',
  185. width: COL_WIDTH_UNDEFINED,
  186. },
  187. ];
  188. return (
  189. <DiscoverQuery
  190. eventView={nextView}
  191. location={location}
  192. orgSlug={organization.slug}
  193. queryExtras={{project: filterProjects ? filterProjects : undefined}}
  194. referrer="api.performance.transaction-summary"
  195. >
  196. {({isLoading, tableData, error: discoverQueryError}) => {
  197. if (discoverQueryError) {
  198. addErrorMessage(t('Unable to get projects associated with transaction'));
  199. redirectToPerformanceHomepage(organization, location);
  200. return null;
  201. }
  202. if (isLoading) {
  203. return <LoadingIndicator />;
  204. }
  205. const selectableProjects = tableData?.data
  206. .map(row => projects.find(project => project.slug === row.project))
  207. .filter((p): p is Project => p !== undefined);
  208. return (
  209. selectableProjects && (
  210. <PickProjectToContinue
  211. data-test-id="transaction-sumamry-project-picker-modal"
  212. projects={selectableProjects}
  213. router={router}
  214. nextPath={{
  215. pathname: generateTransactionSummaryRoute({orgSlug: organization.slug}),
  216. query: {
  217. project: projectId,
  218. transaction: transactionName,
  219. statsPeriod: eventView.statsPeriod,
  220. referrer: 'performance-transaction-summary',
  221. ...location.query,
  222. },
  223. }}
  224. noProjectRedirectPath="/performance/"
  225. allowAllProjectsSelection
  226. />
  227. )
  228. );
  229. }}
  230. </DiscoverQuery>
  231. );
  232. }
  233. const project = projects.find(p => p.id === projectId);
  234. let hasWebVitals: TransactionHeaderProps['hasWebVitals'] =
  235. tab === Tab.WEB_VITALS ? 'yes' : 'maybe';
  236. if (isInDomainView) {
  237. hasWebVitals = 'no';
  238. }
  239. return (
  240. <SentryDocumentTitle
  241. title={getDocumentTitle(transactionName)}
  242. orgSlug={organization.slug}
  243. projectSlug={project?.slug}
  244. >
  245. <Feature
  246. features={['performance-view', ...features]}
  247. organization={organization}
  248. renderDisabled={NoAccess}
  249. >
  250. <MetricsCardinalityProvider location={location} organization={organization}>
  251. <PerformanceEventViewProvider value={{eventView}}>
  252. <PageFiltersContainer
  253. shouldForceProject={defined(project)}
  254. forceProject={project}
  255. specificProjectSlugs={defined(project) ? [project.slug] : []}
  256. >
  257. <Tabs value={tab} onChange={onTabChange}>
  258. <Layout.Page>
  259. <TransactionHeader
  260. eventView={eventView}
  261. location={location}
  262. organization={organization}
  263. projects={projects}
  264. projectId={projectId}
  265. transactionName={transactionName}
  266. currentTab={tab}
  267. hasWebVitals={hasWebVitals}
  268. onChangeThreshold={(threshold, metric) => {
  269. setTransactionThreshold(threshold);
  270. setTransactionThresholdMetric(metric);
  271. }}
  272. metricsCardinality={metricsCardinality}
  273. />
  274. <StyledBody fillSpace={props.fillSpace} hasError={defined(error)}>
  275. {defined(error) && (
  276. <StyledAlert type="error" showIcon>
  277. {error}
  278. </StyledAlert>
  279. )}
  280. <ChildComponent
  281. location={location}
  282. organization={organization}
  283. projects={projects}
  284. eventView={eventView}
  285. projectId={projectId}
  286. transactionName={transactionName}
  287. setError={setError}
  288. transactionThreshold={transactionThreshold}
  289. transactionThresholdMetric={transactionThresholdMetric}
  290. />
  291. </StyledBody>
  292. </Layout.Page>
  293. </Tabs>
  294. </PageFiltersContainer>
  295. </PerformanceEventViewProvider>
  296. </MetricsCardinalityProvider>
  297. </Feature>
  298. </SentryDocumentTitle>
  299. );
  300. }
  301. export function NoAccess() {
  302. return <Alert type="warning">{t("You don't have access to this feature")}</Alert>;
  303. }
  304. const StyledAlert = styled(Alert)`
  305. grid-column: 1/3;
  306. margin: 0;
  307. `;
  308. const StyledBody = styled(Layout.Body)<{fillSpace?: boolean; hasError?: boolean}>`
  309. ${p =>
  310. p.fillSpace &&
  311. `
  312. display: flex;
  313. flex-direction: column;
  314. gap: ${space(3)};
  315. @media (min-width: ${p.theme.breakpoints.large}) {
  316. display: flex;
  317. flex-direction: column;
  318. gap: ${space(3)};
  319. }
  320. `}
  321. `;
  322. export function redirectToPerformanceHomepage(
  323. organization: Organization,
  324. location: Location
  325. ) {
  326. // If there is no transaction name, redirect to the Performance landing page
  327. browserHistory.replace(
  328. normalizeUrl({
  329. pathname: getPerformanceBaseUrl(organization.slug),
  330. query: {
  331. ...location.query,
  332. },
  333. })
  334. );
  335. }
  336. export default PageLayout;