results.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import {Component} from 'react';
  2. import {browserHistory, InjectedRouter} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {Location} from 'history';
  6. import isEqual from 'lodash/isEqual';
  7. import omit from 'lodash/omit';
  8. import {updateSavedQueryVisit} from 'sentry/actionCreators/discoverSavedQueries';
  9. import {fetchTotalCount} from 'sentry/actionCreators/events';
  10. import {fetchProjectsCount} from 'sentry/actionCreators/projects';
  11. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  12. import {Client} from 'sentry/api';
  13. import Alert from 'sentry/components/alert';
  14. import AsyncComponent from 'sentry/components/asyncComponent';
  15. import Confirm from 'sentry/components/confirm';
  16. import DatePageFilter from 'sentry/components/datePageFilter';
  17. import EnvironmentPageFilter from 'sentry/components/environmentPageFilter';
  18. import SearchBar from 'sentry/components/events/searchBar';
  19. import * as Layout from 'sentry/components/layouts/thirds';
  20. import ExternalLink from 'sentry/components/links/externalLink';
  21. import LoadingIndicator from 'sentry/components/loadingIndicator';
  22. import NoProjectMessage from 'sentry/components/noProjectMessage';
  23. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  24. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  25. import {
  26. normalizeDateTimeParams,
  27. normalizeDateTimeString,
  28. } from 'sentry/components/organizations/pageFilters/parse';
  29. import {CursorHandler} from 'sentry/components/pagination';
  30. import ProjectPageFilter from 'sentry/components/projectPageFilter';
  31. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  32. import {MAX_QUERY_LENGTH} from 'sentry/constants';
  33. import {t, tct} from 'sentry/locale';
  34. import {PageContent} from 'sentry/styles/organization';
  35. import space from 'sentry/styles/space';
  36. import {Organization, PageFilters, SavedQuery} from 'sentry/types';
  37. import {defined, generateQueryWithTag} from 'sentry/utils';
  38. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  39. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  40. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  41. import EventView, {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  42. import {formatTagKey, generateAggregateFields} from 'sentry/utils/discover/fields';
  43. import {
  44. DisplayModes,
  45. MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES,
  46. } from 'sentry/utils/discover/types';
  47. import localStorage from 'sentry/utils/localStorage';
  48. import marked from 'sentry/utils/marked';
  49. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  50. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  51. import withApi from 'sentry/utils/withApi';
  52. import withOrganization from 'sentry/utils/withOrganization';
  53. import withPageFilters from 'sentry/utils/withPageFilters';
  54. import {addRoutePerformanceContext} from '../performance/utils';
  55. import {DEFAULT_EVENT_VIEW} from './data';
  56. import {MetricsBaselineContainer} from './metricsBaselineContainer';
  57. import ResultsHeader from './resultsHeader';
  58. import Table from './table';
  59. import Tags from './tags';
  60. import {generateTitle} from './utils';
  61. type Props = {
  62. api: Client;
  63. loading: boolean;
  64. location: Location;
  65. organization: Organization;
  66. router: InjectedRouter;
  67. selection: PageFilters;
  68. setSavedQuery: (savedQuery?: SavedQuery) => void;
  69. isHomepage?: boolean;
  70. savedQuery?: SavedQuery;
  71. };
  72. type State = {
  73. confirmedQuery: boolean;
  74. error: string;
  75. errorCode: number;
  76. eventView: EventView;
  77. needConfirmation: boolean;
  78. showTags: boolean;
  79. tips: string[];
  80. totalValues: null | number;
  81. savedQuery?: SavedQuery;
  82. showMetricsAlert?: boolean;
  83. showUnparameterizedBanner?: boolean;
  84. };
  85. const SHOW_TAGS_STORAGE_KEY = 'discover2:show-tags';
  86. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  87. function readShowTagsState() {
  88. const value = localStorage.getItem(SHOW_TAGS_STORAGE_KEY);
  89. return value === '1';
  90. }
  91. function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQuery) {
  92. if (location.query.yAxis) {
  93. return decodeList(location.query.yAxis);
  94. }
  95. if (location.query.yAxis === null) {
  96. return [];
  97. }
  98. return savedQuery?.yAxis && savedQuery?.yAxis.length > 0
  99. ? decodeList(savedQuery?.yAxis)
  100. : [eventView.getYAxis()];
  101. }
  102. export class Results extends Component<Props, State> {
  103. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  104. const eventView = EventView.fromSavedQueryOrLocation(
  105. nextProps.savedQuery,
  106. nextProps.location
  107. );
  108. return {...prevState, eventView, savedQuery: nextProps.savedQuery};
  109. }
  110. state: State = {
  111. eventView: EventView.fromSavedQueryOrLocation(
  112. this.props.savedQuery,
  113. this.props.location
  114. ),
  115. error: '',
  116. errorCode: 200,
  117. totalValues: null,
  118. showTags: readShowTagsState(),
  119. needConfirmation: false,
  120. confirmedQuery: false,
  121. tips: [],
  122. };
  123. componentDidMount() {
  124. const {organization, selection, location, isHomepage} = this.props;
  125. if (location.query.fromMetric) {
  126. this.setState({showMetricsAlert: true});
  127. browserHistory.replace({
  128. ...location,
  129. query: {...location.query, fromMetric: undefined},
  130. });
  131. }
  132. if (location.query[SHOW_UNPARAM_BANNER]) {
  133. this.setState({showUnparameterizedBanner: true});
  134. browserHistory.replace({
  135. ...location,
  136. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  137. });
  138. }
  139. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  140. addRoutePerformanceContext(selection);
  141. this.checkEventView();
  142. this.canLoadEvents();
  143. if (!isHomepage && defined(location.query.id)) {
  144. updateSavedQueryVisit(organization.slug, location.query.id);
  145. }
  146. }
  147. componentDidUpdate(prevProps: Props, prevState: State) {
  148. const {api, location, organization, selection} = this.props;
  149. const {eventView, confirmedQuery, savedQuery} = this.state;
  150. this.checkEventView();
  151. const currentQuery = eventView.getEventsAPIPayload(location);
  152. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  153. const yAxisArray = getYAxis(location, eventView, savedQuery);
  154. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  155. if (
  156. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  157. this.hasChartParametersChanged(
  158. prevState.eventView,
  159. eventView,
  160. prevYAxisArray,
  161. yAxisArray
  162. )
  163. ) {
  164. api.clear();
  165. this.canLoadEvents();
  166. }
  167. if (
  168. !isEqual(prevProps.selection.datetime, selection.datetime) ||
  169. !isEqual(prevProps.selection.projects, selection.projects)
  170. ) {
  171. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  172. addRoutePerformanceContext(selection);
  173. }
  174. if (prevState.confirmedQuery !== confirmedQuery) {
  175. this.fetchTotalCount();
  176. }
  177. }
  178. tagsApi: Client = new Client();
  179. hasChartParametersChanged(
  180. prevEventView: EventView,
  181. eventView: EventView,
  182. prevYAxisArray: string[],
  183. yAxisArray: string[]
  184. ) {
  185. if (!isEqual(prevYAxisArray, yAxisArray)) {
  186. return true;
  187. }
  188. const prevDisplay = prevEventView.getDisplayMode();
  189. const display = eventView.getDisplayMode();
  190. return prevDisplay !== display;
  191. }
  192. canLoadEvents = async () => {
  193. const {api, location, organization} = this.props;
  194. const {eventView} = this.state;
  195. let needConfirmation = false;
  196. let confirmedQuery = true;
  197. const currentQuery = eventView.getEventsAPIPayload(location);
  198. const duration = eventView.getDays();
  199. if (duration > 30 && currentQuery.project) {
  200. let projectLength = currentQuery.project.length;
  201. if (
  202. projectLength === 0 ||
  203. (projectLength === 1 && currentQuery.project[0] === '-1')
  204. ) {
  205. try {
  206. const results = await fetchProjectsCount(api, organization.slug);
  207. if (projectLength === 0) {
  208. projectLength = results.myProjects;
  209. } else {
  210. projectLength = results.allProjects;
  211. }
  212. } catch (err) {
  213. // do nothing, so the length is 0 or 1 and the query is assumed safe
  214. }
  215. }
  216. if (projectLength > 10) {
  217. needConfirmation = true;
  218. confirmedQuery = false;
  219. }
  220. }
  221. // Once confirmed, a change of project or datetime will happen before this can set it to false,
  222. // this means a query will still happen even if the new conditions need confirmation
  223. // using a state callback to return this to false
  224. this.setState({needConfirmation, confirmedQuery}, () => {
  225. this.setState({confirmedQuery: false});
  226. });
  227. if (needConfirmation) {
  228. this.openConfirm();
  229. }
  230. };
  231. openConfirm = () => {};
  232. setOpenFunction = ({open}) => {
  233. this.openConfirm = open;
  234. return null;
  235. };
  236. handleConfirmed = () => {
  237. this.setState({needConfirmation: false, confirmedQuery: true}, () => {
  238. this.setState({confirmedQuery: false});
  239. });
  240. };
  241. handleCancelled = () => {
  242. this.setState({needConfirmation: false, confirmedQuery: false});
  243. };
  244. async fetchTotalCount() {
  245. const {api, organization, location} = this.props;
  246. const {eventView, confirmedQuery} = this.state;
  247. if (confirmedQuery === false || !eventView.isValid()) {
  248. return;
  249. }
  250. try {
  251. const totals = await fetchTotalCount(
  252. api,
  253. organization.slug,
  254. eventView.getEventsAPIPayload(location)
  255. );
  256. this.setState({totalValues: totals});
  257. } catch (err) {
  258. Sentry.captureException(err);
  259. }
  260. }
  261. checkEventView() {
  262. const {eventView} = this.state;
  263. const {loading} = this.props;
  264. if (eventView.isValid() || loading) {
  265. return;
  266. }
  267. // If the view is not valid, redirect to a known valid state.
  268. const {location, organization, selection, isHomepage, savedQuery} = this.props;
  269. const isReplayEnabled = organization.features.includes('session-replay-ui');
  270. const defaultEventView = Object.assign({}, DEFAULT_EVENT_VIEW, {
  271. fields: isReplayEnabled
  272. ? DEFAULT_EVENT_VIEW.fields.concat(['replayId'])
  273. : DEFAULT_EVENT_VIEW.fields,
  274. });
  275. const query = isHomepage && savedQuery ? omit(savedQuery, 'id') : defaultEventView;
  276. const nextEventView = EventView.fromNewQueryWithLocation(query, location);
  277. if (nextEventView.project.length === 0 && selection.projects) {
  278. nextEventView.project = selection.projects;
  279. }
  280. if (selection.datetime) {
  281. const {period, utc, start, end} = selection.datetime;
  282. nextEventView.statsPeriod = period ?? undefined;
  283. nextEventView.utc = utc?.toString();
  284. nextEventView.start = normalizeDateTimeString(start);
  285. nextEventView.end = normalizeDateTimeString(end);
  286. }
  287. if (location.query?.query) {
  288. nextEventView.query = decodeScalar(location.query.query, '');
  289. }
  290. if (isHomepage && !this.state.savedQuery) {
  291. this.setState({savedQuery, eventView: nextEventView});
  292. }
  293. browserHistory.replace(
  294. nextEventView.getResultsViewUrlTarget(organization.slug, isHomepage)
  295. );
  296. }
  297. handleCursor: CursorHandler = (cursor, path, query, _direction) => {
  298. const {router} = this.props;
  299. router.push({
  300. pathname: path,
  301. query: {...query, cursor},
  302. });
  303. // Treat pagination like the user already confirmed the query
  304. if (!this.state.needConfirmation) {
  305. this.handleConfirmed();
  306. }
  307. };
  308. handleChangeShowTags = () => {
  309. const {organization} = this.props;
  310. trackAnalyticsEvent({
  311. eventKey: 'discover_v2.results.toggle_tag_facets',
  312. eventName: 'Discoverv2: Toggle Tag Facets',
  313. organization_id: parseInt(organization.id, 10),
  314. });
  315. this.setState(state => {
  316. const newValue = !state.showTags;
  317. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  318. return {...state, showTags: newValue};
  319. });
  320. };
  321. handleSearch = (query: string) => {
  322. const {router, location} = this.props;
  323. const queryParams = normalizeDateTimeParams({
  324. ...(location.query || {}),
  325. query,
  326. });
  327. // do not propagate pagination when making a new search
  328. const searchQueryParams = omit(queryParams, 'cursor');
  329. router.push({
  330. pathname: location.pathname,
  331. query: searchQueryParams,
  332. });
  333. };
  334. handleYAxisChange = (value: string[]) => {
  335. const {router, location} = this.props;
  336. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  337. location.query.display as DisplayModes
  338. );
  339. const newQuery = {
  340. ...location.query,
  341. yAxis: value.length > 0 ? value : [null],
  342. // If using Multi Y-axis and not in a supported display, change to the default display mode
  343. display:
  344. value.length > 1 && !isDisplayMultiYAxisSupported
  345. ? location.query.display === DisplayModes.DAILYTOP5
  346. ? DisplayModes.DAILY
  347. : DisplayModes.DEFAULT
  348. : location.query.display,
  349. };
  350. router.push({
  351. pathname: location.pathname,
  352. query: newQuery,
  353. });
  354. // Treat axis changing like the user already confirmed the query
  355. if (!this.state.needConfirmation) {
  356. this.handleConfirmed();
  357. }
  358. trackAnalyticsEvent({
  359. eventKey: 'discover_v2.y_axis_change',
  360. eventName: "Discoverv2: Change chart's y axis",
  361. organization_id: parseInt(this.props.organization.id, 10),
  362. y_axis_value: value,
  363. });
  364. };
  365. handleDisplayChange = (value: string) => {
  366. const {router, location} = this.props;
  367. const newQuery = {
  368. ...location.query,
  369. display: value,
  370. };
  371. router.push({
  372. pathname: location.pathname,
  373. query: newQuery,
  374. });
  375. // Treat display changing like the user already confirmed the query
  376. if (!this.state.needConfirmation) {
  377. this.handleConfirmed();
  378. }
  379. };
  380. handleIntervalChange = (value: string | undefined) => {
  381. const {router, location} = this.props;
  382. const newQuery = {
  383. ...location.query,
  384. interval: value,
  385. };
  386. if (location.query.interval !== value) {
  387. router.push({
  388. pathname: location.pathname,
  389. query: newQuery,
  390. });
  391. // Treat display changing like the user already confirmed the query
  392. if (!this.state.needConfirmation) {
  393. this.handleConfirmed();
  394. }
  395. }
  396. };
  397. handleTopEventsChange = (value: string) => {
  398. const {router, location} = this.props;
  399. const newQuery = {
  400. ...location.query,
  401. topEvents: value,
  402. };
  403. router.push({
  404. pathname: location.pathname,
  405. query: newQuery,
  406. });
  407. // Treat display changing like the user already confirmed the query
  408. if (!this.state.needConfirmation) {
  409. this.handleConfirmed();
  410. }
  411. };
  412. getDocumentTitle(): string {
  413. const {organization} = this.props;
  414. const {eventView} = this.state;
  415. if (!eventView) {
  416. return '';
  417. }
  418. return generateTitle({eventView, organization});
  419. }
  420. renderTagsTable() {
  421. const {organization, location} = this.props;
  422. const {eventView, totalValues, confirmedQuery} = this.state;
  423. return (
  424. <Layout.Side>
  425. <Tags
  426. generateUrl={this.generateTagUrl}
  427. totalValues={totalValues}
  428. eventView={eventView}
  429. organization={organization}
  430. location={location}
  431. confirmedQuery={confirmedQuery}
  432. />
  433. </Layout.Side>
  434. );
  435. }
  436. generateTagUrl = (key: string, value: string) => {
  437. const {organization, isHomepage} = this.props;
  438. const {eventView} = this.state;
  439. const url = eventView.getResultsViewUrlTarget(organization.slug, isHomepage);
  440. url.query = generateQueryWithTag(url.query, {
  441. key: formatTagKey(key),
  442. value,
  443. });
  444. return url;
  445. };
  446. renderError(error: string) {
  447. if (!error) {
  448. return null;
  449. }
  450. return (
  451. <Alert type="error" showIcon>
  452. {error}
  453. </Alert>
  454. );
  455. }
  456. setError = (error: string, errorCode: number) => {
  457. this.setState({error, errorCode});
  458. };
  459. renderMetricsFallbackBanner() {
  460. const {organization} = this.props;
  461. if (
  462. !organization.features.includes('performance-mep-bannerless-ui') &&
  463. this.state.showMetricsAlert
  464. ) {
  465. return (
  466. <Alert type="info" showIcon>
  467. {t(
  468. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  469. )}
  470. </Alert>
  471. );
  472. }
  473. if (this.state.showUnparameterizedBanner) {
  474. return (
  475. <Alert type="info" showIcon>
  476. {tct(
  477. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  478. {
  479. link: (
  480. <ExternalLink href="https://docs.sentry.io/platforms/javascript/guides/react/configuration/integrations/react-router/#parameterized-transaction-names" />
  481. ),
  482. }
  483. )}
  484. </Alert>
  485. );
  486. }
  487. return null;
  488. }
  489. renderTips() {
  490. const {tips} = this.state;
  491. if (tips) {
  492. return tips.map((tip, index) => (
  493. <Alert type="info" showIcon key={`tip-${index}`}>
  494. <TipContainer dangerouslySetInnerHTML={{__html: marked(tip)}} />
  495. </Alert>
  496. ));
  497. }
  498. return null;
  499. }
  500. render() {
  501. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  502. this.props;
  503. const {
  504. eventView,
  505. error,
  506. errorCode,
  507. totalValues,
  508. showTags,
  509. confirmedQuery,
  510. savedQuery,
  511. } = this.state;
  512. const fields = eventView.hasAggregateField()
  513. ? generateAggregateFields(organization, eventView.fields)
  514. : eventView.fields;
  515. const query = eventView.query;
  516. const title = this.getDocumentTitle();
  517. const yAxisArray = getYAxis(location, eventView, savedQuery);
  518. if (!eventView.isValid()) {
  519. return <LoadingIndicator />;
  520. }
  521. return (
  522. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  523. <StyledPageContent>
  524. <NoProjectMessage organization={organization}>
  525. <ResultsHeader
  526. setSavedQuery={setSavedQuery}
  527. errorCode={errorCode}
  528. organization={organization}
  529. location={location}
  530. eventView={eventView}
  531. yAxis={yAxisArray}
  532. router={router}
  533. isHomepage={isHomepage}
  534. />
  535. <Layout.Body>
  536. <CustomMeasurementsProvider
  537. organization={organization}
  538. selection={selection}
  539. >
  540. <Top fullWidth>
  541. {this.renderMetricsFallbackBanner()}
  542. {this.renderError(error)}
  543. {this.renderTips()}
  544. <StyledPageFilterBar condensed>
  545. <ProjectPageFilter />
  546. <EnvironmentPageFilter />
  547. <DatePageFilter alignDropdown="left" />
  548. </StyledPageFilterBar>
  549. <CustomMeasurementsContext.Consumer>
  550. {contextValue => (
  551. <StyledSearchBar
  552. searchSource="eventsv2"
  553. organization={organization}
  554. projectIds={eventView.project}
  555. query={query}
  556. fields={fields}
  557. onSearch={this.handleSearch}
  558. maxQueryLength={MAX_QUERY_LENGTH}
  559. customMeasurements={contextValue?.customMeasurements ?? undefined}
  560. />
  561. )}
  562. </CustomMeasurementsContext.Consumer>
  563. <MetricsCardinalityProvider
  564. organization={organization}
  565. location={location}
  566. >
  567. <MetricsBaselineContainer
  568. api={api}
  569. router={router}
  570. organization={organization}
  571. eventView={eventView}
  572. location={location}
  573. onAxisChange={this.handleYAxisChange}
  574. onDisplayChange={this.handleDisplayChange}
  575. onTopEventsChange={this.handleTopEventsChange}
  576. onIntervalChange={this.handleIntervalChange}
  577. total={totalValues}
  578. confirmedQuery={confirmedQuery}
  579. yAxis={yAxisArray}
  580. />
  581. </MetricsCardinalityProvider>
  582. </Top>
  583. <Layout.Main fullWidth={!showTags}>
  584. <Table
  585. organization={organization}
  586. eventView={eventView}
  587. location={location}
  588. title={title}
  589. setError={this.setError}
  590. onChangeShowTags={this.handleChangeShowTags}
  591. showTags={showTags}
  592. confirmedQuery={confirmedQuery}
  593. onCursor={this.handleCursor}
  594. isHomepage={isHomepage}
  595. setTips={(tips: string[]) => this.setState({tips})}
  596. />
  597. </Layout.Main>
  598. {showTags ? this.renderTagsTable() : null}
  599. <Confirm
  600. priority="primary"
  601. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  602. confirmText={t('Do it')}
  603. cancelText={t('Nevermind')}
  604. onConfirm={this.handleConfirmed}
  605. onCancel={this.handleCancelled}
  606. message={
  607. <p>
  608. {tct(
  609. `You've created a query that will search for events made
  610. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  611. A lot has happened during that time, so this might take awhile.
  612. Are you sure you want to do this?`,
  613. {
  614. dayLimit: <strong />,
  615. projectLimit: <strong />,
  616. }
  617. )}
  618. </p>
  619. }
  620. >
  621. {this.setOpenFunction}
  622. </Confirm>
  623. </CustomMeasurementsProvider>
  624. </Layout.Body>
  625. </NoProjectMessage>
  626. </StyledPageContent>
  627. </SentryDocumentTitle>
  628. );
  629. }
  630. }
  631. const StyledPageContent = styled(PageContent)`
  632. padding: 0;
  633. `;
  634. const StyledPageFilterBar = styled(PageFilterBar)`
  635. margin-bottom: ${space(1)};
  636. `;
  637. const StyledSearchBar = styled(SearchBar)`
  638. margin-bottom: ${space(2)};
  639. `;
  640. const Top = styled(Layout.Main)`
  641. flex-grow: 0;
  642. `;
  643. const TipContainer = styled('span')`
  644. > p {
  645. margin: 0;
  646. }
  647. `;
  648. type SavedQueryState = AsyncComponent['state'] & {
  649. savedQuery?: SavedQuery | null;
  650. };
  651. class SavedQueryAPI extends AsyncComponent<Props, SavedQueryState> {
  652. shouldReload = true;
  653. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  654. const {organization, location} = this.props;
  655. const endpoints: ReturnType<AsyncComponent['getEndpoints']> = [];
  656. if (location.query.id) {
  657. endpoints.push([
  658. 'savedQuery',
  659. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  660. ]);
  661. return endpoints;
  662. }
  663. return endpoints;
  664. }
  665. setSavedQuery = (newSavedQuery?: SavedQuery) => {
  666. this.setState({savedQuery: newSavedQuery});
  667. };
  668. renderBody(): React.ReactNode {
  669. const {savedQuery, loading} = this.state;
  670. return (
  671. <Results
  672. {...this.props}
  673. savedQuery={savedQuery ?? undefined}
  674. loading={loading}
  675. setSavedQuery={this.setSavedQuery}
  676. />
  677. );
  678. }
  679. }
  680. function ResultsContainer(props: Props) {
  681. /**
  682. * Block `<Results>` from mounting until GSH is ready since there are API
  683. * requests being performed on mount.
  684. *
  685. * Also, we skip loading last used projects if you have multiple projects feature as
  686. * you no longer need to enforce a project if it is empty. We assume an empty project is
  687. * the desired behavior because saved queries can contain a project filter. The only
  688. * exception is if we are showing a prebuilt saved query in which case we want to
  689. * respect pinned filters.
  690. */
  691. return (
  692. <PageFiltersContainer
  693. skipLoadLastUsed={
  694. props.organization.features.includes('global-views') && !!props.savedQuery
  695. }
  696. >
  697. <SavedQueryAPI {...props} />
  698. </PageFiltersContainer>
  699. );
  700. }
  701. export default withApi(withOrganization(withPageFilters(ResultsContainer)));