queryList.tsx 12 KB

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