results.tsx 32 KB

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