landing.tsx 9.4 KB

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