queryList.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. import * as React 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 {
  28. constructAddQueryToDashboardLink,
  29. getPrebuiltQueries,
  30. handleAddQueryToDashboard,
  31. } from './utils';
  32. type Props = {
  33. api: Client;
  34. location: Location;
  35. onQueryChange: () => void;
  36. organization: Organization;
  37. pageLinks: string;
  38. renderPrebuilt: boolean;
  39. router: InjectedRouter;
  40. savedQueries: SavedQuery[];
  41. savedQuerySearchQuery: string;
  42. };
  43. class QueryList extends React.Component<Props> {
  44. componentDidMount() {
  45. /**
  46. * We need to reset global selection here because the saved queries can define their own projects
  47. * in the query. This can lead to mismatched queries for the project
  48. */
  49. resetPageFilters();
  50. }
  51. handleDeleteQuery = (eventView: EventView) => {
  52. const {api, organization, onQueryChange, location, savedQueries} = this.props;
  53. handleDeleteQuery(api, organization, eventView).then(() => {
  54. if (savedQueries.length === 1 && location.query.cursor) {
  55. browserHistory.push({
  56. pathname: location.pathname,
  57. query: {...location.query, cursor: undefined},
  58. });
  59. } else {
  60. onQueryChange();
  61. }
  62. });
  63. };
  64. handleDuplicateQuery = (eventView: EventView, yAxis: string[]) => {
  65. const {api, location, organization, onQueryChange} = this.props;
  66. eventView = eventView.clone();
  67. eventView.name = `${eventView.name} copy`;
  68. handleCreateQuery(api, organization, eventView, yAxis).then(() => {
  69. onQueryChange();
  70. browserHistory.push({
  71. pathname: location.pathname,
  72. query: {},
  73. });
  74. });
  75. };
  76. renderQueries() {
  77. const {pageLinks, renderPrebuilt} = this.props;
  78. const links = parseLinkHeader(pageLinks || '');
  79. let cards: React.ReactNode[] = [];
  80. // If we're on the first page (no-previous page exists)
  81. // include the pre-built queries.
  82. if (renderPrebuilt && (!links.previous || links.previous.results === false)) {
  83. cards = cards.concat(this.renderPrebuiltQueries());
  84. }
  85. cards = cards.concat(this.renderSavedQueries());
  86. if (cards.filter(x => x).length === 0) {
  87. return (
  88. <StyledEmptyStateWarning>
  89. <p>{t('No saved queries match that filter')}</p>
  90. </StyledEmptyStateWarning>
  91. );
  92. }
  93. return cards;
  94. }
  95. renderDropdownMenu(items: MenuItemProps[]) {
  96. return (
  97. <DropdownMenuControlV2
  98. items={items}
  99. trigger={({props: triggerProps, ref: triggerRef}) => (
  100. <DropdownTrigger
  101. ref={triggerRef}
  102. {...triggerProps}
  103. aria-label={t('Query actions')}
  104. size="xsmall"
  105. borderless
  106. onClick={e => {
  107. e.stopPropagation();
  108. e.preventDefault();
  109. triggerProps.onClick?.(e);
  110. }}
  111. icon={<IconEllipsis direction="down" size="sm" />}
  112. data-test-id="menu-trigger"
  113. />
  114. )}
  115. placement="bottom right"
  116. offset={4}
  117. />
  118. );
  119. }
  120. renderPrebuiltQueries() {
  121. const {location, organization, savedQuerySearchQuery, router} = this.props;
  122. const views = getPrebuiltQueries(organization);
  123. const hasSearchQuery =
  124. typeof savedQuerySearchQuery === 'string' && savedQuerySearchQuery.length > 0;
  125. const needleSearch = hasSearchQuery ? savedQuerySearchQuery.toLowerCase() : '';
  126. const list = views.map((view, index) => {
  127. const eventView = EventView.fromNewQueryWithLocation(view, location);
  128. // if a search is performed on the list of queries, we filter
  129. // on the pre-built queries
  130. if (
  131. hasSearchQuery &&
  132. eventView.name &&
  133. !eventView.name.toLowerCase().includes(needleSearch)
  134. ) {
  135. return null;
  136. }
  137. const recentTimeline = t('Last ') + eventView.statsPeriod;
  138. const customTimeline =
  139. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  140. ' - ' +
  141. moment(eventView.end).format('MMM D, YYYY h:mm A');
  142. const to = eventView.getResultsViewUrlTarget(organization.slug);
  143. const menuItems = [
  144. {
  145. key: 'add-to-dashboard',
  146. label: t('Add to Dashboard'),
  147. ...(organization.features.includes('new-widget-builder-experience') &&
  148. !organization.features.includes('new-widget-builder-experience-design')
  149. ? {
  150. to: constructAddQueryToDashboardLink({
  151. eventView,
  152. query: view,
  153. organization,
  154. yAxis: view?.yAxis,
  155. location,
  156. }),
  157. }
  158. : {
  159. onAction: () =>
  160. handleAddQueryToDashboard({
  161. eventView,
  162. query: view,
  163. organization,
  164. yAxis: view?.yAxis,
  165. router,
  166. }),
  167. }),
  168. },
  169. ];
  170. return (
  171. <QueryCard
  172. key={`${index}-${eventView.name}`}
  173. to={to}
  174. title={eventView.name}
  175. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  176. queryDetail={eventView.query}
  177. createdBy={eventView.createdBy}
  178. renderGraph={() => (
  179. <MiniGraph
  180. location={location}
  181. eventView={eventView}
  182. organization={organization}
  183. referrer="api.discover.homepage.prebuilt"
  184. />
  185. )}
  186. onEventClick={() => {
  187. trackAnalyticsEvent({
  188. eventKey: 'discover_v2.prebuilt_query_click',
  189. eventName: 'Discoverv2: Click a pre-built query',
  190. organization_id: parseInt(this.props.organization.id, 10),
  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 {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. ...(organization.features.includes('new-widget-builder-experience') &&
  228. !organization.features.includes('new-widget-builder-experience-design')
  229. ? {
  230. to: constructAddQueryToDashboardLink({
  231. eventView,
  232. query: savedQuery,
  233. organization,
  234. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  235. location,
  236. }),
  237. }
  238. : {
  239. onAction: () =>
  240. handleAddQueryToDashboard({
  241. eventView,
  242. query: savedQuery,
  243. organization,
  244. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  245. router,
  246. }),
  247. }),
  248. },
  249. ]
  250. : []),
  251. {
  252. key: 'duplicate',
  253. label: t('Duplicate Query'),
  254. onAction: () =>
  255. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  256. },
  257. {
  258. key: 'delete',
  259. label: t('Delete Query'),
  260. priority: 'danger',
  261. onAction: () => this.handleDeleteQuery(eventView),
  262. },
  263. ];
  264. return (
  265. <QueryCard
  266. key={`${index}-${eventView.id}`}
  267. to={to}
  268. title={eventView.name}
  269. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  270. queryDetail={eventView.query}
  271. createdBy={eventView.createdBy}
  272. dateStatus={dateStatus}
  273. onEventClick={() => {
  274. trackAnalyticsEvent({
  275. eventKey: 'discover_v2.saved_query_click',
  276. eventName: 'Discoverv2: Click a saved query',
  277. organization_id: parseInt(this.props.organization.id, 10),
  278. });
  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. <React.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. </React.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[1]}) {
  334. grid-template-columns: repeat(2, minmax(100px, 1fr));
  335. }
  336. @media (min-width: ${p => p.theme.breakpoints[2]}) {
  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);