queryList.tsx 11 KB

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