landing.tsx 9.4 KB

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