landing.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 {trackAnalyticsEvent} from 'sentry/utils/analytics';
  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} = this.props;
  143. trackAnalyticsEvent({
  144. eventKey: 'discover_v2.change_sort',
  145. eventName: 'Discoverv2: Sort By Changed',
  146. organization_id: parseInt(this.props.organization.id, 10),
  147. sort: value,
  148. });
  149. browserHistory.push({
  150. pathname: location.pathname,
  151. query: {
  152. ...location.query,
  153. cursor: undefined,
  154. sort: value,
  155. },
  156. });
  157. };
  158. renderBanner() {
  159. const {location, organization} = this.props;
  160. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  161. const to = eventView.getResultsViewUrlTarget(organization.slug);
  162. const resultsUrl = `${to.pathname}?${stringify(to.query)}`;
  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. placement="bottom right"
  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. render() {
  226. const {location, organization} = this.props;
  227. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  228. const to = eventView.getResultsViewUrlTarget(organization.slug);
  229. return (
  230. <Feature
  231. organization={organization}
  232. features={['discover-query']}
  233. renderDisabled={this.renderNoAccess}
  234. >
  235. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  236. <StyledPageContent>
  237. <NoProjectMessage organization={organization}>
  238. <PageContent>
  239. <StyledPageHeader>
  240. <Title>
  241. <GuideAnchor target="discover_landing_header">
  242. {t('Discover')}
  243. </GuideAnchor>
  244. </Title>
  245. <StyledButton
  246. data-test-id="build-new-query"
  247. to={to}
  248. priority="primary"
  249. onClick={() => {
  250. trackAnalyticsEvent({
  251. eventKey: 'discover_v2.build_new_query',
  252. eventName: 'Discoverv2: Build a new Discover Query',
  253. organization_id: parseInt(this.props.organization.id, 10),
  254. });
  255. }}
  256. >
  257. {t('Build a new query')}
  258. </StyledButton>
  259. </StyledPageHeader>
  260. {this.renderBanner()}
  261. {this.renderActions()}
  262. {this.renderComponent()}
  263. </PageContent>
  264. </NoProjectMessage>
  265. </StyledPageContent>
  266. </SentryDocumentTitle>
  267. </Feature>
  268. );
  269. }
  270. }
  271. const StyledPageContent = styled(PageContent)`
  272. padding: 0;
  273. `;
  274. const PrebuiltSwitch = styled('div')`
  275. display: flex;
  276. `;
  277. const SwitchLabel = styled('div')`
  278. padding-right: 8px;
  279. `;
  280. const StyledPageHeader = styled('div')`
  281. display: flex;
  282. align-items: flex-end;
  283. font-size: ${p => p.theme.headerFontSize};
  284. color: ${p => p.theme.textColor};
  285. justify-content: space-between;
  286. margin-bottom: ${space(2)};
  287. `;
  288. const StyledSearchBar = styled(SearchBar)`
  289. flex-grow: 1;
  290. `;
  291. const StyledActions = styled('div')`
  292. display: grid;
  293. gap: ${space(2)};
  294. grid-template-columns: auto max-content min-content;
  295. align-items: center;
  296. margin-bottom: ${space(2)};
  297. @media (max-width: ${p => p.theme.breakpoints.small}) {
  298. grid-template-columns: auto;
  299. }
  300. `;
  301. const StyledButton = styled(Button)`
  302. white-space: nowrap;
  303. `;
  304. export default withOrganization(DiscoverLanding);
  305. export {DiscoverLanding};