results.tsx 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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 eventView = EventView.fromSavedQueryOrLocation(
  125. nextProps.savedQuery,
  126. nextProps.location
  127. );
  128. const savedQueryDataset = getSavedQueryDataset(
  129. nextProps.organization,
  130. nextProps.location,
  131. nextProps.savedQuery,
  132. undefined
  133. );
  134. return {...prevState, eventView, savedQuery: nextProps.savedQuery, savedQueryDataset};
  135. }
  136. state: State = {
  137. eventView: EventView.fromSavedQueryOrLocation(
  138. this.props.savedQuery,
  139. this.props.location
  140. ),
  141. savedQueryDataset: getSavedQueryDataset(
  142. this.props.organization,
  143. this.props.location,
  144. this.props.savedQuery,
  145. undefined
  146. ),
  147. error: '',
  148. homepageQuery: undefined,
  149. errorCode: 200,
  150. totalValues: null,
  151. showTags: readShowTagsState(),
  152. needConfirmation: false,
  153. confirmedQuery: false,
  154. tips: [],
  155. showForcedDatasetAlert: true,
  156. };
  157. componentDidMount() {
  158. const {organization, selection, location, isHomepage} = this.props;
  159. if (location.query.fromMetric) {
  160. this.setState({showMetricsAlert: true});
  161. browserHistory.replace({
  162. ...location,
  163. query: {...location.query, fromMetric: undefined},
  164. });
  165. }
  166. if (location.query[SHOW_UNPARAM_BANNER]) {
  167. this.setState({showUnparameterizedBanner: true});
  168. browserHistory.replace({
  169. ...location,
  170. query: {...location.query, [SHOW_UNPARAM_BANNER]: undefined},
  171. });
  172. }
  173. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  174. addRoutePerformanceContext(selection);
  175. this.checkEventView();
  176. this.canLoadEvents();
  177. if (!isHomepage && defined(location.query.id)) {
  178. updateSavedQueryVisit(organization.slug, location.query.id);
  179. }
  180. }
  181. componentDidUpdate(prevProps: Props, prevState: State) {
  182. const {location, organization, selection} = this.props;
  183. const {eventView, confirmedQuery, savedQuery} = this.state;
  184. this.checkEventView();
  185. const currentQuery = eventView.getEventsAPIPayload(location);
  186. const prevQuery = prevState.eventView.getEventsAPIPayload(prevProps.location);
  187. const yAxisArray = getYAxis(location, eventView, savedQuery);
  188. const prevYAxisArray = getYAxis(prevProps.location, eventView, prevState.savedQuery);
  189. const savedQueryDataset =
  190. decodeScalar(location.query.queryDataset) ?? savedQuery?.queryDataset;
  191. const prevSavedQueryDataset =
  192. decodeScalar(prevProps.location.query.queryDataset) ??
  193. prevState.savedQuery?.queryDataset;
  194. const datasetChanged = !isEqual(savedQueryDataset, prevSavedQueryDataset);
  195. if (
  196. !isAPIPayloadSimilar(currentQuery, prevQuery) ||
  197. this.hasChartParametersChanged(
  198. prevState.eventView,
  199. eventView,
  200. prevYAxisArray,
  201. yAxisArray
  202. ) ||
  203. datasetChanged
  204. ) {
  205. this.canLoadEvents();
  206. }
  207. if (
  208. !isEqual(prevProps.selection.datetime, selection.datetime) ||
  209. !isEqual(prevProps.selection.projects, selection.projects)
  210. ) {
  211. loadOrganizationTags(this.tagsApi, organization.slug, selection);
  212. addRoutePerformanceContext(selection);
  213. }
  214. if (prevState.confirmedQuery !== confirmedQuery) {
  215. this.fetchTotalCount();
  216. }
  217. }
  218. tagsApi: Client = new Client();
  219. hasChartParametersChanged(
  220. prevEventView: EventView,
  221. eventView: EventView,
  222. prevYAxisArray: string[],
  223. yAxisArray: string[]
  224. ) {
  225. if (!isEqual(prevYAxisArray, yAxisArray)) {
  226. return true;
  227. }
  228. const prevDisplay = prevEventView.getDisplayMode();
  229. const display = eventView.getDisplayMode();
  230. return prevDisplay !== display;
  231. }
  232. canLoadEvents = async () => {
  233. const {api, location, organization} = this.props;
  234. const {eventView} = this.state;
  235. let needConfirmation = false;
  236. let confirmedQuery = true;
  237. const currentQuery = eventView.getEventsAPIPayload(location);
  238. const duration = eventView.getDays();
  239. if (duration > 30 && currentQuery.project) {
  240. let projectLength = currentQuery.project.length;
  241. if (
  242. projectLength === 0 ||
  243. (projectLength === 1 && currentQuery.project[0] === '-1')
  244. ) {
  245. try {
  246. const results = await fetchProjectsCount(api, organization.slug);
  247. if (projectLength === 0) {
  248. projectLength = results.myProjects;
  249. } else {
  250. projectLength = results.allProjects;
  251. }
  252. } catch (err) {
  253. // do nothing, so the length is 0 or 1 and the query is assumed safe
  254. }
  255. }
  256. if (projectLength > 10) {
  257. needConfirmation = true;
  258. confirmedQuery = false;
  259. }
  260. }
  261. // Once confirmed, a change of project or datetime will happen before this can set it to false,
  262. // this means a query will still happen even if the new conditions need confirmation
  263. // using a state callback to return this to false
  264. this.setState({needConfirmation, confirmedQuery}, () => {
  265. this.setState({confirmedQuery: false});
  266. });
  267. if (needConfirmation) {
  268. this.openConfirm();
  269. }
  270. };
  271. openConfirm = () => {};
  272. setOpenFunction = ({open}) => {
  273. this.openConfirm = open;
  274. return null;
  275. };
  276. handleConfirmed = () => {
  277. this.setState({needConfirmation: false, confirmedQuery: true}, () => {
  278. this.setState({confirmedQuery: false});
  279. });
  280. };
  281. handleCancelled = () => {
  282. this.setState({needConfirmation: false, confirmedQuery: false});
  283. };
  284. async fetchTotalCount() {
  285. const {api, organization, location} = this.props;
  286. const {eventView, confirmedQuery} = this.state;
  287. if (confirmedQuery === false || !eventView.isValid()) {
  288. return;
  289. }
  290. try {
  291. const totals = await fetchTotalCount(
  292. api,
  293. organization.slug,
  294. eventView.getEventsAPIPayload(location)
  295. );
  296. this.setState({totalValues: totals});
  297. } catch (err) {
  298. Sentry.captureException(err);
  299. }
  300. }
  301. checkEventView() {
  302. const {eventView, splitDecision, savedQueryDataset} = this.state;
  303. const {loading} = this.props;
  304. if (eventView.isValid() || loading) {
  305. return;
  306. }
  307. // If the view is not valid, redirect to a known valid state.
  308. const {location, organization, selection, isHomepage, savedQuery} = this.props;
  309. const value = getSavedQueryDataset(organization, location, savedQuery, splitDecision);
  310. const defaultEventView = hasDatasetSelector(organization)
  311. ? (getSavedQueryWithDataset(DEFAULT_EVENT_VIEW_MAP[value]) as NewQuery)
  312. : DEFAULT_EVENT_VIEW;
  313. const query = isHomepage && savedQuery ? omit(savedQuery, 'id') : defaultEventView;
  314. const nextEventView = EventView.fromNewQueryWithLocation(query, location);
  315. if (nextEventView.project.length === 0 && selection.projects) {
  316. nextEventView.project = selection.projects;
  317. }
  318. if (selection.datetime) {
  319. const {period, utc, start, end} = selection.datetime;
  320. nextEventView.statsPeriod = period ?? undefined;
  321. nextEventView.utc = utc?.toString();
  322. nextEventView.start = normalizeDateTimeString(start);
  323. nextEventView.end = normalizeDateTimeString(end);
  324. }
  325. if (location.query?.query) {
  326. nextEventView.query = decodeScalar(location.query.query, '');
  327. }
  328. if (isHomepage && !this.state.savedQuery) {
  329. this.setState({savedQuery, eventView: nextEventView});
  330. }
  331. browserHistory.replace(
  332. normalizeUrl(
  333. nextEventView.getResultsViewUrlTarget(
  334. organization.slug,
  335. isHomepage,
  336. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  337. )
  338. )
  339. );
  340. }
  341. handleCursor: CursorHandler = (cursor, path, query, _direction) => {
  342. const {router} = this.props;
  343. router.push({
  344. pathname: path,
  345. query: {...query, cursor},
  346. });
  347. // Treat pagination like the user already confirmed the query
  348. if (!this.state.needConfirmation) {
  349. this.handleConfirmed();
  350. }
  351. };
  352. handleChangeShowTags = () => {
  353. const {organization} = this.props;
  354. trackAnalytics('discover_v2.results.toggle_tag_facets', {
  355. organization,
  356. });
  357. this.setState(state => {
  358. const newValue = !state.showTags;
  359. localStorage.setItem(SHOW_TAGS_STORAGE_KEY, newValue ? '1' : '0');
  360. return {...state, showTags: newValue};
  361. });
  362. };
  363. handleSearch = (query: string) => {
  364. const {router, location} = this.props;
  365. const queryParams = normalizeDateTimeParams({
  366. ...(location.query || {}),
  367. query,
  368. });
  369. // do not propagate pagination when making a new search
  370. const searchQueryParams = omit(queryParams, 'cursor');
  371. router.push({
  372. pathname: location.pathname,
  373. query: searchQueryParams,
  374. });
  375. };
  376. handleYAxisChange = (value: string[]) => {
  377. const {router, location} = this.props;
  378. const isDisplayMultiYAxisSupported = MULTI_Y_AXIS_SUPPORTED_DISPLAY_MODES.includes(
  379. location.query.display as DisplayModes
  380. );
  381. const newQuery = {
  382. ...location.query,
  383. yAxis: value.length > 0 ? value : [null],
  384. // If using Multi Y-axis and not in a supported display, change to the default display mode
  385. display:
  386. value.length > 1 && !isDisplayMultiYAxisSupported
  387. ? location.query.display === DisplayModes.DAILYTOP5
  388. ? DisplayModes.DAILY
  389. : DisplayModes.DEFAULT
  390. : location.query.display,
  391. };
  392. router.push({
  393. pathname: location.pathname,
  394. query: newQuery,
  395. });
  396. // Treat axis changing like the user already confirmed the query
  397. if (!this.state.needConfirmation) {
  398. this.handleConfirmed();
  399. }
  400. trackAnalytics('discover_v2.y_axis_change', {
  401. organization: this.props.organization,
  402. y_axis_value: value,
  403. });
  404. };
  405. handleDisplayChange = (value: string) => {
  406. const {router, location} = this.props;
  407. const newQuery = {
  408. ...location.query,
  409. display: value,
  410. };
  411. router.push({
  412. pathname: location.pathname,
  413. query: newQuery,
  414. });
  415. // Treat display changing like the user already confirmed the query
  416. if (!this.state.needConfirmation) {
  417. this.handleConfirmed();
  418. }
  419. };
  420. handleIntervalChange = (value: string | undefined) => {
  421. const {router, location} = this.props;
  422. const newQuery = {
  423. ...location.query,
  424. interval: value,
  425. };
  426. if (location.query.interval !== value) {
  427. router.push({
  428. pathname: location.pathname,
  429. query: newQuery,
  430. });
  431. // Treat display changing like the user already confirmed the query
  432. if (!this.state.needConfirmation) {
  433. this.handleConfirmed();
  434. }
  435. }
  436. };
  437. handleTopEventsChange = (value: string) => {
  438. const {router, location} = this.props;
  439. const newQuery = {
  440. ...location.query,
  441. topEvents: value,
  442. };
  443. router.push({
  444. pathname: location.pathname,
  445. query: newQuery,
  446. });
  447. // Treat display changing like the user already confirmed the query
  448. if (!this.state.needConfirmation) {
  449. this.handleConfirmed();
  450. }
  451. };
  452. getDocumentTitle(): string {
  453. const {organization} = this.props;
  454. const {eventView} = this.state;
  455. if (!eventView) {
  456. return '';
  457. }
  458. return generateTitle({eventView, organization});
  459. }
  460. renderTagsTable() {
  461. const {organization, location} = this.props;
  462. const {eventView, totalValues, confirmedQuery} = this.state;
  463. return (
  464. <Layout.Side>
  465. <Tags
  466. generateUrl={this.generateTagUrl}
  467. totalValues={totalValues}
  468. eventView={eventView}
  469. organization={organization}
  470. location={location}
  471. confirmedQuery={confirmedQuery}
  472. />
  473. </Layout.Side>
  474. );
  475. }
  476. generateTagUrl = (key: string, value: string) => {
  477. const {organization, isHomepage} = this.props;
  478. const {eventView, savedQueryDataset} = this.state;
  479. const url = eventView.getResultsViewUrlTarget(
  480. organization.slug,
  481. isHomepage,
  482. hasDatasetSelector(organization) ? savedQueryDataset : undefined
  483. );
  484. url.query = generateQueryWithTag(url.query, {
  485. key: formatTagKey(key),
  486. value,
  487. });
  488. return url;
  489. };
  490. renderError(error: string) {
  491. if (!error) {
  492. return null;
  493. }
  494. return (
  495. <Alert type="error" showIcon>
  496. {error}
  497. </Alert>
  498. );
  499. }
  500. setError = (error: string, errorCode: number) => {
  501. this.setState({error, errorCode});
  502. };
  503. renderMetricsFallbackBanner() {
  504. const {organization} = this.props;
  505. if (
  506. !organization.features.includes('performance-mep-bannerless-ui') &&
  507. this.state.showMetricsAlert
  508. ) {
  509. return (
  510. <Alert type="info" showIcon>
  511. {t(
  512. "You've navigated to this page from a performance metric widget generated from processed events. The results here only show indexed events."
  513. )}
  514. </Alert>
  515. );
  516. }
  517. if (this.state.showUnparameterizedBanner) {
  518. return (
  519. <Alert type="info" showIcon>
  520. {tct(
  521. 'These are unparameterized transactions. To better organize your transactions, [link:set transaction names manually].',
  522. {
  523. link: (
  524. <ExternalLink href="https://docs.sentry.io/platforms/javascript/tracing/instrumentation/automatic-instrumentation/#beforenavigate" />
  525. ),
  526. }
  527. )}
  528. </Alert>
  529. );
  530. }
  531. return null;
  532. }
  533. renderForcedDatasetBanner() {
  534. const {organization, savedQuery} = this.props;
  535. if (
  536. hasDatasetSelector(organization) &&
  537. this.state.showForcedDatasetAlert &&
  538. (this.state.splitDecision || savedQuery?.datasetSource === DatasetSource.FORCED)
  539. ) {
  540. const splitDecision = this.state.splitDecision ?? savedQuery?.queryDataset;
  541. if (!splitDecision) {
  542. return null;
  543. }
  544. return (
  545. <Alert
  546. type="warning"
  547. showIcon
  548. trailingItems={
  549. <StyledCloseButton
  550. icon={<IconClose size="sm" />}
  551. aria-label={t('Close')}
  552. onClick={() => {
  553. this.setState({showForcedDatasetAlert: false});
  554. }}
  555. size="zero"
  556. borderless
  557. />
  558. }
  559. >
  560. {tct(
  561. "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.",
  562. {splitDecision: DATASET_LABEL_MAP[splitDecision]}
  563. )}
  564. </Alert>
  565. );
  566. }
  567. return null;
  568. }
  569. renderTips() {
  570. const {tips} = this.state;
  571. if (tips) {
  572. return tips.map((tip, index) => (
  573. <Alert type="info" showIcon key={`tip-${index}`}>
  574. <TipContainer dangerouslySetInnerHTML={{__html: marked(tip)}} />
  575. </Alert>
  576. ));
  577. }
  578. return null;
  579. }
  580. setTips = (tips: string[]) => {
  581. // If there are currently no tips set and the new tips are empty, do nothing
  582. // and bail out of an expensive entire table rerender
  583. if (!tips.length && !this.state.tips.length) {
  584. return;
  585. }
  586. this.setState({tips});
  587. };
  588. setSplitDecision = (value?: SavedQueryDatasets) => {
  589. const {eventView} = this.state;
  590. const newEventView = eventView.withDataset(
  591. getDatasetFromLocationOrSavedQueryDataset(undefined, value)
  592. );
  593. this.setState({
  594. splitDecision: value,
  595. savedQueryDataset: value,
  596. eventView: newEventView,
  597. });
  598. };
  599. render() {
  600. const {organization, location, router, selection, api, setSavedQuery, isHomepage} =
  601. this.props;
  602. const {
  603. eventView,
  604. error,
  605. errorCode,
  606. totalValues,
  607. showTags,
  608. confirmedQuery,
  609. savedQuery,
  610. splitDecision,
  611. savedQueryDataset,
  612. } = this.state;
  613. const fields = eventView.hasAggregateField()
  614. ? generateAggregateFields(organization, eventView.fields)
  615. : eventView.fields;
  616. const query = eventView.query;
  617. const title = this.getDocumentTitle();
  618. const yAxisArray = getYAxis(location, eventView, savedQuery);
  619. if (!eventView.isValid()) {
  620. return <LoadingIndicator />;
  621. }
  622. return (
  623. <SentryDocumentTitle title={title} orgSlug={organization.slug}>
  624. <Fragment>
  625. <ResultsHeader
  626. setSavedQuery={setSavedQuery}
  627. errorCode={errorCode}
  628. organization={organization}
  629. location={location}
  630. eventView={eventView}
  631. yAxis={yAxisArray}
  632. router={router}
  633. isHomepage={isHomepage}
  634. />
  635. <Layout.Body>
  636. <CustomMeasurementsProvider organization={organization} selection={selection}>
  637. <Top fullWidth>
  638. {this.renderMetricsFallbackBanner()}
  639. {this.renderError(error)}
  640. {this.renderTips()}
  641. {this.renderForcedDatasetBanner()}
  642. <Wrapper>
  643. <Feature
  644. organization={organization}
  645. features="performance-discover-dataset-selector"
  646. >
  647. {({hasFeature}) =>
  648. hasFeature && (
  649. <DatasetSelector
  650. isHomepage={isHomepage}
  651. savedQuery={savedQuery}
  652. splitDecision={splitDecision}
  653. eventView={eventView}
  654. />
  655. )
  656. }
  657. </Feature>
  658. <PageFilterBar condensed>
  659. <ProjectPageFilter />
  660. <EnvironmentPageFilter />
  661. <DatePageFilter />
  662. </PageFilterBar>
  663. </Wrapper>
  664. <CustomMeasurementsContext.Consumer>
  665. {contextValue => (
  666. <StyledSearchBar
  667. searchSource="eventsv2"
  668. organization={organization}
  669. projectIds={eventView.project}
  670. query={query}
  671. fields={fields}
  672. onSearch={this.handleSearch}
  673. maxQueryLength={MAX_QUERY_LENGTH}
  674. customMeasurements={contextValue?.customMeasurements ?? undefined}
  675. dataset={eventView.dataset}
  676. />
  677. )}
  678. </CustomMeasurementsContext.Consumer>
  679. <SampleDataAlert query={query} />
  680. <MetricsCardinalityProvider
  681. organization={organization}
  682. location={location}
  683. >
  684. <ResultsChart
  685. api={api}
  686. router={router}
  687. organization={organization}
  688. eventView={eventView}
  689. location={location}
  690. onAxisChange={this.handleYAxisChange}
  691. onDisplayChange={this.handleDisplayChange}
  692. onTopEventsChange={this.handleTopEventsChange}
  693. onIntervalChange={this.handleIntervalChange}
  694. total={totalValues}
  695. confirmedQuery={confirmedQuery}
  696. yAxis={yAxisArray}
  697. />
  698. </MetricsCardinalityProvider>
  699. </Top>
  700. <Layout.Main fullWidth={!showTags}>
  701. <Table
  702. organization={organization}
  703. eventView={eventView}
  704. location={location}
  705. title={title}
  706. setError={this.setError}
  707. onChangeShowTags={this.handleChangeShowTags}
  708. showTags={showTags}
  709. confirmedQuery={confirmedQuery}
  710. onCursor={this.handleCursor}
  711. isHomepage={isHomepage}
  712. setTips={this.setTips}
  713. queryDataset={savedQueryDataset}
  714. setSplitDecision={(value?: SavedQueryDatasets) => {
  715. if (
  716. organization.features.includes(
  717. 'performance-discover-dataset-selector'
  718. ) &&
  719. value !== SavedQueryDatasets.DISCOVER &&
  720. value !== savedQuery?.dataset
  721. ) {
  722. this.setSplitDecision(value);
  723. }
  724. }}
  725. dataset={
  726. organization.features.includes(
  727. 'performance-discover-dataset-selector'
  728. )
  729. ? eventView.dataset
  730. : undefined
  731. }
  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. `;