results.tsx 24 KB

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