queryList.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  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. trackAdvancedAnalyticsEvent('discover_v2.prebuilt_query_click', {
  172. organization,
  173. query_name: eventView.name,
  174. });
  175. }}
  176. renderContextMenu={() => (
  177. <Feature organization={organization} features={['dashboards-edit']}>
  178. {({hasFeature}) => {
  179. return hasFeature && this.renderDropdownMenu(menuItems);
  180. }}
  181. </Feature>
  182. )}
  183. />
  184. );
  185. });
  186. return list;
  187. }
  188. renderSavedQueries() {
  189. const {savedQueries, location, organization, router} = this.props;
  190. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  191. return [];
  192. }
  193. return savedQueries.map((savedQuery, index) => {
  194. const eventView = EventView.fromSavedQuery(savedQuery);
  195. const recentTimeline = t('Last ') + eventView.statsPeriod;
  196. const customTimeline =
  197. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  198. ' - ' +
  199. moment(eventView.end).format('MMM D, YYYY h:mm A');
  200. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  201. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  202. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  203. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  204. ...(canAddToDashboard
  205. ? [
  206. {
  207. key: 'add-to-dashboard',
  208. label: t('Add to Dashboard'),
  209. onAction: () =>
  210. handleAddQueryToDashboard({
  211. eventView,
  212. location,
  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. trackAdvancedAnalyticsEvent('discover_v2.saved_query_click', {organization});
  245. }}
  246. renderGraph={() => (
  247. <MiniGraph
  248. location={location}
  249. eventView={eventView}
  250. organization={organization}
  251. referrer={referrer}
  252. yAxis={
  253. savedQuery.yAxis && savedQuery.yAxis.length
  254. ? savedQuery.yAxis
  255. : ['count()']
  256. }
  257. />
  258. )}
  259. renderContextMenu={() => (
  260. <Feature organization={organization} features={['dashboards-edit']}>
  261. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  262. </Feature>
  263. )}
  264. />
  265. );
  266. });
  267. }
  268. render() {
  269. const {pageLinks} = this.props;
  270. return (
  271. <Fragment>
  272. <QueryGrid>{this.renderQueries()}</QueryGrid>
  273. <PaginationRow
  274. pageLinks={pageLinks}
  275. onCursor={(cursor, path, query, direction) => {
  276. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  277. const newQuery: Query & {cursor?: string} = {...query, cursor};
  278. const isPrevious = direction === -1;
  279. if (offset <= 0 && isPrevious) {
  280. delete newQuery.cursor;
  281. }
  282. browserHistory.push({
  283. pathname: path,
  284. query: newQuery,
  285. });
  286. }}
  287. />
  288. </Fragment>
  289. );
  290. }
  291. }
  292. const PaginationRow = styled(Pagination)`
  293. margin-bottom: 20px;
  294. `;
  295. const QueryGrid = styled('div')`
  296. display: grid;
  297. grid-template-columns: minmax(100px, 1fr);
  298. gap: ${space(2)};
  299. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  300. grid-template-columns: repeat(2, minmax(100px, 1fr));
  301. }
  302. @media (min-width: ${p => p.theme.breakpoints.large}) {
  303. grid-template-columns: repeat(3, minmax(100px, 1fr));
  304. }
  305. `;
  306. const DropdownTrigger = styled(Button)`
  307. transform: translateX(${space(1)});
  308. `;
  309. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  310. grid-column: 1 / 4;
  311. `;
  312. export default withApi(QueryList);