results.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  1. import {Component, Fragment} from 'react';
  2. import type {InjectedRouter} from 'react-router';
  3. import {browserHistory} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import * as Sentry from '@sentry/react';
  6. import type {Location} from 'history';
  7. import isEqual from 'lodash/isEqual';
  8. import omit from 'lodash/omit';
  9. import {updateSavedQueryVisit} from 'sentry/actionCreators/discoverSavedQueries';
  10. import {fetchTotalCount} from 'sentry/actionCreators/events';
  11. import {fetchProjectsCount} from 'sentry/actionCreators/projects';
  12. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  13. import {Client} from 'sentry/api';
  14. import {Alert} from 'sentry/components/alert';
  15. import Confirm from 'sentry/components/confirm';
  16. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  17. import SearchBar from 'sentry/components/events/searchBar';
  18. import * as Layout from 'sentry/components/layouts/thirds';
  19. import ExternalLink from 'sentry/components/links/externalLink';
  20. import LoadingIndicator from 'sentry/components/loadingIndicator';
  21. import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
  22. import {EnvironmentPageFilter} from 'sentry/components/organizations/environmentPageFilter';
  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 {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
  30. import type {CursorHandler} from 'sentry/components/pagination';
  31. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  32. import {MAX_QUERY_LENGTH} from 'sentry/constants';
  33. import {t, tct} from 'sentry/locale';
  34. import {space} from 'sentry/styles/space';
  35. import type {Organization, PageFilters, SavedQuery} from 'sentry/types';
  36. import {defined, generateQueryWithTag} from 'sentry/utils';
  37. import {trackAnalytics} from 'sentry/utils/analytics';
  38. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  39. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  40. import EventView, {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  41. import {formatTagKey, generateAggregateFields} from 'sentry/utils/discover/fields';
  42. import {
  43. DisplayModes,
  44. MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES,
  45. } from 'sentry/utils/discover/types';
  46. import localStorage from 'sentry/utils/localStorage';
  47. import marked from 'sentry/utils/marked';
  48. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  49. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  50. import withApi from 'sentry/utils/withApi';
  51. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  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 ResultsChart from './resultsChart';
  57. import ResultsHeader from './resultsHeader';
  58. import {SampleDataAlert} from './sampleDataAlert';
  59. import Table from './table';
  60. import Tags from './tags';
  61. import {generateTitle} from './utils';
  62. type Props = {
  63. api: Client;
  64. loading: boolean;
  65. location: Location;
  66. organization: Organization;
  67. router: InjectedRouter;
  68. selection: PageFilters;
  69. setSavedQuery: (savedQuery?: SavedQuery) => void;
  70. isHomepage?: boolean;
  71. savedQuery?: SavedQuery;
  72. };
  73. type State = {
  74. confirmedQuery: boolean;
  75. error: string;
  76. errorCode: number;
  77. eventView: EventView;
  78. needConfirmation: boolean;
  79. showTags: boolean;
  80. tips: string[];
  81. totalValues: null | number;
  82. savedQuery?: SavedQuery;
  83. showMetricsAlert?: boolean;
  84. showUnparameterizedBanner?: boolean;
  85. };
  86. const SHOW_TAGS_STORAGE_KEY = 'discover2:show-tags';
  87. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  88. function readShowTagsState() {
  89. const value = localStorage.getItem(SHOW_TAGS_STORAGE_KEY);
  90. return value === '1';
  91. }
  92. function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQuery) {
  93. if (location.query.yAxis) {
  94. return decodeList(location.query.yAxis);
  95. }
  96. if (location.query.yAxis === null) {
  97. return [];
  98. }
  99. return savedQuery?.yAxis && savedQuery?.yAxis.length > 0
  100. ? decodeList(savedQuery?.yAxis)
  101. : [eventView.getYAxis()];
  102. }
  103. export class Results extends Component<Props, State> {
  104. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  105. const eventView = EventView.fromSavedQueryOrLocation(
  106. nextProps.savedQuery,
  107. nextProps.location
  108. );
  109. return {...prevState, eventView, savedQuery: nextProps.savedQuery};
  110. }
  111. state: State = {
  112. eventView: EventView.fromSavedQueryOrLocation(
  113. this.props.savedQuery,
  114. this.props.location
  115. ),
  116. error: '',
  117. errorCode: 200,
  118. totalValues: null,
  119. showTags: readShowTagsState(),
  120. needConfirmation: false,
  121. confirmedQuery: false,
  122. tips: [],
  123. };
  124. componentDidMount() {
  125. const {organization, selection, location, isHomepage} = this.props;
  126. if (location.query.fromMetric) {
  127. this.setState({showMetricsAlert: true});
  128. browserHistory.replace({
  129. ...location,
  130. query: {...location.query, fromMetric: undefined},
  131. });
  132. }
  133. if (location.query[SHOW_UNPARAM_BANNER]) {
  134. this.setState({showUnparameterizedBanner: true});
  135. browserHistory.replace({
  136. ...location,
  137. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  138. });
  139. }
  140. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  141. addRoutePerformanceContext(selection);
  142. this.checkEventView();
  143. this.canLoadEvents();
  144. if (!isHomepage && defined(location.query.id)) {
  145. updateSavedQueryVisit(organization.slug, location.query.id);
  146. }
  147. }
  148. componentDidUpdate(prevProps: Props, prevState: State) {
  149. const {location, organization, selection} = this.props;
  150. const {eventView, confirmedQuery, savedQuery} = this.state;
  151. this.checkEventView();
  152. const currentQuery = eventView.getEventsAPIPayload(location);
  153. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  154. const yAxisArray = getYAxis(location, eventView, savedQuery);
  155. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  156. if (
  157. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  158. this.hasChartParametersChanged(
  159. prevState.eventView,
  160. eventView,
  161. prevYAxisArray,
  162. yAxisArray
  163. )
  164. ) {
  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');
  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. normalizeUrl(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. trackAnalytics('discover_v2.results.toggle_tag_facets', {
  311. organization,
  312. });
  313. this.setState(state => {
  314. const newValue = !state.showTags;
  315. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  316. return {...state, showTags: newValue};
  317. });
  318. };
  319. handleSearch = (query: string) => {
  320. const {router, location} = this.props;
  321. const queryParams = normalizeDateTimeParams({
  322. ...(location.query || {}),
  323. query,
  324. });
  325. // do not propagate pagination when making a new search
  326. const searchQueryParams = omit(queryParams, 'cursor');
  327. router.push({
  328. pathname: location.pathname,
  329. query: searchQueryParams,
  330. });
  331. };
  332. handleYAxisChange = (value: string[]) => {
  333. const {router, location} = this.props;
  334. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  335. location.query.display as DisplayModes
  336. );
  337. const newQuery = {
  338. ...location.query,
  339. yAxis: value.length > 0 ? value : [null],
  340. // If using Multi Y-axis and not in a supported display, change to the default display mode
  341. display:
  342. value.length > 1 && !isDisplayMultiYAxisSupported
  343. ? location.query.display === DisplayModes.DAILYTOP5
  344. ? DisplayModes.DAILY
  345. : DisplayModes.DEFAULT
  346. : location.query.display,
  347. };
  348. router.push({
  349. pathname: location.pathname,
  350. query: newQuery,
  351. });
  352. // Treat axis changing like the user already confirmed the query
  353. if (!this.state.needConfirmation) {
  354. this.handleConfirmed();
  355. }
  356. trackAnalytics('discover_v2.y_axis_change', {
  357. organization: this.props.organization,
  358. y_axis_value: value,
  359. });
  360. };
  361. handleDisplayChange = (value: string) => {
  362. const {router, location} = this.props;
  363. const newQuery = {
  364. ...location.query,
  365. display: value,
  366. };
  367. router.push({
  368. pathname: location.pathname,
  369. query: newQuery,
  370. });
  371. // Treat display changing like the user already confirmed the query
  372. if (!this.state.needConfirmation) {
  373. this.handleConfirmed();
  374. }
  375. };
  376. handleIntervalChange = (value: string | undefined) => {
  377. const {router, location} = this.props;
  378. const newQuery = {
  379. ...location.query,
  380. interval: value,
  381. };
  382. if (location.query.interval !== value) {
  383. router.push({
  384. pathname: location.pathname,
  385. query: newQuery,
  386. });
  387. // Treat display changing like the user already confirmed the query
  388. if (!this.state.needConfirmation) {
  389. this.handleConfirmed();
  390. }
  391. }
  392. };
  393. handleTopEventsChange = (value: string) => {
  394. const {router, location} = this.props;
  395. const newQuery = {
  396. ...location.query,
  397. topEvents: value,
  398. };
  399. router.push({
  400. pathname: location.pathname,
  401. query: newQuery,
  402. });
  403. // Treat display changing like the user already confirmed the query
  404. if (!this.state.needConfirmation) {
  405. this.handleConfirmed();
  406. }
  407. };
  408. getDocumentTitle(): string {
  409. const {organization} = this.props;
  410. const {eventView} = this.state;
  411. if (!eventView) {
  412. return '';
  413. }
  414. return generateTitle({eventView, organization});
  415. }
  416. renderTagsTable() {
  417. const {organization, location} = this.props;
  418. const {eventView, totalValues, confirmedQuery} = this.state;
  419. return (
  420. <Layout.Side>
  421. <Tags
  422. generateUrl={this.generateTagUrl}
  423. totalValues={totalValues}
  424. eventView={eventView}
  425. organization={organization}
  426. location={location}
  427. confirmedQuery={confirmedQuery}
  428. />
  429. </Layout.Side>
  430. );
  431. }
  432. generateTagUrl = (key: string, value: string) => {
  433. const {organization, isHomepage} = this.props;
  434. const {eventView} = this.state;
  435. const url = eventView.getResultsViewUrlTarget(organization.slug, isHomepage);
  436. url.query = generateQueryWithTag(url.query, {
  437. key: formatTagKey(key),
  438. value,
  439. });
  440. return url;
  441. };
  442. renderError(error: string) {
  443. if (!error) {
  444. return null;
  445. }
  446. return (
  447. <Alert type="error" showIcon>
  448. {error}
  449. </Alert>
  450. );
  451. }
  452. setError = (error: string, errorCode: number) => {
  453. this.setState({error, errorCode});
  454. };
  455. renderMetricsFallbackBanner() {
  456. const {organization} = this.props;
  457. if (
  458. !organization.features.includes('performance-mep-bannerless-ui') &&
  459. this.state.showMetricsAlert
  460. ) {
  461. return (
  462. <Alert type="info" showIcon>
  463. {t(
  464. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  465. )}
  466. </Alert>
  467. );
  468. }
  469. if (this.state.showUnparameterizedBanner) {
  470. return (
  471. <Alert type="info" showIcon>
  472. {tct(
  473. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  474. {
  475. link: (
  476. <ExternalLink href="https://docs.sentry.io/platforms/javascript/performance/instrumentation/automatic-instrumentation/#beforenavigate" />
  477. ),
  478. }
  479. )}
  480. </Alert>
  481. );
  482. }
  483. return null;
  484. }
  485. renderTips() {
  486. const {tips} = this.state;
  487. if (tips) {
  488. return tips.map((tip, index) => (
  489. <Alert type="info" showIcon key={`tip-${index}`}>
  490. <TipContainer dangerouslySetInnerHTML={{__html: marked(tip)}} />
  491. </Alert>
  492. ));
  493. }
  494. return null;
  495. }
  496. setTips = (tips: string[]) => {
  497. // If there are currently no tips set and the new tips are empty, do nothing
  498. // and bail out of an expensive entire table rerender
  499. if (!tips.length && !this.state.tips.length) {
  500. return;
  501. }
  502. this.setState({tips});
  503. };
  504. render() {
  505. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  506. this.props;
  507. const {
  508. eventView,
  509. error,
  510. errorCode,
  511. totalValues,
  512. showTags,
  513. confirmedQuery,
  514. savedQuery,
  515. } = this.state;
  516. const fields = eventView.hasAggregateField()
  517. ? generateAggregateFields(organization, eventView.fields)
  518. : eventView.fields;
  519. const query = eventView.query;
  520. const title = this.getDocumentTitle();
  521. const yAxisArray = getYAxis(location, eventView, savedQuery);
  522. if (!eventView.isValid()) {
  523. return <LoadingIndicator />;
  524. }
  525. return (
  526. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  527. <Fragment>
  528. <ResultsHeader
  529. setSavedQuery={setSavedQuery}
  530. errorCode={errorCode}
  531. organization={organization}
  532. location={location}
  533. eventView={eventView}
  534. yAxis={yAxisArray}
  535. router={router}
  536. isHomepage={isHomepage}
  537. />
  538. <Layout.Body>
  539. <CustomMeasurementsProvider organization={organization} selection={selection}>
  540. <Top fullWidth>
  541. {this.renderMetricsFallbackBanner()}
  542. {this.renderError(error)}
  543. {this.renderTips()}
  544. <StyledPageFilterBar condensed>
  545. <ProjectPageFilter />
  546. <EnvironmentPageFilter />
  547. <DatePageFilter />
  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. <SampleDataAlert query={query} />
  564. <MetricsCardinalityProvider
  565. organization={organization}
  566. location={location}
  567. >
  568. <ResultsChart
  569. api={api}
  570. router={router}
  571. organization={organization}
  572. eventView={eventView}
  573. location={location}
  574. onAxisChange={this.handleYAxisChange}
  575. onDisplayChange={this.handleDisplayChange}
  576. onTopEventsChange={this.handleTopEventsChange}
  577. onIntervalChange={this.handleIntervalChange}
  578. total={totalValues}
  579. confirmedQuery={confirmedQuery}
  580. yAxis={yAxisArray}
  581. />
  582. </MetricsCardinalityProvider>
  583. </Top>
  584. <Layout.Main fullWidth={!showTags}>
  585. <Table
  586. organization={organization}
  587. eventView={eventView}
  588. location={location}
  589. title={title}
  590. setError={this.setError}
  591. onChangeShowTags={this.handleChangeShowTags}
  592. showTags={showTags}
  593. confirmedQuery={confirmedQuery}
  594. onCursor={this.handleCursor}
  595. isHomepage={isHomepage}
  596. setTips={this.setTips}
  597. />
  598. </Layout.Main>
  599. {showTags ? this.renderTagsTable() : null}
  600. <Confirm
  601. priority="primary"
  602. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  603. confirmText={t('Do it')}
  604. cancelText={t('Nevermind')}
  605. onConfirm={this.handleConfirmed}
  606. onCancel={this.handleCancelled}
  607. message={
  608. <p>
  609. {tct(
  610. `You've created a query that will search for events made
  611. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  612. A lot has happened during that time, so this might take awhile.
  613. Are you sure you want to do this?`,
  614. {
  615. dayLimit: <strong />,
  616. projectLimit: <strong />,
  617. }
  618. )}
  619. </p>
  620. }
  621. >
  622. {this.setOpenFunction}
  623. </Confirm>
  624. </CustomMeasurementsProvider>
  625. </Layout.Body>
  626. </Fragment>
  627. </SentryDocumentTitle>
  628. );
  629. }
  630. }
  631. const StyledPageFilterBar = styled(PageFilterBar)`
  632. margin-bottom: ${space(2)};
  633. `;
  634. const StyledSearchBar = styled(SearchBar)`
  635. margin-bottom: ${space(2)};
  636. `;
  637. const Top = styled(Layout.Main)`
  638. flex-grow: 0;
  639. `;
  640. const TipContainer = styled('span')`
  641. > p {
  642. margin: 0;
  643. }
  644. `;
  645. type SavedQueryState = DeprecatedAsyncComponent['state'] & {
  646. savedQuery?: SavedQuery | null;
  647. };
  648. class SavedQueryAPI extends DeprecatedAsyncComponent<Props, SavedQueryState> {
  649. shouldReload = true;
  650. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  651. const {organization, location} = this.props;
  652. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [];
  653. if (location.query.id) {
  654. endpoints.push([
  655. 'savedQuery',
  656. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  657. ]);
  658. return endpoints;
  659. }
  660. return endpoints;
  661. }
  662. setSavedQuery = (newSavedQuery?: SavedQuery) => {
  663. this.setState({savedQuery: newSavedQuery});
  664. };
  665. renderBody(): React.ReactNode {
  666. const {savedQuery, loading} = this.state;
  667. return (
  668. <Results
  669. {...this.props}
  670. savedQuery={savedQuery ?? undefined}
  671. loading={loading}
  672. setSavedQuery={this.setSavedQuery}
  673. />
  674. );
  675. }
  676. }
  677. function ResultsContainer(props: Props) {
  678. /**
  679. * Block `<Results>` from mounting until GSH is ready since there are API
  680. * requests being performed on mount.
  681. *
  682. * Also, we skip loading last used projects if you have multiple projects feature as
  683. * you no longer need to enforce a project if it is empty. We assume an empty project is
  684. * the desired behavior because saved queries can contain a project filter. The only
  685. * exception is if we are showing a prebuilt saved query in which case we want to
  686. * respect pinned filters.
  687. */
  688. return (
  689. <PageFiltersContainer
  690. disablePersistence={
  691. props.organization.features.includes('discover-query') &&
  692. !!(props.savedQuery || props.location.query.id)
  693. }
  694. skipLoadLastUsed={
  695. props.organization.features.includes('global-views') && !!props.savedQuery
  696. }
  697. >
  698. <SavedQueryAPI {...props} />
  699. </PageFiltersContainer>
  700. );
  701. }
  702. export default withApi(withOrganization(withPageFilters(ResultsContainer)));