landing.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 Button from 'sentry/components/button';
  11. import CompactSelect from 'sentry/components/forms/compactSelect';
  12. import {Title} from 'sentry/components/layouts/thirds';
  13. import NoProjectMessage from 'sentry/components/noProjectMessage';
  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 {PageContent} from 'sentry/styles/organization';
  19. import space from 'sentry/styles/space';
  20. import {Organization, SavedQuery, SelectValue} from 'sentry/types';
  21. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  22. import EventView from 'sentry/utils/discover/eventView';
  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. return <Banner organization={organization} resultsUrl={resultsUrl} />;
  159. }
  160. renderActions() {
  161. const activeSort = this.getActiveSort();
  162. const {renderPrebuilt, savedQueries} = this.state;
  163. return (
  164. <StyledActions>
  165. <StyledSearchBar
  166. defaultQuery=""
  167. query={this.getSavedQuerySearchQuery()}
  168. placeholder={t('Search saved queries')}
  169. onSearch={this.handleSearchQuery}
  170. />
  171. <PrebuiltSwitch>
  172. <SwitchLabel>Show Prebuilt</SwitchLabel>
  173. <Switch
  174. isActive={renderPrebuilt}
  175. isDisabled={renderPrebuilt && (savedQueries ?? []).length === 0}
  176. size="lg"
  177. toggle={this.togglePrebuilt}
  178. />
  179. </PrebuiltSwitch>
  180. <CompactSelect
  181. triggerProps={{prefix: t('Sort By')}}
  182. value={activeSort.value}
  183. options={SORT_OPTIONS}
  184. onChange={opt => this.handleSortChange(opt.value)}
  185. placement="bottom right"
  186. />
  187. </StyledActions>
  188. );
  189. }
  190. togglePrebuilt = () => {
  191. const {renderPrebuilt} = this.state;
  192. this.setState({renderPrebuilt: !renderPrebuilt}, () => {
  193. setRenderPrebuilt(!renderPrebuilt);
  194. this.fetchData({reloading: true});
  195. });
  196. };
  197. renderNoAccess() {
  198. return (
  199. <PageContent>
  200. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  201. </PageContent>
  202. );
  203. }
  204. renderBody() {
  205. const {location, organization, router} = this.props;
  206. const {savedQueries, savedQueriesPageLinks, renderPrebuilt} = this.state;
  207. return (
  208. <QueryList
  209. pageLinks={savedQueriesPageLinks}
  210. savedQueries={savedQueries ?? []}
  211. savedQuerySearchQuery={this.getSavedQuerySearchQuery()}
  212. renderPrebuilt={renderPrebuilt}
  213. location={location}
  214. organization={organization}
  215. onQueryChange={this.handleQueryChange}
  216. router={router}
  217. />
  218. );
  219. }
  220. render() {
  221. const {location, organization} = this.props;
  222. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  223. const to = eventView.getResultsViewUrlTarget(organization.slug);
  224. return (
  225. <Feature
  226. organization={organization}
  227. features={['discover-query']}
  228. renderDisabled={this.renderNoAccess}
  229. >
  230. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  231. <StyledPageContent>
  232. <NoProjectMessage organization={organization}>
  233. <PageContent>
  234. <StyledPageHeader>
  235. <Title>
  236. <GuideAnchor target="discover_landing_header">
  237. {t('Discover')}
  238. </GuideAnchor>
  239. </Title>
  240. <StyledButton
  241. data-test-id="build-new-query"
  242. to={to}
  243. priority="primary"
  244. onClick={() => {
  245. trackAdvancedAnalyticsEvent('discover_v2.build_new_query', {
  246. organization,
  247. });
  248. }}
  249. >
  250. {t('Build a new query')}
  251. </StyledButton>
  252. </StyledPageHeader>
  253. {this.renderBanner()}
  254. {this.renderActions()}
  255. {this.renderComponent()}
  256. </PageContent>
  257. </NoProjectMessage>
  258. </StyledPageContent>
  259. </SentryDocumentTitle>
  260. </Feature>
  261. );
  262. }
  263. }
  264. const StyledPageContent = styled(PageContent)`
  265. padding: 0;
  266. `;
  267. const PrebuiltSwitch = styled('div')`
  268. display: flex;
  269. `;
  270. const SwitchLabel = styled('div')`
  271. padding-right: 8px;
  272. `;
  273. const StyledPageHeader = styled('div')`
  274. display: flex;
  275. align-items: flex-end;
  276. font-size: ${p => p.theme.headerFontSize};
  277. color: ${p => p.theme.textColor};
  278. justify-content: space-between;
  279. margin-bottom: ${space(2)};
  280. `;
  281. const StyledSearchBar = styled(SearchBar)`
  282. flex-grow: 1;
  283. `;
  284. const StyledActions = styled('div')`
  285. display: grid;
  286. gap: ${space(2)};
  287. grid-template-columns: auto max-content min-content;
  288. align-items: center;
  289. margin-bottom: ${space(2)};
  290. @media (max-width: ${p => p.theme.breakpoints.small}) {
  291. grid-template-columns: auto;
  292. }
  293. `;
  294. const StyledButton = styled(Button)`
  295. white-space: nowrap;
  296. `;
  297. export default withOrganization(DiscoverLanding);
  298. export {DiscoverLanding};