results.tsx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. import {Component, Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {Location} from 'history';
  5. import isEqual from 'lodash/isEqual';
  6. import omit from 'lodash/omit';
  7. import {updateSavedQueryVisit} from 'sentry/actionCreators/discoverSavedQueries';
  8. import {fetchTotalCount} from 'sentry/actionCreators/events';
  9. import {fetchProjectsCount} from 'sentry/actionCreators/projects';
  10. import {loadOrganizationTags} from 'sentry/actionCreators/tags';
  11. import {Client} from 'sentry/api';
  12. import {Alert} from 'sentry/components/alert';
  13. import {Button} from 'sentry/components/button';
  14. import Confirm from 'sentry/components/confirm';
  15. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  16. import SearchBar from 'sentry/components/events/searchBar';
  17. import * as Layout from 'sentry/components/layouts/thirds';
  18. import ExternalLink from 'sentry/components/links/externalLink';
  19. import LoadingIndicator from 'sentry/components/loadingIndicator';
  20. import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
  21. import {EnvironmentPageFilter} from 'sentry/components/organizations/environmentPageFilter';
  22. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  23. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  24. import {
  25. normalizeDateTimeParams,
  26. normalizeDateTimeString,
  27. } from 'sentry/components/organizations/pageFilters/parse';
  28. import {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
  29. import type {CursorHandler} from 'sentry/components/pagination';
  30. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  31. import {MAX_QUERY_LENGTH} from 'sentry/constants';
  32. import {IconClose} from 'sentry/icons/iconClose';
  33. import {t, tct} from 'sentry/locale';
  34. import {space} from 'sentry/styles/space';
  35. import type {PageFilters} from 'sentry/types/core';
  36. import {SavedSearchType} from 'sentry/types/group';
  37. import type {InjectedRouter} from 'sentry/types/legacyReactRouter';
  38. import type {NewQuery, Organization, SavedQuery} from 'sentry/types/organization';
  39. import {defined, generateQueryWithTag} from 'sentry/utils';
  40. import {trackAnalytics} from 'sentry/utils/analytics';
  41. import {browserHistory} from 'sentry/utils/browserHistory';
  42. import type {CustomMeasurementCollection} from 'sentry/utils/customMeasurements/customMeasurements';
  43. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  44. import {CustomMeasurementsProvider} from 'sentry/utils/customMeasurements/customMeasurementsProvider';
  45. import EventView, {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  46. import {formatTagKey, generateAggregateFields} from 'sentry/utils/discover/fields';
  47. import {
  48. DatasetSource,
  49. DiscoverDatasets,
  50. DisplayModes,
  51. MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES,
  52. SavedQueryDatasets,
  53. } from 'sentry/utils/discover/types';
  54. import localStorage from 'sentry/utils/localStorage';
  55. import marked from 'sentry/utils/marked';
  56. import {MetricsCardinalityProvider} from 'sentry/utils/performance/contexts/metricsCardinality';
  57. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  58. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  59. import withApi from 'sentry/utils/withApi';
  60. import withOrganization from 'sentry/utils/withOrganization';
  61. import withPageFilters from 'sentry/utils/withPageFilters';
  62. import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
  63. import {DATASET_LABEL_MAP} from 'sentry/views/discover/savedQuery/datasetSelectorTabs';
  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 ResultsSearchQueryBuilder from './resultsSearchQueryBuilder';
  74. import {SampleDataAlert} from './sampleDataAlert';
  75. import Table from './table';
  76. import Tags from './tags';
  77. import {generateTitle} from './utils';
  78. type Props = {
  79. api: Client;
  80. loading: boolean;
  81. location: Location;
  82. organization: Organization;
  83. router: InjectedRouter;
  84. selection: PageFilters;
  85. setSavedQuery: (savedQuery?: SavedQuery) => void;
  86. isHomepage?: boolean;
  87. savedQuery?: SavedQuery;
  88. };
  89. type State = {
  90. confirmedQuery: boolean;
  91. error: string;
  92. errorCode: number;
  93. eventView: EventView;
  94. needConfirmation: boolean;
  95. showTags: boolean;
  96. tips: string[];
  97. totalValues: null | number;
  98. homepageQuery?: SavedQuery;
  99. savedQuery?: SavedQuery;
  100. savedQueryDataset?: SavedQueryDatasets;
  101. showForcedDatasetAlert?: boolean;
  102. showMetricsAlert?: boolean;
  103. showUnparameterizedBanner?: boolean;
  104. splitDecision?: SavedQueryDatasets;
  105. };
  106. const SHOW_TAGS_STORAGE_KEY = 'discover2:show-tags';
  107. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  108. function readShowTagsState() {
  109. const value = localStorage.getItem(SHOW_TAGS_STORAGE_KEY);
  110. return value === '1';
  111. }
  112. function getYAxis(location: Location, eventView: EventView, savedQuery?: SavedQuery) {
  113. if (location.query.yAxis) {
  114. return decodeList(location.query.yAxis);
  115. }
  116. if (location.query.yAxis === null) {
  117. return [];
  118. }
  119. return savedQuery?.yAxis && savedQuery?.yAxis.length > 0
  120. ? decodeList(savedQuery?.yAxis)
  121. : [eventView.getYAxis()];
  122. }
  123. export class Results extends Component<Props, State> {
  124. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  125. const savedQueryDataset = getSavedQueryDataset(
  126. nextProps.organization,
  127. nextProps.location,
  128. nextProps.savedQuery,
  129. undefined
  130. );
  131. const eventViewFromQuery = EventView.fromSavedQueryOrLocation(
  132. nextProps.savedQuery,
  133. nextProps.location
  134. );
  135. const eventView =
  136. hasDatasetSelector(nextProps.organization) && !eventViewFromQuery.dataset
  137. ? eventViewFromQuery.withDataset(
  138. getDatasetFromLocationOrSavedQueryDataset(undefined, savedQueryDataset)
  139. )
  140. : eventViewFromQuery;
  141. return {...prevState, eventView, savedQuery: nextProps.savedQuery, savedQueryDataset};
  142. }
  143. state: State = {
  144. eventView: EventView.fromSavedQueryOrLocation(
  145. this.props.savedQuery,
  146. this.props.location
  147. ),
  148. savedQueryDataset: getSavedQueryDataset(
  149. this.props.organization,
  150. this.props.location,
  151. this.props.savedQuery,
  152. undefined
  153. ),
  154. error: '',
  155. homepageQuery: undefined,
  156. errorCode: 200,
  157. totalValues: null,
  158. showTags: readShowTagsState(),
  159. needConfirmation: false,
  160. confirmedQuery: false,
  161. tips: [],
  162. showForcedDatasetAlert: true,
  163. };
  164. componentDidMount() {
  165. const {organization, selection, location, isHomepage} = this.props;
  166. if (location.query.fromMetric) {
  167. this.setState({showMetricsAlert: true});
  168. browserHistory.replace({
  169. ...location,
  170. query: {...location.query, fromMetric: undefined},
  171. });
  172. }
  173. if (location.query[SHOW_UNPARAM_BANNER]) {
  174. this.setState({showUnparameterizedBanner: true});
  175. browserHistory.replace({
  176. ...location,
  177. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  178. });
  179. }
  180. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  181. addRoutePerformanceContext(selection);
  182. this.checkEventView();
  183. this.canLoadEvents();
  184. if (!isHomepage && defined(location.query.id)) {
  185. updateSavedQueryVisit(organization.slug, location.query.id);
  186. }
  187. }
  188. componentDidUpdate(prevProps: Props, prevState: State) {
  189. const {location, organization, selection} = this.props;
  190. const {eventView, confirmedQuery, savedQuery} = this.state;
  191. this.checkEventView();
  192. const currentQuery = eventView.getEventsAPIPayload(location);
  193. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  194. const yAxisArray = getYAxis(location, eventView, savedQuery);
  195. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  196. const savedQueryDataset =
  197. decodeScalar(location.query.queryDataset) ?? savedQuery?.queryDataset;
  198. const prevSavedQueryDataset =
  199. decodeScalar(prevProps.location.query.queryDataset) ??
  200. prevState.savedQuery?.queryDataset;
  201. const datasetChanged = !isEqual(savedQueryDataset, prevSavedQueryDataset);
  202. if (
  203. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  204. this.hasChartParametersChanged(
  205. prevState.eventView,
  206. eventView,
  207. prevYAxisArray,
  208. yAxisArray
  209. ) ||
  210. datasetChanged
  211. ) {
  212. this.canLoadEvents();
  213. }
  214. if (
  215. !isEqual(prevProps.selection.datetime, selection.datetime) ||
  216. !isEqual(prevProps.selection.projects, selection.projects)
  217. ) {
  218. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  219. addRoutePerformanceContext(selection);
  220. }
  221. if (prevState.confirmedQuery !== confirmedQuery) {
  222. this.fetchTotalCount();
  223. }
  224. }
  225. tagsApi: Client = new Client();
  226. hasChartParametersChanged(
  227. prevEventView: EventView,
  228. eventView: EventView,
  229. prevYAxisArray: string[],
  230. yAxisArray: string[]
  231. ) {
  232. if (!isEqual(prevYAxisArray, yAxisArray)) {
  233. return true;
  234. }
  235. const prevDisplay = prevEventView.getDisplayMode();
  236. const display = eventView.getDisplayMode();
  237. return prevDisplay !== display;
  238. }
  239. canLoadEvents = async () => {
  240. const {api, location, organization} = this.props;
  241. const {eventView} = this.state;
  242. let needConfirmation = false;
  243. let confirmedQuery = true;
  244. const currentQuery = eventView.getEventsAPIPayload(location);
  245. const duration = eventView.getDays();
  246. if (duration > 30 && currentQuery.project) {
  247. let projectLength = currentQuery.project.length;
  248. if (
  249. projectLength === 0 ||
  250. (projectLength === 1 && currentQuery.project[0] === '-1')
  251. ) {
  252. try {
  253. const results = await fetchProjectsCount(api, organization.slug);
  254. if (projectLength === 0) {
  255. projectLength = results.myProjects;
  256. } else {
  257. projectLength = results.allProjects;
  258. }
  259. } catch (err) {
  260. // do nothing, so the length is 0 or 1 and the query is assumed safe
  261. }
  262. }
  263. if (projectLength > 10) {
  264. needConfirmation = true;
  265. confirmedQuery = false;
  266. }
  267. }
  268. // Once confirmed, a change of project or datetime will happen before this can set it to false,
  269. // this means a query will still happen even if the new conditions need confirmation
  270. // using a state callback to return this to false
  271. this.setState({needConfirmation, confirmedQuery}, () => {
  272. this.setState({confirmedQuery: false});
  273. });
  274. if (needConfirmation) {
  275. this.openConfirm();
  276. }
  277. };
  278. openConfirm = () => {};
  279. setOpenFunction = ({open}) => {
  280. this.openConfirm = open;
  281. return null;
  282. };
  283. handleConfirmed = () => {
  284. this.setState({needConfirmation: false, confirmedQuery: true}, () => {
  285. this.setState({confirmedQuery: false});
  286. });
  287. };
  288. handleCancelled = () => {
  289. this.setState({needConfirmation: false, confirmedQuery: false});
  290. };
  291. async fetchTotalCount() {
  292. const {api, organization, location} = this.props;
  293. const {eventView, confirmedQuery} = this.state;
  294. if (confirmedQuery === false || !eventView.isValid()) {
  295. return;
  296. }
  297. try {
  298. const totals = await fetchTotalCount(
  299. api,
  300. organization.slug,
  301. eventView.getEventsAPIPayload(location)
  302. );
  303. this.setState({totalValues: totals});
  304. } catch (err) {
  305. Sentry.captureException(err);
  306. }
  307. }
  308. checkEventView() {
  309. const {eventView, splitDecision, savedQueryDataset} = this.state;
  310. const {loading} = this.props;
  311. if (eventView.isValid() || loading) {
  312. return;
  313. }
  314. // If the view is not valid, redirect to a known valid state.
  315. const {location, organization, selection, isHomepage, savedQuery} = this.props;
  316. const value = getSavedQueryDataset(organization, location, savedQuery, splitDecision);
  317. const defaultEventView = hasDatasetSelector(organization)
  318. ? (getSavedQueryWithDataset(DEFAULT_EVENT_VIEW_MAP[value]) as NewQuery)
  319. : DEFAULT_EVENT_VIEW;
  320. const query = isHomepage && savedQuery ? omit(savedQuery, 'id') : defaultEventView;
  321. const nextEventView = EventView.fromNewQueryWithLocation(query, location);
  322. if (nextEventView.project.length === 0 && selection.projects) {
  323. nextEventView.project = selection.projects;
  324. }
  325. if (selection.datetime) {
  326. const {period, utc, start, end} = selection.datetime;
  327. nextEventView.statsPeriod = period ?? undefined;
  328. nextEventView.utc = utc?.toString();
  329. nextEventView.start = normalizeDateTimeString(start);
  330. nextEventView.end = normalizeDateTimeString(end);
  331. }
  332. if (location.query?.query) {
  333. nextEventView.query = decodeScalar(location.query.query, '');
  334. }
  335. if (isHomepage && !this.state.savedQuery) {
  336. this.setState({savedQuery, eventView: nextEventView});
  337. }
  338. browserHistory.replace(
  339. normalizeUrl(
  340. nextEventView.getResultsViewUrlTarget(
  341. organization.slug,
  342. isHomepage,
  343. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  344. )
  345. )
  346. );
  347. }
  348. handleCursor: CursorHandler = (cursor, path, query, _direction) => {
  349. const {router} = this.props;
  350. router.push({
  351. pathname: path,
  352. query: {...query, cursor},
  353. });
  354. // Treat pagination like the user already confirmed the query
  355. if (!this.state.needConfirmation) {
  356. this.handleConfirmed();
  357. }
  358. };
  359. handleChangeShowTags = () => {
  360. const {organization} = this.props;
  361. trackAnalytics('discover_v2.results.toggle_tag_facets', {
  362. organization,
  363. });
  364. this.setState(state => {
  365. const newValue = !state.showTags;
  366. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  367. return {...state, showTags: newValue};
  368. });
  369. };
  370. handleSearch = (query: string) => {
  371. const {router, location} = this.props;
  372. const queryParams = normalizeDateTimeParams({
  373. ...(location.query || {}),
  374. query,
  375. });
  376. // do not propagate pagination when making a new search
  377. const searchQueryParams = omit(queryParams, 'cursor');
  378. router.push({
  379. pathname: location.pathname,
  380. query: searchQueryParams,
  381. });
  382. };
  383. handleYAxisChange = (value: string[]) => {
  384. const {router, location} = this.props;
  385. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  386. location.query.display as DisplayModes
  387. );
  388. const newQuery = {
  389. ...location.query,
  390. yAxis: value.length > 0 ? value : [null],
  391. // If using Multi Y-axis and not in a supported display, change to the default display mode
  392. display:
  393. value.length > 1 && !isDisplayMultiYAxisSupported
  394. ? location.query.display === DisplayModes.DAILYTOP5
  395. ? DisplayModes.DAILY
  396. : DisplayModes.DEFAULT
  397. : location.query.display,
  398. };
  399. router.push({
  400. pathname: location.pathname,
  401. query: newQuery,
  402. });
  403. // Treat axis changing like the user already confirmed the query
  404. if (!this.state.needConfirmation) {
  405. this.handleConfirmed();
  406. }
  407. trackAnalytics('discover_v2.y_axis_change', {
  408. organization: this.props.organization,
  409. y_axis_value: value,
  410. });
  411. };
  412. handleDisplayChange = (value: string) => {
  413. const {router, location} = this.props;
  414. const newQuery = {
  415. ...location.query,
  416. display: value,
  417. };
  418. router.push({
  419. pathname: location.pathname,
  420. query: newQuery,
  421. });
  422. // Treat display changing like the user already confirmed the query
  423. if (!this.state.needConfirmation) {
  424. this.handleConfirmed();
  425. }
  426. };
  427. handleIntervalChange = (value: string | undefined) => {
  428. const {router, location} = this.props;
  429. const newQuery = {
  430. ...location.query,
  431. interval: value,
  432. };
  433. if (location.query.interval !== value) {
  434. router.push({
  435. pathname: location.pathname,
  436. query: newQuery,
  437. });
  438. // Treat display changing like the user already confirmed the query
  439. if (!this.state.needConfirmation) {
  440. this.handleConfirmed();
  441. }
  442. }
  443. };
  444. handleTopEventsChange = (value: string) => {
  445. const {router, location} = this.props;
  446. const newQuery = {
  447. ...location.query,
  448. topEvents: value,
  449. };
  450. router.push({
  451. pathname: location.pathname,
  452. query: newQuery,
  453. });
  454. // Treat display changing like the user already confirmed the query
  455. if (!this.state.needConfirmation) {
  456. this.handleConfirmed();
  457. }
  458. };
  459. getDocumentTitle(): string {
  460. const {eventView} = this.state;
  461. if (!eventView) {
  462. return '';
  463. }
  464. return generateTitle({eventView});
  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. renderSearchBar(customMeasurements: CustomMeasurementCollection | undefined) {
  606. const {organization} = this.props;
  607. const {eventView} = this.state;
  608. const fields = eventView.hasAggregateField()
  609. ? generateAggregateFields(organization, eventView.fields)
  610. : eventView.fields;
  611. if (organization.features.includes('search-query-builder-discover')) {
  612. return (
  613. <Wrapper>
  614. <ResultsSearchQueryBuilder
  615. projectIds={eventView.project}
  616. query={eventView.query}
  617. fields={fields}
  618. onSearch={this.handleSearch}
  619. customMeasurements={customMeasurements}
  620. dataset={eventView.dataset}
  621. includeTransactions
  622. />
  623. </Wrapper>
  624. );
  625. }
  626. let savedSearchType: SavedSearchType | undefined = SavedSearchType.EVENT;
  627. if (hasDatasetSelector(organization)) {
  628. savedSearchType =
  629. eventView.dataset === DiscoverDatasets.TRANSACTIONS
  630. ? SavedSearchType.TRANSACTION
  631. : SavedSearchType.ERROR;
  632. }
  633. return (
  634. <StyledSearchBar
  635. searchSource="eventsv2"
  636. organization={organization}
  637. projectIds={eventView.project}
  638. query={eventView.query}
  639. fields={fields}
  640. onSearch={this.handleSearch}
  641. maxQueryLength={MAX_QUERY_LENGTH}
  642. customMeasurements={customMeasurements}
  643. dataset={eventView.dataset}
  644. includeTransactions
  645. savedSearchType={savedSearchType}
  646. />
  647. );
  648. }
  649. render() {
  650. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  651. this.props;
  652. const {
  653. eventView,
  654. error,
  655. errorCode,
  656. totalValues,
  657. showTags,
  658. confirmedQuery,
  659. savedQuery,
  660. splitDecision,
  661. savedQueryDataset,
  662. } = this.state;
  663. const hasDatasetSelectorFeature = hasDatasetSelector(organization);
  664. const query = eventView.query;
  665. const title = this.getDocumentTitle();
  666. const yAxisArray = getYAxis(location, eventView, savedQuery);
  667. if (!eventView.isValid()) {
  668. return <LoadingIndicator />;
  669. }
  670. return (
  671. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  672. <Fragment>
  673. <ResultsHeader
  674. setSavedQuery={setSavedQuery}
  675. errorCode={errorCode}
  676. organization={organization}
  677. location={location}
  678. eventView={eventView}
  679. yAxis={yAxisArray}
  680. router={router}
  681. isHomepage={isHomepage}
  682. splitDecision={splitDecision}
  683. />
  684. <Layout.Body>
  685. <CustomMeasurementsProvider organization={organization} selection={selection}>
  686. <Top fullWidth>
  687. {this.renderMetricsFallbackBanner()}
  688. {this.renderError(error)}
  689. {this.renderTips()}
  690. {this.renderForcedDatasetBanner()}
  691. {!hasDatasetSelectorFeature && <SampleDataAlert query={query} />}
  692. <Wrapper>
  693. <PageFilterBar condensed>
  694. <ProjectPageFilter />
  695. <EnvironmentPageFilter />
  696. <DatePageFilter />
  697. </PageFilterBar>
  698. </Wrapper>
  699. <CustomMeasurementsContext.Consumer>
  700. {contextValue =>
  701. this.renderSearchBar(contextValue?.customMeasurements ?? undefined)
  702. }
  703. </CustomMeasurementsContext.Consumer>
  704. <MetricsCardinalityProvider
  705. organization={organization}
  706. location={location}
  707. >
  708. <ResultsChart
  709. api={api}
  710. router={router}
  711. organization={organization}
  712. eventView={eventView}
  713. location={location}
  714. onAxisChange={this.handleYAxisChange}
  715. onDisplayChange={this.handleDisplayChange}
  716. onTopEventsChange={this.handleTopEventsChange}
  717. onIntervalChange={this.handleIntervalChange}
  718. total={totalValues}
  719. confirmedQuery={confirmedQuery}
  720. yAxis={yAxisArray}
  721. />
  722. </MetricsCardinalityProvider>
  723. </Top>
  724. <Layout.Main fullWidth={!showTags}>
  725. <Table
  726. organization={organization}
  727. eventView={eventView}
  728. location={location}
  729. title={title}
  730. setError={this.setError}
  731. onChangeShowTags={this.handleChangeShowTags}
  732. showTags={showTags}
  733. confirmedQuery={confirmedQuery}
  734. onCursor={this.handleCursor}
  735. isHomepage={isHomepage}
  736. setTips={this.setTips}
  737. queryDataset={savedQueryDataset}
  738. setSplitDecision={(value?: SavedQueryDatasets) => {
  739. if (
  740. hasDatasetSelectorFeature &&
  741. value !== SavedQueryDatasets.DISCOVER &&
  742. value !== savedQuery?.dataset
  743. ) {
  744. this.setSplitDecision(value);
  745. }
  746. }}
  747. dataset={hasDatasetSelectorFeature ? eventView.dataset : undefined}
  748. />
  749. </Layout.Main>
  750. {showTags ? this.renderTagsTable() : null}
  751. <Confirm
  752. priority="primary"
  753. header={<strong>{t('May lead to thumb twiddling')}</strong>}
  754. confirmText={t('Do it')}
  755. cancelText={t('Nevermind')}
  756. onConfirm={this.handleConfirmed}
  757. onCancel={this.handleCancelled}
  758. message={
  759. <p>
  760. {tct(
  761. `You've created a query that will search for events made
  762. [dayLimit:over more than 30 days] for [projectLimit:more than 10 projects].
  763. A lot has happened during that time, so this might take awhile.
  764. Are you sure you want to do this?`,
  765. {
  766. dayLimit: <strong />,
  767. projectLimit: <strong />,
  768. }
  769. )}
  770. </p>
  771. }
  772. >
  773. {this.setOpenFunction}
  774. </Confirm>
  775. </CustomMeasurementsProvider>
  776. </Layout.Body>
  777. </Fragment>
  778. </SentryDocumentTitle>
  779. );
  780. }
  781. }
  782. const Wrapper = styled('div')`
  783. display: flex;
  784. flex-direction: row;
  785. gap: ${space(1)};
  786. margin-bottom: ${space(2)};
  787. @media (max-width: ${p => p.theme.breakpoints.small}) {
  788. display: grid;
  789. grid-auto-flow: row;
  790. }
  791. `;
  792. const StyledSearchBar = styled(SearchBar)`
  793. margin-bottom: ${space(2)};
  794. `;
  795. const Top = styled(Layout.Main)`
  796. flex-grow: 0;
  797. `;
  798. const TipContainer = styled('span')`
  799. > p {
  800. margin: 0;
  801. }
  802. `;
  803. type SavedQueryState = DeprecatedAsyncComponent['state'] & {
  804. savedQuery?: SavedQuery | null;
  805. };
  806. class SavedQueryAPI extends DeprecatedAsyncComponent<Props, SavedQueryState> {
  807. shouldReload = true;
  808. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  809. const {organization, location} = this.props;
  810. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [];
  811. if (location.query.id) {
  812. endpoints.push([
  813. 'savedQuery',
  814. `/organizations/${organization.slug}/discover/saved/${location.query.id}/`,
  815. ]);
  816. return endpoints;
  817. }
  818. return endpoints;
  819. }
  820. setSavedQuery = (newSavedQuery?: SavedQuery) => {
  821. this.setState({savedQuery: newSavedQuery});
  822. };
  823. renderBody(): React.ReactNode {
  824. const {organization} = this.props;
  825. const {savedQuery, loading} = this.state;
  826. let savedQueryWithDataset = savedQuery;
  827. if (hasDatasetSelector(organization) && savedQuery) {
  828. savedQueryWithDataset = getSavedQueryWithDataset(savedQuery) as SavedQuery;
  829. }
  830. return (
  831. <Results
  832. {...this.props}
  833. savedQuery={savedQueryWithDataset ?? undefined}
  834. loading={loading}
  835. setSavedQuery={this.setSavedQuery}
  836. />
  837. );
  838. }
  839. }
  840. function ResultsContainer(props: Props) {
  841. /**
  842. * Block `<Results>` from mounting until GSH is ready since there are API
  843. * requests being performed on mount.
  844. *
  845. * Also, we skip loading last used projects if you have multiple projects feature as
  846. * you no longer need to enforce a project if it is empty. We assume an empty project is
  847. * the desired behavior because saved queries can contain a project filter. The only
  848. * exception is if we are showing a prebuilt saved query in which case we want to
  849. * respect pinned filters.
  850. */
  851. return (
  852. <PageFiltersContainer
  853. disablePersistence={
  854. props.organization.features.includes('discover-query') &&
  855. !!(props.savedQuery || props.location.query.id)
  856. }
  857. skipLoadLastUsed={
  858. props.organization.features.includes('global-views') && !!props.savedQuery
  859. }
  860. >
  861. <SavedQueryAPI {...props} />
  862. </PageFiltersContainer>
  863. );
  864. }
  865. export default withApi(withOrganization(withPageFilters(ResultsContainer)));
  866. const StyledCloseButton = styled(Button)`
  867. background-color: transparent;
  868. transition: opacity 0.1s linear;
  869. &:hover,
  870. &:focus {
  871. background-color: transparent;
  872. opacity: 1;
  873. }
  874. `;