landing.tsx 9.8 KB

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