results.tsx 24 KB

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