queryList.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. handleCreateQuery,
  27. handleDeleteQuery,
  28. handleUpdateHomepageQuery,
  29. } from './savedQuery/utils';
  30. import MiniGraph from './miniGraph';
  31. import QueryCard from './querycard';
  32. import {getPrebuiltQueries, handleAddQueryToDashboard} from './utils';
  33. type Props = {
  34. api: Client;
  35. location: Location;
  36. onQueryChange: () => void;
  37. organization: Organization;
  38. pageLinks: string;
  39. renderPrebuilt: boolean;
  40. router: InjectedRouter;
  41. savedQueries: SavedQuery[];
  42. savedQuerySearchQuery: string;
  43. };
  44. class QueryList extends Component<Props> {
  45. componentDidMount() {
  46. /**
  47. * We need to reset global selection here because the saved queries can define their own projects
  48. * in the query. This can lead to mismatched queries for the project
  49. */
  50. resetPageFilters();
  51. }
  52. handleDeleteQuery = (eventView: EventView) => {
  53. const {api, organization, onQueryChange, location, savedQueries} = this.props;
  54. handleDeleteQuery(api, organization, eventView).then(() => {
  55. if (savedQueries.length === 1 && location.query.cursor) {
  56. browserHistory.push({
  57. pathname: location.pathname,
  58. query: {...location.query, cursor: undefined},
  59. });
  60. } else {
  61. onQueryChange();
  62. }
  63. });
  64. };
  65. handleDuplicateQuery = (eventView: EventView, yAxis: string[]) => {
  66. const {api, location, organization, onQueryChange} = this.props;
  67. eventView = eventView.clone();
  68. eventView.name = `${eventView.name} copy`;
  69. handleCreateQuery(api, organization, eventView, yAxis).then(() => {
  70. onQueryChange();
  71. browserHistory.push({
  72. pathname: location.pathname,
  73. query: {},
  74. });
  75. });
  76. };
  77. renderQueries() {
  78. const {pageLinks, renderPrebuilt} = this.props;
  79. const links = parseLinkHeader(pageLinks || '');
  80. let cards: React.ReactNode[] = [];
  81. // If we're on the first page (no-previous page exists)
  82. // include the pre-built queries.
  83. if (renderPrebuilt && (!links.previous || links.previous.results === false)) {
  84. cards = cards.concat(this.renderPrebuiltQueries());
  85. }
  86. cards = cards.concat(this.renderSavedQueries());
  87. if (cards.filter(x => x).length === 0) {
  88. return (
  89. <StyledEmptyStateWarning>
  90. <p>{t('No saved queries match that filter')}</p>
  91. </StyledEmptyStateWarning>
  92. );
  93. }
  94. return cards;
  95. }
  96. renderDropdownMenu(items: MenuItemProps[]) {
  97. return (
  98. <DropdownMenu
  99. items={items}
  100. trigger={triggerProps => (
  101. <DropdownTrigger
  102. {...triggerProps}
  103. aria-label={t('Query actions')}
  104. size="xs"
  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. position="bottom-end"
  116. offset={4}
  117. />
  118. );
  119. }
  120. renderPrebuiltQueries() {
  121. const {api, 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. onAction: () =>
  148. handleAddQueryToDashboard({
  149. eventView,
  150. location,
  151. query: view,
  152. organization,
  153. yAxis: view?.yAxis,
  154. router,
  155. }),
  156. },
  157. {
  158. key: 'set-as-default',
  159. label: t('Set as Default'),
  160. onAction: () => {
  161. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  162. trackAnalytics('discover_v2.set_as_default', {
  163. organization,
  164. source: 'context-menu',
  165. type: 'prebuilt-query',
  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. trackAnalytics('discover_v2.prebuilt_query_click', {
  188. organization,
  189. query_name: eventView.name,
  190. });
  191. }}
  192. renderContextMenu={() => (
  193. <Feature organization={organization} features="dashboards-edit">
  194. {({hasFeature}) => {
  195. return hasFeature && this.renderDropdownMenu(menuItems);
  196. }}
  197. </Feature>
  198. )}
  199. />
  200. );
  201. });
  202. return list;
  203. }
  204. renderSavedQueries() {
  205. const {api, savedQueries, location, organization, router} = this.props;
  206. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  207. return [];
  208. }
  209. return savedQueries.map((savedQuery, index) => {
  210. const eventView = EventView.fromSavedQuery(savedQuery);
  211. const recentTimeline = t('Last ') + eventView.statsPeriod;
  212. const customTimeline =
  213. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  214. ' - ' +
  215. moment(eventView.end).format('MMM D, YYYY h:mm A');
  216. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  217. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  218. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  219. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  220. ...(canAddToDashboard
  221. ? [
  222. {
  223. key: 'add-to-dashboard',
  224. label: t('Add to Dashboard'),
  225. onAction: () =>
  226. handleAddQueryToDashboard({
  227. eventView,
  228. location,
  229. query: savedQuery,
  230. organization,
  231. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  232. router,
  233. }),
  234. },
  235. ]
  236. : []),
  237. {
  238. key: 'set-as-default',
  239. label: t('Set as Default'),
  240. onAction: () => {
  241. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  242. trackAnalytics('discover_v2.set_as_default', {
  243. organization,
  244. source: 'context-menu',
  245. type: 'saved-query',
  246. });
  247. },
  248. },
  249. {
  250. key: 'duplicate',
  251. label: t('Duplicate Query'),
  252. onAction: () =>
  253. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  254. },
  255. {
  256. key: 'delete',
  257. label: t('Delete Query'),
  258. priority: 'danger',
  259. onAction: () => this.handleDeleteQuery(eventView),
  260. },
  261. ];
  262. return (
  263. <QueryCard
  264. key={`${index}-${eventView.id}`}
  265. to={to}
  266. title={eventView.name}
  267. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  268. queryDetail={eventView.query}
  269. createdBy={eventView.createdBy}
  270. dateStatus={dateStatus}
  271. onEventClick={() => {
  272. trackAnalytics('discover_v2.saved_query_click', {organization});
  273. }}
  274. renderGraph={() => (
  275. <MiniGraph
  276. location={location}
  277. eventView={eventView}
  278. organization={organization}
  279. referrer={referrer}
  280. yAxis={savedQuery.yAxis?.length ? savedQuery.yAxis : ['count()']}
  281. />
  282. )}
  283. renderContextMenu={() => (
  284. <Feature organization={organization} features="dashboards-edit">
  285. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  286. </Feature>
  287. )}
  288. />
  289. );
  290. });
  291. }
  292. render() {
  293. const {pageLinks} = this.props;
  294. return (
  295. <Fragment>
  296. <QueryGrid>{this.renderQueries()}</QueryGrid>
  297. <PaginationRow
  298. pageLinks={pageLinks}
  299. onCursor={(cursor, path, query, direction) => {
  300. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  301. const newQuery: Query & {cursor?: string} = {...query, cursor};
  302. const isPrevious = direction === -1;
  303. if (offset <= 0 && isPrevious) {
  304. delete newQuery.cursor;
  305. }
  306. browserHistory.push({
  307. pathname: path,
  308. query: newQuery,
  309. });
  310. }}
  311. />
  312. </Fragment>
  313. );
  314. }
  315. }
  316. const PaginationRow = styled(Pagination)`
  317. margin-bottom: 20px;
  318. `;
  319. const QueryGrid = styled('div')`
  320. display: grid;
  321. grid-template-columns: minmax(100px, 1fr);
  322. gap: ${space(2)};
  323. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  324. grid-template-columns: repeat(2, minmax(100px, 1fr));
  325. }
  326. @media (min-width: ${p => p.theme.breakpoints.large}) {
  327. grid-template-columns: repeat(3, minmax(100px, 1fr));
  328. }
  329. `;
  330. const DropdownTrigger = styled(Button)`
  331. transform: translateX(${space(1)});
  332. `;
  333. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  334. grid-column: 1 / 4;
  335. `;
  336. export default withApi(QueryList);