landing.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 DropdownControl, {DropdownItem} from 'sentry/components/dropdownControl';
  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. <DropdownControl buttonProps={{prefix: t('Sort By')}} label={activeSort.label}>
  186. {SORT_OPTIONS.map(({label, value}) => (
  187. <DropdownItem
  188. key={value}
  189. onSelect={this.handleSortChange}
  190. eventKey={value}
  191. isActive={value === activeSort.value}
  192. >
  193. {label}
  194. </DropdownItem>
  195. ))}
  196. </DropdownControl>
  197. </StyledActions>
  198. );
  199. }
  200. togglePrebuilt = () => {
  201. const {renderPrebuilt} = this.state;
  202. this.setState({renderPrebuilt: !renderPrebuilt}, () => {
  203. setRenderPrebuilt(!renderPrebuilt);
  204. this.fetchData({reloading: true});
  205. });
  206. };
  207. renderNoAccess() {
  208. return (
  209. <PageContent>
  210. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  211. </PageContent>
  212. );
  213. }
  214. renderBody() {
  215. const {location, organization, router} = this.props;
  216. const {savedQueries, savedQueriesPageLinks, renderPrebuilt} = this.state;
  217. return (
  218. <QueryList
  219. pageLinks={savedQueriesPageLinks}
  220. savedQueries={savedQueries ?? []}
  221. savedQuerySearchQuery={this.getSavedQuerySearchQuery()}
  222. renderPrebuilt={renderPrebuilt}
  223. location={location}
  224. organization={organization}
  225. onQueryChange={this.handleQueryChange}
  226. router={router}
  227. />
  228. );
  229. }
  230. render() {
  231. const {location, organization} = this.props;
  232. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  233. const to = eventView.getResultsViewUrlTarget(organization.slug);
  234. return (
  235. <Feature
  236. organization={organization}
  237. features={['discover-query']}
  238. renderDisabled={this.renderNoAccess}
  239. >
  240. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  241. <StyledPageContent>
  242. <NoProjectMessage organization={organization}>
  243. <PageContent>
  244. <StyledPageHeader>
  245. <Title>
  246. <GuideAnchor target="discover_landing_header">
  247. {t('Discover')}
  248. </GuideAnchor>
  249. </Title>
  250. <StyledButton
  251. data-test-id="build-new-query"
  252. to={to}
  253. priority="primary"
  254. onClick={() => {
  255. trackAnalyticsEvent({
  256. eventKey: 'discover_v2.build_new_query',
  257. eventName: 'Discoverv2: Build a new Discover Query',
  258. organization_id: parseInt(this.props.organization.id, 10),
  259. });
  260. }}
  261. >
  262. {t('Build a new query')}
  263. </StyledButton>
  264. </StyledPageHeader>
  265. {this.renderBanner()}
  266. {this.renderActions()}
  267. {this.renderComponent()}
  268. </PageContent>
  269. </NoProjectMessage>
  270. </StyledPageContent>
  271. </SentryDocumentTitle>
  272. </Feature>
  273. );
  274. }
  275. }
  276. const StyledPageContent = styled(PageContent)`
  277. padding: 0;
  278. `;
  279. const PrebuiltSwitch = styled('div')`
  280. display: flex;
  281. `;
  282. const SwitchLabel = styled('div')`
  283. padding-right: 8px;
  284. `;
  285. const StyledPageHeader = styled('div')`
  286. display: flex;
  287. align-items: flex-end;
  288. font-size: ${p => p.theme.headerFontSize};
  289. color: ${p => p.theme.textColor};
  290. justify-content: space-between;
  291. margin-bottom: ${space(2)};
  292. `;
  293. const StyledSearchBar = styled(SearchBar)`
  294. flex-grow: 1;
  295. `;
  296. const StyledActions = styled('div')`
  297. display: grid;
  298. gap: ${space(2)};
  299. grid-template-columns: auto max-content min-content;
  300. align-items: center;
  301. margin-bottom: ${space(2)};
  302. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  303. grid-template-columns: auto;
  304. }
  305. `;
  306. const StyledButton = styled(Button)`
  307. white-space: nowrap;
  308. `;
  309. export default withOrganization(DiscoverLanding);
  310. export {DiscoverLanding};