queryList.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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-timezone';
  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 {NewQuery, 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 newQuery = organization.features.includes(
  129. 'performance-discover-dataset-selector'
  130. )
  131. ? (getSavedQueryWithDataset(view) as NewQuery)
  132. : view;
  133. const eventView = EventView.fromNewQueryWithLocation(newQuery, location);
  134. // if a search is performed on the list of queries, we filter
  135. // on the pre-built queries
  136. if (
  137. hasSearchQuery &&
  138. eventView.name &&
  139. !eventView.name.toLowerCase().includes(needleSearch)
  140. ) {
  141. return null;
  142. }
  143. const recentTimeline = t('Last ') + eventView.statsPeriod;
  144. const customTimeline =
  145. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  146. ' - ' +
  147. moment(eventView.end).format('MMM D, YYYY h:mm A');
  148. const to = eventView.getResultsViewUrlTarget(organization.slug);
  149. if (organization.features.includes('performance-discover-dataset-selector')) {
  150. to.query = {
  151. ...to.query,
  152. queryDataset: view.queryDataset,
  153. };
  154. }
  155. const menuItems = [
  156. {
  157. key: 'add-to-dashboard',
  158. label: t('Add to Dashboard'),
  159. onAction: () =>
  160. handleAddQueryToDashboard({
  161. eventView,
  162. location,
  163. query: view,
  164. organization,
  165. yAxis: view?.yAxis,
  166. router,
  167. }),
  168. },
  169. {
  170. key: 'set-as-default',
  171. label: t('Set as Default'),
  172. onAction: () => {
  173. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  174. trackAnalytics('discover_v2.set_as_default', {
  175. organization,
  176. source: 'context-menu',
  177. type: 'prebuilt-query',
  178. });
  179. },
  180. },
  181. ];
  182. return (
  183. <QueryCard
  184. key={`${index}-${eventView.name}`}
  185. to={to}
  186. title={eventView.name}
  187. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  188. queryDetail={eventView.query}
  189. createdBy={eventView.createdBy}
  190. renderGraph={() => (
  191. <MiniGraph
  192. location={location}
  193. eventView={eventView}
  194. organization={organization}
  195. referrer="api.discover.homepage.prebuilt"
  196. />
  197. )}
  198. onEventClick={() => {
  199. trackAnalytics('discover_v2.prebuilt_query_click', {
  200. organization,
  201. query_name: eventView.name,
  202. });
  203. }}
  204. renderContextMenu={() => (
  205. <Feature organization={organization} features="dashboards-edit">
  206. {({hasFeature}) => {
  207. return hasFeature && this.renderDropdownMenu(menuItems);
  208. }}
  209. </Feature>
  210. )}
  211. />
  212. );
  213. });
  214. return list;
  215. }
  216. renderSavedQueries() {
  217. const {api, savedQueries, location, organization, router} = this.props;
  218. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  219. return [];
  220. }
  221. return savedQueries.map((query, index) => {
  222. const savedQuery = organization.features.includes(
  223. 'performance-discover-dataset-selector'
  224. )
  225. ? (getSavedQueryWithDataset(query) as SavedQuery)
  226. : query;
  227. const eventView = EventView.fromSavedQuery(savedQuery);
  228. const recentTimeline = t('Last ') + eventView.statsPeriod;
  229. const customTimeline =
  230. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  231. ' - ' +
  232. moment(eventView.end).format('MMM D, YYYY h:mm A');
  233. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  234. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  235. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  236. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  237. ...(canAddToDashboard
  238. ? [
  239. {
  240. key: 'add-to-dashboard',
  241. label: t('Add to Dashboard'),
  242. onAction: () =>
  243. handleAddQueryToDashboard({
  244. eventView,
  245. location,
  246. query: savedQuery,
  247. organization,
  248. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  249. router,
  250. }),
  251. },
  252. ]
  253. : []),
  254. {
  255. key: 'set-as-default',
  256. label: t('Set as Default'),
  257. onAction: () => {
  258. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  259. trackAnalytics('discover_v2.set_as_default', {
  260. organization,
  261. source: 'context-menu',
  262. type: 'saved-query',
  263. });
  264. },
  265. },
  266. {
  267. key: 'duplicate',
  268. label: t('Duplicate Query'),
  269. onAction: () =>
  270. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  271. },
  272. {
  273. key: 'delete',
  274. label: t('Delete Query'),
  275. priority: 'danger',
  276. onAction: () => this.handleDeleteQuery(eventView),
  277. },
  278. ];
  279. return (
  280. <QueryCard
  281. key={`${index}-${eventView.id}`}
  282. to={to}
  283. title={eventView.name}
  284. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  285. queryDetail={eventView.query}
  286. createdBy={eventView.createdBy}
  287. dateStatus={dateStatus}
  288. onEventClick={() => {
  289. trackAnalytics('discover_v2.saved_query_click', {organization});
  290. }}
  291. renderGraph={() => (
  292. <MiniGraph
  293. location={location}
  294. eventView={eventView}
  295. organization={organization}
  296. referrer={referrer}
  297. yAxis={savedQuery.yAxis?.length ? savedQuery.yAxis : ['count()']}
  298. />
  299. )}
  300. renderContextMenu={() => (
  301. <Feature organization={organization} features="dashboards-edit">
  302. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  303. </Feature>
  304. )}
  305. />
  306. );
  307. });
  308. }
  309. render() {
  310. const {pageLinks} = this.props;
  311. return (
  312. <Fragment>
  313. <QueryGrid>{this.renderQueries()}</QueryGrid>
  314. <PaginationRow
  315. pageLinks={pageLinks}
  316. onCursor={(cursor, path, query, direction) => {
  317. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  318. const newQuery: Query & {cursor?: string} = {...query, cursor};
  319. const isPrevious = direction === -1;
  320. if (offset <= 0 && isPrevious) {
  321. delete newQuery.cursor;
  322. }
  323. browserHistory.push({
  324. pathname: path,
  325. query: newQuery,
  326. });
  327. }}
  328. />
  329. </Fragment>
  330. );
  331. }
  332. }
  333. const PaginationRow = styled(Pagination)`
  334. margin-bottom: 20px;
  335. `;
  336. const QueryGrid = styled('div')`
  337. display: grid;
  338. grid-template-columns: minmax(100px, 1fr);
  339. gap: ${space(2)};
  340. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  341. grid-template-columns: repeat(2, minmax(100px, 1fr));
  342. }
  343. @media (min-width: ${p => p.theme.breakpoints.large}) {
  344. grid-template-columns: repeat(3, minmax(100px, 1fr));
  345. }
  346. `;
  347. const DropdownTrigger = styled(Button)`
  348. transform: translateX(${space(1)});
  349. `;
  350. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  351. grid-column: 1 / 4;
  352. `;
  353. export default withApi(QueryList);