landing.tsx 11 KB

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