queryList.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import {Component, Fragment} from 'react';
  2. import type {InjectedRouter} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import type {Location, Query} from 'history';
  5. import moment from 'moment-timezone';
  6. import {resetPageFilters} from 'sentry/actionCreators/pageFilters';
  7. import type {Client} from 'sentry/api';
  8. import Feature from 'sentry/components/acl/feature';
  9. import {Button} from 'sentry/components/button';
  10. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  11. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  12. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  13. import Pagination from 'sentry/components/pagination';
  14. import TimeSince from 'sentry/components/timeSince';
  15. import {IconEllipsis} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import type {NewQuery, Organization, SavedQuery} from 'sentry/types';
  19. import {trackAnalytics} from 'sentry/utils/analytics';
  20. import {browserHistory} from 'sentry/utils/browserHistory';
  21. import EventView from 'sentry/utils/discover/eventView';
  22. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  23. import {decodeList} from 'sentry/utils/queryString';
  24. import withApi from 'sentry/utils/withApi';
  25. import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
  26. import {
  27. getSavedQueryWithDataset,
  28. handleCreateQuery,
  29. handleDeleteQuery,
  30. handleUpdateHomepageQuery,
  31. } from './savedQuery/utils';
  32. import MiniGraph from './miniGraph';
  33. import QueryCard from './querycard';
  34. import {getPrebuiltQueries, handleAddQueryToDashboard} from './utils';
  35. type Props = {
  36. api: Client;
  37. location: Location;
  38. onQueryChange: () => void;
  39. organization: Organization;
  40. pageLinks: string;
  41. renderPrebuilt: boolean;
  42. router: InjectedRouter;
  43. savedQueries: SavedQuery[];
  44. savedQuerySearchQuery: string;
  45. };
  46. class QueryList extends Component<Props> {
  47. componentDidMount() {
  48. /**
  49. * We need to reset global selection here because the saved queries can define their own projects
  50. * in the query. This can lead to mismatched queries for the project
  51. */
  52. resetPageFilters();
  53. }
  54. handleDeleteQuery = (eventView: EventView) => {
  55. const {api, organization, onQueryChange, location, savedQueries} = this.props;
  56. handleDeleteQuery(api, organization, eventView).then(() => {
  57. if (savedQueries.length === 1 && location.query.cursor) {
  58. browserHistory.push({
  59. pathname: location.pathname,
  60. query: {...location.query, cursor: undefined},
  61. });
  62. } else {
  63. onQueryChange();
  64. }
  65. });
  66. };
  67. handleDuplicateQuery = (eventView: EventView, yAxis: string[]) => {
  68. const {api, location, organization, onQueryChange} = this.props;
  69. eventView = eventView.clone();
  70. eventView.name = `${eventView.name} copy`;
  71. handleCreateQuery(api, organization, eventView, yAxis).then(() => {
  72. onQueryChange();
  73. browserHistory.push({
  74. pathname: location.pathname,
  75. query: {},
  76. });
  77. });
  78. };
  79. renderQueries() {
  80. const {pageLinks, renderPrebuilt} = this.props;
  81. const links = parseLinkHeader(pageLinks || '');
  82. let cards: React.ReactNode[] = [];
  83. // If we're on the first page (no-previous page exists)
  84. // include the pre-built queries.
  85. if (renderPrebuilt && (!links.previous || links.previous.results === false)) {
  86. cards = cards.concat(this.renderPrebuiltQueries());
  87. }
  88. cards = cards.concat(this.renderSavedQueries());
  89. if (cards.filter(x => x).length === 0) {
  90. return (
  91. <StyledEmptyStateWarning>
  92. <p>{t('No saved queries match that filter')}</p>
  93. </StyledEmptyStateWarning>
  94. );
  95. }
  96. return cards;
  97. }
  98. renderDropdownMenu(items: MenuItemProps[]) {
  99. return (
  100. <DropdownMenu
  101. items={items}
  102. trigger={triggerProps => (
  103. <DropdownTrigger
  104. {...triggerProps}
  105. aria-label={t('Query actions')}
  106. size="xs"
  107. borderless
  108. onClick={e => {
  109. e.stopPropagation();
  110. e.preventDefault();
  111. triggerProps.onClick?.(e);
  112. }}
  113. icon={<IconEllipsis direction="down" size="sm" />}
  114. data-test-id="menu-trigger"
  115. />
  116. )}
  117. position="bottom-end"
  118. offset={4}
  119. />
  120. );
  121. }
  122. renderPrebuiltQueries() {
  123. const {api, location, organization, savedQuerySearchQuery, router} = this.props;
  124. const views = getPrebuiltQueries(organization);
  125. const hasSearchQuery =
  126. typeof savedQuerySearchQuery === 'string' && savedQuerySearchQuery.length > 0;
  127. const needleSearch = hasSearchQuery ? savedQuerySearchQuery.toLowerCase() : '';
  128. const list = views.map((view, index) => {
  129. const newQuery = organization.features.includes(
  130. 'performance-discover-dataset-selector'
  131. )
  132. ? (getSavedQueryWithDataset(view) as NewQuery)
  133. : view;
  134. const eventView = EventView.fromNewQueryWithLocation(newQuery, location);
  135. // if a search is performed on the list of queries, we filter
  136. // on the pre-built queries
  137. if (
  138. hasSearchQuery &&
  139. eventView.name &&
  140. !eventView.name.toLowerCase().includes(needleSearch)
  141. ) {
  142. return null;
  143. }
  144. const recentTimeline = t('Last ') + eventView.statsPeriod;
  145. const customTimeline =
  146. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  147. ' - ' +
  148. moment(eventView.end).format('MMM D, YYYY h:mm A');
  149. const to = eventView.getResultsViewUrlTarget(
  150. organization.slug,
  151. false,
  152. hasDatasetSelector(organization) ? view.queryDataset : undefined
  153. );
  154. const menuItems = [
  155. {
  156. key: 'add-to-dashboard',
  157. label: t('Add to Dashboard'),
  158. onAction: () =>
  159. handleAddQueryToDashboard({
  160. eventView,
  161. location,
  162. query: view,
  163. organization,
  164. yAxis: view?.yAxis,
  165. router,
  166. }),
  167. },
  168. {
  169. key: 'set-as-default',
  170. label: t('Set as Default'),
  171. onAction: () => {
  172. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  173. trackAnalytics('discover_v2.set_as_default', {
  174. organization,
  175. source: 'context-menu',
  176. type: 'prebuilt-query',
  177. });
  178. },
  179. },
  180. ];
  181. return (
  182. <QueryCard
  183. key={`${index}-${eventView.name}`}
  184. to={to}
  185. title={eventView.name}
  186. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  187. queryDetail={eventView.query}
  188. createdBy={eventView.createdBy}
  189. renderGraph={() => (
  190. <MiniGraph
  191. location={location}
  192. eventView={eventView}
  193. organization={organization}
  194. referrer="api.discover.homepage.prebuilt"
  195. />
  196. )}
  197. onEventClick={() => {
  198. trackAnalytics('discover_v2.prebuilt_query_click', {
  199. organization,
  200. query_name: eventView.name,
  201. });
  202. }}
  203. renderContextMenu={() => (
  204. <Feature organization={organization} features="dashboards-edit">
  205. {({hasFeature}) => {
  206. return hasFeature && this.renderDropdownMenu(menuItems);
  207. }}
  208. </Feature>
  209. )}
  210. />
  211. );
  212. });
  213. return list;
  214. }
  215. renderSavedQueries() {
  216. const {api, savedQueries, location, organization, router} = this.props;
  217. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  218. return [];
  219. }
  220. return savedQueries.map((query, index) => {
  221. const savedQuery = organization.features.includes(
  222. 'performance-discover-dataset-selector'
  223. )
  224. ? (getSavedQueryWithDataset(query) as SavedQuery)
  225. : query;
  226. const eventView = EventView.fromSavedQuery(savedQuery);
  227. const recentTimeline = t('Last ') + eventView.statsPeriod;
  228. const customTimeline =
  229. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  230. ' - ' +
  231. moment(eventView.end).format('MMM D, YYYY h:mm A');
  232. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  233. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  234. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  235. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  236. ...(canAddToDashboard
  237. ? [
  238. {
  239. key: 'add-to-dashboard',
  240. label: t('Add to Dashboard'),
  241. onAction: () =>
  242. handleAddQueryToDashboard({
  243. eventView,
  244. location,
  245. query: savedQuery,
  246. organization,
  247. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  248. router,
  249. }),
  250. },
  251. ]
  252. : []),
  253. {
  254. key: 'set-as-default',
  255. label: t('Set as Default'),
  256. onAction: () => {
  257. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  258. trackAnalytics('discover_v2.set_as_default', {
  259. organization,
  260. source: 'context-menu',
  261. type: 'saved-query',
  262. });
  263. },
  264. },
  265. {
  266. key: 'duplicate',
  267. label: t('Duplicate Query'),
  268. onAction: () =>
  269. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  270. },
  271. {
  272. key: 'delete',
  273. label: t('Delete Query'),
  274. priority: 'danger',
  275. onAction: () => this.handleDeleteQuery(eventView),
  276. },
  277. ];
  278. return (
  279. <QueryCard
  280. key={`${index}-${eventView.id}`}
  281. to={to}
  282. title={eventView.name}
  283. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  284. queryDetail={eventView.query}
  285. createdBy={eventView.createdBy}
  286. dateStatus={dateStatus}
  287. onEventClick={() => {
  288. trackAnalytics('discover_v2.saved_query_click', {organization});
  289. }}
  290. renderGraph={() => (
  291. <MiniGraph
  292. location={location}
  293. eventView={eventView}
  294. organization={organization}
  295. referrer={referrer}
  296. yAxis={savedQuery.yAxis?.length ? savedQuery.yAxis : ['count()']}
  297. />
  298. )}
  299. renderContextMenu={() => (
  300. <Feature organization={organization} features="dashboards-edit">
  301. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  302. </Feature>
  303. )}
  304. />
  305. );
  306. });
  307. }
  308. render() {
  309. const {pageLinks} = this.props;
  310. return (
  311. <Fragment>
  312. <QueryGrid>{this.renderQueries()}</QueryGrid>
  313. <PaginationRow
  314. pageLinks={pageLinks}
  315. onCursor={(cursor, path, query, direction) => {
  316. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  317. const newQuery: Query & {cursor?: string} = {...query, cursor};
  318. const isPrevious = direction === -1;
  319. if (offset <= 0 && isPrevious) {
  320. delete newQuery.cursor;
  321. }
  322. browserHistory.push({
  323. pathname: path,
  324. query: newQuery,
  325. });
  326. }}
  327. />
  328. </Fragment>
  329. );
  330. }
  331. }
  332. const PaginationRow = styled(Pagination)`
  333. margin-bottom: 20px;
  334. `;
  335. const QueryGrid = styled('div')`
  336. display: grid;
  337. grid-template-columns: minmax(100px, 1fr);
  338. gap: ${space(2)};
  339. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  340. grid-template-columns: repeat(2, minmax(100px, 1fr));
  341. }
  342. @media (min-width: ${p => p.theme.breakpoints.large}) {
  343. grid-template-columns: repeat(3, minmax(100px, 1fr));
  344. }
  345. `;
  346. const DropdownTrigger = styled(Button)`
  347. transform: translateX(${space(1)});
  348. `;
  349. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  350. grid-column: 1 / 4;
  351. `;
  352. export default withApi(QueryList);