queryList.tsx 13 KB

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