results.tsx 29 KB

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