queryList.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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 DropdownMenuControl from 'sentry/components/dropdownMenuControl';
  11. import {MenuItemProps} from 'sentry/components/dropdownMenuItem';
  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. <DropdownMenuControl
  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. location,
  147. query: view,
  148. organization,
  149. yAxis: view?.yAxis,
  150. router,
  151. }),
  152. },
  153. ];
  154. return (
  155. <QueryCard
  156. key={`${index}-${eventView.name}`}
  157. to={to}
  158. title={eventView.name}
  159. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  160. queryDetail={eventView.query}
  161. createdBy={eventView.createdBy}
  162. renderGraph={() => (
  163. <MiniGraph
  164. location={location}
  165. eventView={eventView}
  166. organization={organization}
  167. referrer="api.discover.homepage.prebuilt"
  168. />
  169. )}
  170. onEventClick={() => {
  171. trackAnalyticsEvent({
  172. eventKey: 'discover_v2.prebuilt_query_click',
  173. eventName: 'Discoverv2: Click a pre-built query',
  174. organization_id: parseInt(this.props.organization.id, 10),
  175. query_name: eventView.name,
  176. });
  177. }}
  178. renderContextMenu={() => (
  179. <Feature organization={organization} features={['dashboards-edit']}>
  180. {({hasFeature}) => {
  181. return hasFeature && this.renderDropdownMenu(menuItems);
  182. }}
  183. </Feature>
  184. )}
  185. />
  186. );
  187. });
  188. return list;
  189. }
  190. renderSavedQueries() {
  191. const {savedQueries, location, organization, router} = this.props;
  192. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  193. return [];
  194. }
  195. return savedQueries.map((savedQuery, index) => {
  196. const eventView = EventView.fromSavedQuery(savedQuery);
  197. const recentTimeline = t('Last ') + eventView.statsPeriod;
  198. const customTimeline =
  199. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  200. ' - ' +
  201. moment(eventView.end).format('MMM D, YYYY h:mm A');
  202. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  203. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  204. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  205. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  206. ...(canAddToDashboard
  207. ? [
  208. {
  209. key: 'add-to-dashboard',
  210. label: t('Add to Dashboard'),
  211. onAction: () =>
  212. handleAddQueryToDashboard({
  213. eventView,
  214. location,
  215. query: savedQuery,
  216. organization,
  217. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  218. router,
  219. }),
  220. },
  221. ]
  222. : []),
  223. {
  224. key: 'duplicate',
  225. label: t('Duplicate Query'),
  226. onAction: () =>
  227. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  228. },
  229. {
  230. key: 'delete',
  231. label: t('Delete Query'),
  232. priority: 'danger',
  233. onAction: () => this.handleDeleteQuery(eventView),
  234. },
  235. ];
  236. return (
  237. <QueryCard
  238. key={`${index}-${eventView.id}`}
  239. to={to}
  240. title={eventView.name}
  241. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  242. queryDetail={eventView.query}
  243. createdBy={eventView.createdBy}
  244. dateStatus={dateStatus}
  245. onEventClick={() => {
  246. trackAnalyticsEvent({
  247. eventKey: 'discover_v2.saved_query_click',
  248. eventName: 'Discoverv2: Click a saved query',
  249. organization_id: parseInt(this.props.organization.id, 10),
  250. });
  251. }}
  252. renderGraph={() => (
  253. <MiniGraph
  254. location={location}
  255. eventView={eventView}
  256. organization={organization}
  257. referrer={referrer}
  258. yAxis={
  259. savedQuery.yAxis && savedQuery.yAxis.length
  260. ? savedQuery.yAxis
  261. : ['count()']
  262. }
  263. />
  264. )}
  265. renderContextMenu={() => (
  266. <Feature organization={organization} features={['dashboards-edit']}>
  267. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  268. </Feature>
  269. )}
  270. />
  271. );
  272. });
  273. }
  274. render() {
  275. const {pageLinks} = this.props;
  276. return (
  277. <Fragment>
  278. <QueryGrid>{this.renderQueries()}</QueryGrid>
  279. <PaginationRow
  280. pageLinks={pageLinks}
  281. onCursor={(cursor, path, query, direction) => {
  282. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  283. const newQuery: Query & {cursor?: string} = {...query, cursor};
  284. const isPrevious = direction === -1;
  285. if (offset <= 0 && isPrevious) {
  286. delete newQuery.cursor;
  287. }
  288. browserHistory.push({
  289. pathname: path,
  290. query: newQuery,
  291. });
  292. }}
  293. />
  294. </Fragment>
  295. );
  296. }
  297. }
  298. const PaginationRow = styled(Pagination)`
  299. margin-bottom: 20px;
  300. `;
  301. const QueryGrid = styled('div')`
  302. display: grid;
  303. grid-template-columns: minmax(100px, 1fr);
  304. gap: ${space(2)};
  305. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  306. grid-template-columns: repeat(2, minmax(100px, 1fr));
  307. }
  308. @media (min-width: ${p => p.theme.breakpoints.large}) {
  309. grid-template-columns: repeat(3, minmax(100px, 1fr));
  310. }
  311. `;
  312. const DropdownTrigger = styled(Button)`
  313. transform: translateX(${space(1)});
  314. `;
  315. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  316. grid-column: 1 / 4;
  317. `;
  318. export default withApi(QueryList);