results.tsx 31 KB

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