queryList.tsx 13 KB

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