queryList.tsx 12 KB

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