results.tsx 28 KB

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