results.tsx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989
  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 {organization} = this.props;
  465. const {eventView} = this.state;
  466. if (!eventView) {
  467. return '';
  468. }
  469. return generateTitle({eventView, organization});
  470. }
  471. renderTagsTable() {
  472. const {organization, location} = this.props;
  473. const {eventView, totalValues, confirmedQuery} = this.state;
  474. return (
  475. <Layout.Side>
  476. <Tags
  477. generateUrl={this.generateTagUrl}
  478. totalValues={totalValues}
  479. eventView={eventView}
  480. organization={organization}
  481. location={location}
  482. confirmedQuery={confirmedQuery}
  483. />
  484. </Layout.Side>
  485. );
  486. }
  487. generateTagUrl = (key: string, value: string) => {
  488. const {organization, isHomepage} = this.props;
  489. const {eventView, savedQueryDataset} = this.state;
  490. const url = eventView.getResultsViewUrlTarget(
  491. organization.slug,
  492. isHomepage,
  493. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  494. );
  495. url.query = generateQueryWithTag(url.query, {
  496. key: formatTagKey(key),
  497. value,
  498. });
  499. return url;
  500. };
  501. renderError(error: string) {
  502. if (!error) {
  503. return null;
  504. }
  505. return (
  506. <Alert type="error" showIcon>
  507. {error}
  508. </Alert>
  509. );
  510. }
  511. setError = (error: string, errorCode: number) => {
  512. this.setState({error, errorCode});
  513. };
  514. renderMetricsFallbackBanner() {
  515. const {organization} = this.props;
  516. if (
  517. !organization.features.includes('performance-mep-bannerless-ui') &&
  518. this.state.showMetricsAlert
  519. ) {
  520. return (
  521. <Alert type="info" showIcon>
  522. {t(
  523. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  524. )}
  525. </Alert>
  526. );
  527. }
  528. if (this.state.showUnparameterizedBanner) {
  529. return (
  530. <Alert type="info" showIcon>
  531. {tct(
  532. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  533. {
  534. link: (
  535. <ExternalLink href="https://docs.sentry.io/platforms/javascript/tracing/instrumentation/automatic-instrumentation/#beforenavigate" />
  536. ),
  537. }
  538. )}
  539. </Alert>
  540. );
  541. }
  542. return null;
  543. }
  544. renderForcedDatasetBanner() {
  545. const {organization, savedQuery} = this.props;
  546. if (
  547. hasDatasetSelector(organization) &&
  548. this.state.showForcedDatasetAlert &&
  549. (this.state.splitDecision || savedQuery?.datasetSource === DatasetSource.FORCED)
  550. ) {
  551. const splitDecision = this.state.splitDecision ?? savedQuery?.queryDataset;
  552. if (!splitDecision) {
  553. return null;
  554. }
  555. return (
  556. <Alert
  557. type="warning"
  558. showIcon
  559. trailingItems={
  560. <StyledCloseButton
  561. icon={<IconClose size="sm" />}
  562. aria-label={t('Close')}
  563. onClick={() => {
  564. this.setState({showForcedDatasetAlert: false});
  565. }}
  566. size="zero"
  567. borderless
  568. />
  569. }
  570. >
  571. {tct(
  572. "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.",
  573. {splitDecision: DATASET_LABEL_MAP[splitDecision]}
  574. )}
  575. </Alert>
  576. );
  577. }
  578. return null;
  579. }
  580. renderTips() {
  581. const {tips} = this.state;
  582. if (tips) {
  583. return tips.map((tip, index) => (
  584. <Alert type="info" showIcon key={`tip-${index}`}>
  585. <TipContainer dangerouslySetInnerHTML={{__html: marked(tip)}} />
  586. </Alert>
  587. ));
  588. }
  589. return null;
  590. }
  591. setTips = (tips: string[]) => {
  592. // If there are currently no tips set and the new tips are empty, do nothing
  593. // and bail out of an expensive entire table rerender
  594. if (!tips.length && !this.state.tips.length) {
  595. return;
  596. }
  597. this.setState({tips});
  598. };
  599. setSplitDecision = (value?: SavedQueryDatasets) => {
  600. const {eventView} = this.state;
  601. const newEventView = eventView.withDataset(
  602. getDatasetFromLocationOrSavedQueryDataset(undefined, value)
  603. );
  604. this.setState({
  605. splitDecision: value,
  606. savedQueryDataset: value,
  607. eventView: newEventView,
  608. });
  609. };
  610. renderSearchBar(customMeasurements: CustomMeasurementCollection | undefined) {
  611. const {organization} = this.props;
  612. const {eventView} = this.state;
  613. const fields = eventView.hasAggregateField()
  614. ? generateAggregateFields(organization, eventView.fields)
  615. : eventView.fields;
  616. if (organization.features.includes('search-query-builder-discover')) {
  617. return (
  618. <ResultsSearchQueryBuilder
  619. projectIds={eventView.project}
  620. query={eventView.query}
  621. fields={fields}
  622. onSearch={this.handleSearch}
  623. customMeasurements={customMeasurements}
  624. dataset={eventView.dataset}
  625. includeTransactions
  626. />
  627. );
  628. }
  629. let savedSearchType: SavedSearchType | undefined = SavedSearchType.EVENT;
  630. if (hasDatasetSelector(organization)) {
  631. savedSearchType =
  632. eventView.dataset === DiscoverDatasets.TRANSACTIONS
  633. ? SavedSearchType.TRANSACTION
  634. : SavedSearchType.ERROR;
  635. }
  636. return (
  637. <StyledSearchBar
  638. searchSource="eventsv2"
  639. organization={organization}
  640. projectIds={eventView.project}
  641. query={eventView.query}
  642. fields={fields}
  643. onSearch={this.handleSearch}
  644. maxQueryLength={MAX_QUERY_LENGTH}
  645. customMeasurements={customMeasurements}
  646. dataset={eventView.dataset}
  647. includeTransactions
  648. savedSearchType={savedSearchType}
  649. />
  650. );
  651. }
  652. render() {
  653. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  654. this.props;
  655. const {
  656. eventView,
  657. error,
  658. errorCode,
  659. totalValues,
  660. showTags,
  661. confirmedQuery,
  662. savedQuery,
  663. splitDecision,
  664. savedQueryDataset,
  665. } = this.state;
  666. const hasDatasetSelectorFeature = hasDatasetSelector(organization);
  667. const query = eventView.query;
  668. const title = this.getDocumentTitle();
  669. const yAxisArray = getYAxis(location, eventView, savedQuery);
  670. if (!eventView.isValid()) {
  671. return <LoadingIndicator />;
  672. }
  673. return (
  674. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  675. <Fragment>
  676. <ResultsHeader
  677. setSavedQuery={setSavedQuery}
  678. errorCode={errorCode}
  679. organization={organization}
  680. location={location}
  681. eventView={eventView}
  682. yAxis={yAxisArray}
  683. router={router}
  684. isHomepage={isHomepage}
  685. />
  686. <Layout.Body>
  687. <CustomMeasurementsProvider organization={organization} selection={selection}>
  688. <Top fullWidth>
  689. {this.renderMetricsFallbackBanner()}
  690. {this.renderError(error)}
  691. {this.renderTips()}
  692. {this.renderForcedDatasetBanner()}
  693. {!hasDatasetSelectorFeature && <SampleDataAlert query={query} />}
  694. <Wrapper>
  695. <Feature
  696. organization={organization}
  697. features="performance-discover-dataset-selector"
  698. >
  699. {({hasFeature}) =>
  700. hasFeature && (
  701. <DatasetSelector
  702. isHomepage={isHomepage}
  703. savedQuery={savedQuery}
  704. splitDecision={splitDecision}
  705. eventView={eventView}
  706. />
  707. )
  708. }
  709. </Feature>
  710. <PageFilterBar condensed>
  711. <ProjectPageFilter />
  712. <EnvironmentPageFilter />
  713. <DatePageFilter />
  714. </PageFilterBar>
  715. </Wrapper>
  716. <CustomMeasurementsContext.Consumer>
  717. {contextValue =>
  718. this.renderSearchBar(contextValue?.customMeasurements ?? undefined)
  719. }
  720. </CustomMeasurementsContext.Consumer>
  721. <MetricsCardinalityProvider
  722. organization={organization}
  723. location={location}
  724. >
  725. <ResultsChart
  726. api={api}
  727. router={router}
  728. organization={organization}
  729. eventView={eventView}
  730. location={location}
  731. onAxisChange={this.handleYAxisChange}
  732. onDisplayChange={this.handleDisplayChange}
  733. onTopEventsChange={this.handleTopEventsChange}
  734. onIntervalChange={this.handleIntervalChange}
  735. total={totalValues}
  736. confirmedQuery={confirmedQuery}
  737. yAxis={yAxisArray}
  738. />
  739. </MetricsCardinalityProvider>
  740. </Top>
  741. <Layout.Main fullWidth={!showTags}>
  742. <Table
  743. organization={organization}
  744. eventView={eventView}
  745. location={location}
  746. title={title}
  747. setError={this.setError}
  748. onChangeShowTags={this.handleChangeShowTags}
  749. showTags={showTags}
  750. confirmedQuery={confirmedQuery}
  751. onCursor={this.handleCursor}
  752. isHomepage={isHomepage}
  753. setTips={this.setTips}
  754. queryDataset={savedQueryDataset}
  755. setSplitDecision={(value?: SavedQueryDatasets) => {
  756. if (
  757. hasDatasetSelectorFeature &&
  758. value !== SavedQueryDatasets.DISCOVER &&
  759. value !== savedQuery?.dataset
  760. ) {
  761. this.setSplitDecision(value);
  762. }
  763. }}
  764. dataset={hasDatasetSelectorFeature ? eventView.dataset : undefined}
  765. />
  766. </Layout.Main>
  767. {showTags ? this.renderTagsTable() : null}
  768. <Confirm
  769. priority="primary"
  770. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  771. confirmText={t('Do it')}
  772. cancelText={t('Nevermind')}
  773. onConfirm={this.handleConfirmed}
  774. onCancel={this.handleCancelled}
  775. message={
  776. <p>
  777. {tct(
  778. `You've created a query that will search for events made
  779. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  780. A lot has happened during that time, so this might take awhile.
  781. Are you sure you want to do this?`,
  782. {
  783. dayLimit: <strong />,
  784. projectLimit: <strong />,
  785. }
  786. )}
  787. </p>
  788. }
  789. >
  790. {this.setOpenFunction}
  791. </Confirm>
  792. </CustomMeasurementsProvider>
  793. </Layout.Body>
  794. </Fragment>
  795. </SentryDocumentTitle>
  796. );
  797. }
  798. }
  799. const Wrapper = styled('div')`
  800. display: flex;
  801. flex-direction: row;
  802. gap: ${space(1)};
  803. margin-bottom: ${space(2)};
  804. @media (max-width: ${p => p.theme.breakpoints.small}) {
  805. display: grid;
  806. grid-auto-flow: row;
  807. }
  808. `;
  809. const StyledSearchBar = styled(SearchBar)`
  810. margin-bottom: ${space(2)};
  811. `;
  812. const Top = styled(Layout.Main)`
  813. flex-grow: 0;
  814. `;
  815. const TipContainer = styled('span')`
  816. > p {
  817. margin: 0;
  818. }
  819. `;
  820. type SavedQueryState = DeprecatedAsyncComponent['state'] & {
  821. savedQuery?: SavedQuery | null;
  822. };
  823. class SavedQueryAPI extends DeprecatedAsyncComponent<Props, SavedQueryState> {
  824. shouldReload = true;
  825. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  826. const {organization, location} = this.props;
  827. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [];
  828. if (location.query.id) {
  829. endpoints.push([
  830. 'savedQuery',
  831. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  832. ]);
  833. return endpoints;
  834. }
  835. return endpoints;
  836. }
  837. setSavedQuery = (newSavedQuery?: SavedQuery) => {
  838. this.setState({savedQuery: newSavedQuery});
  839. };
  840. renderBody(): React.ReactNode {
  841. const {organization} = this.props;
  842. const {savedQuery, loading} = this.state;
  843. let savedQueryWithDataset = savedQuery;
  844. if (hasDatasetSelector(organization) && savedQuery) {
  845. savedQueryWithDataset = getSavedQueryWithDataset(savedQuery) as SavedQuery;
  846. }
  847. return (
  848. <Results
  849. {...this.props}
  850. savedQuery={savedQueryWithDataset ?? undefined}
  851. loading={loading}
  852. setSavedQuery={this.setSavedQuery}
  853. />
  854. );
  855. }
  856. }
  857. function ResultsContainer(props: Props) {
  858. /**
  859. * Block `<Results>` from mounting until GSH is ready since there are API
  860. * requests being performed on mount.
  861. *
  862. * Also, we skip loading last used projects if you have multiple projects feature as
  863. * you no longer need to enforce a project if it is empty. We assume an empty project is
  864. * the desired behavior because saved queries can contain a project filter. The only
  865. * exception is if we are showing a prebuilt saved query in which case we want to
  866. * respect pinned filters.
  867. */
  868. return (
  869. <PageFiltersContainer
  870. disablePersistence={
  871. props.organization.features.includes('discover-query') &&
  872. !!(props.savedQuery || props.location.query.id)
  873. }
  874. skipLoadLastUsed={
  875. props.organization.features.includes('global-views') && !!props.savedQuery
  876. }
  877. >
  878. <SavedQueryAPI {...props} />
  879. </PageFiltersContainer>
  880. );
  881. }
  882. export default withApi(withOrganization(withPageFilters(ResultsContainer)));
  883. const StyledCloseButton = styled(Button)`
  884. background-color: transparent;
  885. transition: opacity 0.1s linear;
  886. &:hover,
  887. &:focus {
  888. background-color: transparent;
  889. opacity: 1;
  890. }
  891. `;