landing.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import {browserHistory, RouteComponentProps} from 'react-router';
  2. import styled from '@emotion/styled';
  3. import isEqual from 'lodash/isEqual';
  4. import pick from 'lodash/pick';
  5. import {stringify} from 'query-string';
  6. import Feature from 'sentry/components/acl/feature';
  7. import {Alert} from 'sentry/components/alert';
  8. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  9. import AsyncComponent from 'sentry/components/asyncComponent';
  10. import Breadcrumbs from 'sentry/components/breadcrumbs';
  11. import {Button} from 'sentry/components/button';
  12. import {CompactSelect} from 'sentry/components/compactSelect';
  13. import * as Layout from 'sentry/components/layouts/thirds';
  14. import SearchBar from 'sentry/components/searchBar';
  15. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  16. import Switch from 'sentry/components/switchButton';
  17. import {t} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import {Organization, SavedQuery, SelectValue} from 'sentry/types';
  20. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  21. import EventView from 'sentry/utils/discover/eventView';
  22. import {getDiscoverLandingUrl} from 'sentry/utils/discover/urls';
  23. import {decodeScalar} from 'sentry/utils/queryString';
  24. import withOrganization from 'sentry/utils/withOrganization';
  25. import Banner from './banner';
  26. import {DEFAULT_EVENT_VIEW} from './data';
  27. import QueryList from './queryList';
  28. import {getPrebuiltQueries, setRenderPrebuilt, shouldRenderPrebuilt} from './utils';
  29. const SORT_OPTIONS: SelectValue<string>[] = [
  30. {label: t('My Queries'), value: 'myqueries'},
  31. {label: t('Recently Edited'), value: '-dateUpdated'},
  32. {label: t('Query Name (A-Z)'), value: 'name'},
  33. {label: t('Date Created (Newest)'), value: '-dateCreated'},
  34. {label: t('Date Created (Oldest)'), value: 'dateCreated'},
  35. {label: t('Most Outdated'), value: 'dateUpdated'},
  36. {label: t('Most Popular'), value: 'mostPopular'},
  37. {label: t('Recently Viewed'), value: 'recentlyViewed'},
  38. ];
  39. type Props = {
  40. organization: Organization;
  41. } & RouteComponentProps<{}, {}> &
  42. AsyncComponent['props'];
  43. type State = {
  44. savedQueries: SavedQuery[] | null;
  45. savedQueriesPageLinks: string;
  46. } & AsyncComponent['state'];
  47. class DiscoverLanding extends AsyncComponent<Props, State> {
  48. state: State = {
  49. // AsyncComponent state
  50. loading: true,
  51. reloading: false,
  52. error: false,
  53. errors: {},
  54. // local component state
  55. renderPrebuilt: shouldRenderPrebuilt(),
  56. savedQueries: null,
  57. savedQueriesPageLinks: '',
  58. };
  59. shouldReload = true;
  60. getSavedQuerySearchQuery(): string {
  61. const {location} = this.props;
  62. return decodeScalar(location.query.query, '').trim();
  63. }
  64. getActiveSort() {
  65. const {location} = this.props;
  66. const urlSort = decodeScalar(location.query.sort, 'myqueries');
  67. return SORT_OPTIONS.find(item => item.value === urlSort) || SORT_OPTIONS[0];
  68. }
  69. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  70. const {organization, location} = this.props;
  71. const views = getPrebuiltQueries(organization);
  72. const searchQuery = this.getSavedQuerySearchQuery();
  73. const cursor = decodeScalar(location.query.cursor);
  74. let perPage = 9;
  75. const canRenderPrebuilt = this.state
  76. ? this.state.renderPrebuilt
  77. : shouldRenderPrebuilt();
  78. if (!cursor && canRenderPrebuilt) {
  79. // invariant: we're on the first page
  80. if (searchQuery && searchQuery.length > 0) {
  81. const needleSearch = searchQuery.toLowerCase();
  82. const numOfPrebuiltQueries = views.reduce((sum, view) => {
  83. const eventView = EventView.fromNewQueryWithLocation(view, location);
  84. // if a search is performed on the list of queries, we filter
  85. // on the pre-built queries
  86. if (eventView.name && eventView.name.toLowerCase().includes(needleSearch)) {
  87. return sum + 1;
  88. }
  89. return sum;
  90. }, 0);
  91. perPage = Math.max(1, perPage - numOfPrebuiltQueries);
  92. } else {
  93. perPage = Math.max(1, perPage - views.length);
  94. }
  95. }
  96. const queryParams: Props['location']['query'] = {
  97. cursor,
  98. query: `version:2 name:"${searchQuery}"`,
  99. per_page: perPage.toString(),
  100. sortBy: this.getActiveSort().value,
  101. };
  102. if (!cursor) {
  103. delete queryParams.cursor;
  104. }
  105. return [
  106. [
  107. 'savedQueries',
  108. `/organizations/${organization.slug}/discover/saved/`,
  109. {
  110. query: queryParams,
  111. },
  112. ],
  113. ];
  114. }
  115. componentDidUpdate(prevProps: Props) {
  116. const PAYLOAD_KEYS = ['sort', 'cursor', 'query'] as const;
  117. const payloadKeysChanged = !isEqual(
  118. pick(prevProps.location.query, PAYLOAD_KEYS),
  119. pick(this.props.location.query, PAYLOAD_KEYS)
  120. );
  121. // if any of the query strings relevant for the payload has changed,
  122. // we re-fetch data
  123. if (payloadKeysChanged) {
  124. this.fetchData();
  125. }
  126. }
  127. handleQueryChange = () => {
  128. this.fetchData({reloading: true});
  129. };
  130. handleSearchQuery = (searchQuery: string) => {
  131. const {location} = this.props;
  132. browserHistory.push({
  133. pathname: location.pathname,
  134. query: {
  135. ...location.query,
  136. cursor: undefined,
  137. query: String(searchQuery).trim() || undefined,
  138. },
  139. });
  140. };
  141. handleSortChange = (value: string) => {
  142. const {location, organization} = this.props;
  143. trackAdvancedAnalyticsEvent('discover_v2.change_sort', {organization, sort: value});
  144. browserHistory.push({
  145. pathname: location.pathname,
  146. query: {
  147. ...location.query,
  148. cursor: undefined,
  149. sort: value,
  150. },
  151. });
  152. };
  153. renderBanner() {
  154. const {location, organization} = this.props;
  155. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  156. const to = eventView.getResultsViewUrlTarget(organization.slug);
  157. const resultsUrl = `${to.pathname}?${stringify(to.query)}`;
  158. if (organization.features.includes('discover-query-builder-as-landing-page')) {
  159. return null;
  160. }
  161. return <Banner organization={organization} resultsUrl={resultsUrl} />;
  162. }
  163. renderActions() {
  164. const activeSort = this.getActiveSort();
  165. const {renderPrebuilt, savedQueries} = this.state;
  166. return (
  167. <StyledActions>
  168. <StyledSearchBar
  169. defaultQuery=""
  170. query={this.getSavedQuerySearchQuery()}
  171. placeholder={t('Search saved queries')}
  172. onSearch={this.handleSearchQuery}
  173. />
  174. <PrebuiltSwitch>
  175. Show Prebuilt
  176. <Switch
  177. isActive={renderPrebuilt}
  178. isDisabled={renderPrebuilt && (savedQueries ?? []).length === 0}
  179. size="lg"
  180. toggle={this.togglePrebuilt}
  181. />
  182. </PrebuiltSwitch>
  183. <CompactSelect
  184. triggerProps={{prefix: t('Sort By')}}
  185. value={activeSort.value}
  186. options={SORT_OPTIONS}
  187. onChange={opt => this.handleSortChange(opt.value)}
  188. position="bottom-end"
  189. />
  190. </StyledActions>
  191. );
  192. }
  193. togglePrebuilt = () => {
  194. const {renderPrebuilt} = this.state;
  195. this.setState({renderPrebuilt: !renderPrebuilt}, () => {
  196. setRenderPrebuilt(!renderPrebuilt);
  197. this.fetchData({reloading: true});
  198. });
  199. };
  200. renderNoAccess() {
  201. return (
  202. <Layout.Page withPadding>
  203. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  204. </Layout.Page>
  205. );
  206. }
  207. renderBody() {
  208. const {location, organization, router} = this.props;
  209. const {savedQueries, savedQueriesPageLinks, renderPrebuilt} = this.state;
  210. return (
  211. <QueryList
  212. pageLinks={savedQueriesPageLinks}
  213. savedQueries={savedQueries ?? []}
  214. savedQuerySearchQuery={this.getSavedQuerySearchQuery()}
  215. renderPrebuilt={renderPrebuilt}
  216. location={location}
  217. organization={organization}
  218. onQueryChange={this.handleQueryChange}
  219. router={router}
  220. />
  221. );
  222. }
  223. renderBreadcrumbs() {
  224. return (
  225. <Breadcrumbs
  226. crumbs={[
  227. {
  228. key: 'discover-homepage',
  229. label: t('Discover'),
  230. to: getDiscoverLandingUrl(this.props.organization),
  231. },
  232. {
  233. key: 'discover-saved-queries',
  234. label: t('Saved Queries'),
  235. },
  236. ]}
  237. />
  238. );
  239. }
  240. render() {
  241. const {location, organization} = this.props;
  242. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  243. const to = organization.features.includes('discover-query-builder-as-landing-page')
  244. ? `/organizations/${organization.slug}/discover/homepage/`
  245. : eventView.getResultsViewUrlTarget(organization.slug);
  246. return (
  247. <Feature
  248. organization={organization}
  249. features={['discover-query']}
  250. renderDisabled={this.renderNoAccess}
  251. >
  252. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  253. <Layout.Page>
  254. <Layout.Header>
  255. <Layout.HeaderContent>
  256. {organization.features.includes(
  257. 'discover-query-builder-as-landing-page'
  258. ) ? (
  259. this.renderBreadcrumbs()
  260. ) : (
  261. <Layout.Title>
  262. <GuideAnchor target="discover_landing_header">
  263. {t('Discover')}
  264. </GuideAnchor>
  265. </Layout.Title>
  266. )}
  267. </Layout.HeaderContent>
  268. <Layout.HeaderActions>
  269. <Button
  270. data-test-id="build-new-query"
  271. to={to}
  272. size="sm"
  273. priority="primary"
  274. onClick={() => {
  275. trackAdvancedAnalyticsEvent('discover_v2.build_new_query', {
  276. organization,
  277. });
  278. }}
  279. >
  280. {t('Build a new query')}
  281. </Button>
  282. </Layout.HeaderActions>
  283. </Layout.Header>
  284. <Layout.Body>
  285. <Layout.Main fullWidth>
  286. {this.renderBanner()}
  287. {this.renderActions()}
  288. {this.renderComponent()}
  289. </Layout.Main>
  290. </Layout.Body>
  291. </Layout.Page>
  292. </SentryDocumentTitle>
  293. </Feature>
  294. );
  295. }
  296. }
  297. const PrebuiltSwitch = styled('label')`
  298. display: flex;
  299. align-items: center;
  300. gap: ${space(1.5)};
  301. font-weight: normal;
  302. margin: 0;
  303. `;
  304. const StyledSearchBar = styled(SearchBar)`
  305. flex-grow: 1;
  306. `;
  307. const StyledActions = styled('div')`
  308. display: grid;
  309. gap: ${space(2)};
  310. grid-template-columns: auto max-content min-content;
  311. align-items: center;
  312. margin-bottom: ${space(2)};
  313. @media (max-width: ${p => p.theme.breakpoints.small}) {
  314. grid-template-columns: auto;
  315. }
  316. `;
  317. export default withOrganization(DiscoverLanding);
  318. export {DiscoverLanding};