landing.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 {makeDiscoverPathname} from 'sentry/views/discover/pathnames';
  26. import {getSavedQueryWithDataset} from 'sentry/views/discover/savedQuery/utils';
  27. import QueryList from './queryList';
  28. import {getPrebuiltQueries, setRenderPrebuilt, shouldRenderPrebuilt} from './utils';
  29. const SORT_OPTIONS: Array<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. DeprecatedAsyncComponent['props'];
  43. type State = {
  44. savedQueries: SavedQuery[] | null;
  45. savedQueriesPageLinks: string;
  46. } & DeprecatedAsyncComponent['state'];
  47. class DiscoverLanding extends DeprecatedAsyncComponent<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<DeprecatedAsyncComponent['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 newQuery = organization.features.includes(
  84. 'performance-discover-dataset-selector'
  85. )
  86. ? (getSavedQueryWithDataset(view) as NewQuery)
  87. : view;
  88. const eventView = EventView.fromNewQueryWithLocation(newQuery, location);
  89. // if a search is performed on the list of queries, we filter
  90. // on the pre-built queries
  91. if (eventView.name?.toLowerCase().includes(needleSearch)) {
  92. return sum + 1;
  93. }
  94. return sum;
  95. }, 0);
  96. perPage = Math.max(1, perPage - numOfPrebuiltQueries);
  97. } else {
  98. perPage = Math.max(1, perPage - views.length);
  99. }
  100. }
  101. const queryParams: Props['location']['query'] = {
  102. cursor,
  103. query: `version:2 name:"${searchQuery}"`,
  104. per_page: perPage.toString(),
  105. sortBy: this.getActiveSort()!.value,
  106. };
  107. if (!cursor) {
  108. delete queryParams.cursor;
  109. }
  110. return [
  111. [
  112. 'savedQueries',
  113. `/organizations/${organization.slug}/discover/saved/`,
  114. {
  115. query: queryParams,
  116. },
  117. ],
  118. ];
  119. }
  120. componentDidUpdate(prevProps: Props) {
  121. const PAYLOAD_KEYS = ['sort', 'cursor', 'query'] as const;
  122. const payloadKeysChanged = !isEqual(
  123. pick(prevProps.location.query, PAYLOAD_KEYS),
  124. pick(this.props.location.query, PAYLOAD_KEYS)
  125. );
  126. // if any of the query strings relevant for the payload has changed,
  127. // we re-fetch data
  128. if (payloadKeysChanged) {
  129. this.fetchData();
  130. }
  131. }
  132. handleQueryChange = () => {
  133. this.fetchData({reloading: true});
  134. };
  135. handleSearchQuery = (searchQuery: string) => {
  136. const {location} = this.props;
  137. browserHistory.push({
  138. pathname: location.pathname,
  139. query: {
  140. ...location.query,
  141. cursor: undefined,
  142. query: String(searchQuery).trim() || undefined,
  143. },
  144. });
  145. };
  146. handleSortChange = (value: string) => {
  147. const {location, organization} = this.props;
  148. trackAnalytics('discover_v2.change_sort', {organization, sort: value});
  149. browserHistory.push({
  150. pathname: location.pathname,
  151. query: {
  152. ...location.query,
  153. cursor: undefined,
  154. sort: value,
  155. },
  156. });
  157. };
  158. renderActions() {
  159. const activeSort = this.getActiveSort();
  160. const {renderPrebuilt, savedQueries} = this.state;
  161. return (
  162. <StyledActions>
  163. <StyledSearchBar
  164. defaultQuery=""
  165. query={this.getSavedQuerySearchQuery()}
  166. placeholder={t('Search saved queries')}
  167. onSearch={this.handleSearchQuery}
  168. />
  169. <PrebuiltSwitch>
  170. Show Prebuilt
  171. <Switch
  172. isActive={renderPrebuilt}
  173. isDisabled={renderPrebuilt && (savedQueries ?? []).length === 0}
  174. size="lg"
  175. toggle={this.togglePrebuilt}
  176. />
  177. </PrebuiltSwitch>
  178. <CompactSelect
  179. triggerProps={{prefix: t('Sort By')}}
  180. value={activeSort!.value}
  181. options={SORT_OPTIONS}
  182. onChange={opt => this.handleSortChange(opt.value)}
  183. position="bottom-end"
  184. />
  185. </StyledActions>
  186. );
  187. }
  188. togglePrebuilt = () => {
  189. const {renderPrebuilt} = this.state;
  190. this.setState({renderPrebuilt: !renderPrebuilt}, () => {
  191. setRenderPrebuilt(!renderPrebuilt);
  192. this.fetchData({reloading: true});
  193. });
  194. };
  195. renderNoAccess() {
  196. return (
  197. <Layout.Page withPadding>
  198. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  199. </Layout.Page>
  200. );
  201. }
  202. renderBody() {
  203. const {location, organization, router} = this.props;
  204. const {savedQueries, savedQueriesPageLinks, renderPrebuilt} = this.state;
  205. return (
  206. <QueryList
  207. pageLinks={savedQueriesPageLinks}
  208. savedQueries={savedQueries ?? []}
  209. savedQuerySearchQuery={this.getSavedQuerySearchQuery()}
  210. renderPrebuilt={renderPrebuilt}
  211. location={location}
  212. organization={organization}
  213. onQueryChange={this.handleQueryChange}
  214. router={router}
  215. />
  216. );
  217. }
  218. renderBreadcrumbs() {
  219. return (
  220. <Breadcrumbs
  221. crumbs={[
  222. {
  223. key: 'discover-homepage',
  224. label: t('Discover'),
  225. to: getDiscoverLandingUrl(this.props.organization),
  226. },
  227. {
  228. key: 'discover-saved-queries',
  229. label: t('Saved Queries'),
  230. },
  231. ]}
  232. />
  233. );
  234. }
  235. render() {
  236. const {organization} = this.props;
  237. const to = makeDiscoverPathname({
  238. path: `/homepage/`,
  239. organization,
  240. });
  241. return (
  242. <Feature
  243. organization={organization}
  244. features="discover-query"
  245. renderDisabled={this.renderNoAccess}
  246. >
  247. <SentryDocumentTitle title={t('Discover')} orgSlug={organization.slug}>
  248. <Layout.Page>
  249. <Layout.Header>
  250. <Layout.HeaderContent>{this.renderBreadcrumbs()}</Layout.HeaderContent>
  251. <Layout.HeaderActions>
  252. <LinkButton
  253. data-test-id="build-new-query"
  254. to={to}
  255. size="sm"
  256. priority="primary"
  257. onClick={() => {
  258. trackAnalytics('discover_v2.build_new_query', {
  259. organization,
  260. });
  261. }}
  262. >
  263. {t('Build a new query')}
  264. </LinkButton>
  265. </Layout.HeaderActions>
  266. </Layout.Header>
  267. <Layout.Body>
  268. <Layout.Main fullWidth>
  269. {this.renderActions()}
  270. {this.renderComponent()}
  271. </Layout.Main>
  272. </Layout.Body>
  273. </Layout.Page>
  274. </SentryDocumentTitle>
  275. </Feature>
  276. );
  277. }
  278. }
  279. const PrebuiltSwitch = styled('label')`
  280. display: flex;
  281. align-items: center;
  282. gap: ${space(1.5)};
  283. font-weight: ${p => p.theme.fontWeightNormal};
  284. margin: 0;
  285. `;
  286. const StyledSearchBar = styled(SearchBar)`
  287. flex-grow: 1;
  288. `;
  289. const StyledActions = styled('div')`
  290. display: grid;
  291. gap: ${space(2)};
  292. grid-template-columns: auto max-content min-content;
  293. align-items: center;
  294. margin-bottom: ${space(2)};
  295. @media (max-width: ${p => p.theme.breakpoints.small}) {
  296. grid-template-columns: auto;
  297. }
  298. `;
  299. export default withOrganization(DiscoverLanding);
  300. export {DiscoverLanding};