landing.tsx 9.8 KB

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