landing.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. import * as ReactRouter from 'react-router';
  2. import {Params} from 'react-router/lib/Router';
  3. import styled from '@emotion/styled';
  4. import {Location} from 'history';
  5. import isEqual from 'lodash/isEqual';
  6. import pick from 'lodash/pick';
  7. import {stringify} from 'query-string';
  8. import Feature from 'app/components/acl/feature';
  9. import Alert from 'app/components/alert';
  10. import GuideAnchor from 'app/components/assistant/guideAnchor';
  11. import AsyncComponent from 'app/components/asyncComponent';
  12. import Button from 'app/components/button';
  13. import DropdownControl, {DropdownItem} from 'app/components/dropdownControl';
  14. import LightWeightNoProjectMessage from 'app/components/lightWeightNoProjectMessage';
  15. import SearchBar from 'app/components/searchBar';
  16. import SentryDocumentTitle from 'app/components/sentryDocumentTitle';
  17. import Switch from 'app/components/switchButton';
  18. import {t} from 'app/locale';
  19. import ConfigStore from 'app/stores/configStore';
  20. import {PageContent} from 'app/styles/organization';
  21. import space from 'app/styles/space';
  22. import {Organization, SavedQuery, SelectValue} from 'app/types';
  23. import {trackAnalyticsEvent} from 'app/utils/analytics';
  24. import EventView from 'app/utils/discover/eventView';
  25. import {decodeScalar} from 'app/utils/queryString';
  26. import withOrganization from 'app/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. ];
  39. type Props = {
  40. organization: Organization;
  41. location: Location;
  42. router: ReactRouter.InjectedRouter;
  43. params: Params;
  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: 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. ReactRouter.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} = this.props;
  145. trackAnalyticsEvent({
  146. eventKey: 'discover_v2.change_sort',
  147. eventName: 'Discoverv2: Sort By Changed',
  148. organization_id: parseInt(this.props.organization.id, 10),
  149. sort: value,
  150. });
  151. ReactRouter.browserHistory.push({
  152. pathname: location.pathname,
  153. query: {
  154. ...location.query,
  155. cursor: undefined,
  156. sort: value,
  157. },
  158. });
  159. };
  160. renderBanner() {
  161. const {location, organization} = this.props;
  162. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  163. const to = eventView.getResultsViewUrlTarget(organization.slug);
  164. const resultsUrl = `${to.pathname}?${stringify(to.query)}`;
  165. return <Banner organization={organization} resultsUrl={resultsUrl} />;
  166. }
  167. renderActions() {
  168. const activeSort = this.getActiveSort();
  169. const {renderPrebuilt, savedQueries} = this.state;
  170. return (
  171. <StyledActions>
  172. <StyledSearchBar
  173. defaultQuery=""
  174. query={this.getSavedQuerySearchQuery()}
  175. placeholder={t('Search saved queries')}
  176. onSearch={this.handleSearchQuery}
  177. />
  178. <PrebuiltSwitch>
  179. <SwitchLabel>Show Prebuilt</SwitchLabel>
  180. <Switch
  181. isActive={renderPrebuilt}
  182. isDisabled={renderPrebuilt && (savedQueries ?? []).length === 0}
  183. size="lg"
  184. toggle={this.togglePrebuilt}
  185. />
  186. </PrebuiltSwitch>
  187. <DropdownControl buttonProps={{prefix: t('Sort By')}} label={activeSort.label}>
  188. {SORT_OPTIONS.map(({label, value}) => (
  189. <DropdownItem
  190. key={value}
  191. onSelect={this.handleSortChange}
  192. eventKey={value}
  193. isActive={value === activeSort.value}
  194. >
  195. {label}
  196. </DropdownItem>
  197. ))}
  198. </DropdownControl>
  199. </StyledActions>
  200. );
  201. }
  202. togglePrebuilt = () => {
  203. const {renderPrebuilt} = this.state;
  204. this.setState({renderPrebuilt: !renderPrebuilt}, () => {
  205. setRenderPrebuilt(!renderPrebuilt);
  206. this.fetchData({reloading: true});
  207. });
  208. };
  209. onGoLegacyDiscover = () => {
  210. localStorage.setItem('discover:version', '1');
  211. const user = ConfigStore.get('user');
  212. trackAnalyticsEvent({
  213. eventKey: 'discover_v2.opt_out',
  214. eventName: 'Discoverv2: Go to discover',
  215. organization_id: parseInt(this.props.organization.id, 10),
  216. user_id: parseInt(user.id, 10),
  217. });
  218. };
  219. renderNoAccess() {
  220. return (
  221. <PageContent>
  222. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  223. </PageContent>
  224. );
  225. }
  226. renderBody() {
  227. const {location, organization} = this.props;
  228. const {savedQueries, savedQueriesPageLinks, renderPrebuilt} = this.state;
  229. return (
  230. <QueryList
  231. pageLinks={savedQueriesPageLinks}
  232. savedQueries={savedQueries ?? []}
  233. savedQuerySearchQuery={this.getSavedQuerySearchQuery()}
  234. renderPrebuilt={renderPrebuilt}
  235. location={location}
  236. organization={organization}
  237. onQueryChange={this.handleQueryChange}
  238. />
  239. );
  240. }
  241. render() {
  242. const {location, organization} = this.props;
  243. const eventView = EventView.fromNewQueryWithLocation(DEFAULT_EVENT_VIEW, location);
  244. const to = eventView.getResultsViewUrlTarget(organization.slug);
  245. return (
  246. <Feature
  247. organization={organization}
  248. features={['discover-query']}
  249. renderDisabled={this.renderNoAccess}
  250. >
  251. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  252. <StyledPageContent>
  253. <LightWeightNoProjectMessage organization={organization}>
  254. <PageContent>
  255. <StyledPageHeader>
  256. <GuideAnchor target="discover_landing_header">
  257. {t('Discover')}
  258. </GuideAnchor>
  259. <StyledButton
  260. data-test-id="build-new-query"
  261. to={to}
  262. priority="primary"
  263. onClick={() => {
  264. trackAnalyticsEvent({
  265. eventKey: 'discover_v2.build_new_query',
  266. eventName: 'Discoverv2: Build a new Discover Query',
  267. organization_id: parseInt(this.props.organization.id, 10),
  268. });
  269. }}
  270. >
  271. {t('Build a new query')}
  272. </StyledButton>
  273. </StyledPageHeader>
  274. {this.renderBanner()}
  275. {this.renderActions()}
  276. {this.renderComponent()}
  277. </PageContent>
  278. </LightWeightNoProjectMessage>
  279. </StyledPageContent>
  280. </SentryDocumentTitle>
  281. </Feature>
  282. );
  283. }
  284. }
  285. const StyledPageContent = styled(PageContent)`
  286. padding: 0;
  287. `;
  288. const PrebuiltSwitch = styled('div')`
  289. display: flex;
  290. `;
  291. const SwitchLabel = styled('div')`
  292. padding-right: 8px;
  293. `;
  294. export const StyledPageHeader = styled('div')`
  295. display: flex;
  296. align-items: flex-end;
  297. font-size: ${p => p.theme.headerFontSize};
  298. color: ${p => p.theme.textColor};
  299. justify-content: space-between;
  300. margin-bottom: ${space(2)};
  301. `;
  302. const StyledSearchBar = styled(SearchBar)`
  303. flex-grow: 1;
  304. `;
  305. const StyledActions = styled('div')`
  306. display: grid;
  307. grid-gap: ${space(2)};
  308. grid-template-columns: auto max-content min-content;
  309. align-items: center;
  310. margin-bottom: ${space(2)};
  311. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  312. grid-template-columns: auto;
  313. }
  314. `;
  315. const StyledButton = styled(Button)`
  316. white-space: nowrap;
  317. `;
  318. export default withOrganization(DiscoverLanding);
  319. export {DiscoverLanding};