results.tsx 30 KB

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