queryList.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. ? // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  173. SAVED_QUERY_DATASET_TO_WIDGET_TYPE[
  174. getSavedQueryDataset(organization, location, newQuery)
  175. ]
  176. : undefined,
  177. }),
  178. },
  179. {
  180. key: 'set-as-default',
  181. label: t('Set as Default'),
  182. onAction: () => {
  183. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  184. trackAnalytics('discover_v2.set_as_default', {
  185. organization,
  186. source: 'context-menu',
  187. type: 'prebuilt-query',
  188. });
  189. },
  190. },
  191. ];
  192. return (
  193. <QueryCard
  194. key={`${index}-${eventView.name}`}
  195. to={to}
  196. title={eventView.name}
  197. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  198. queryDetail={eventView.query}
  199. createdBy={eventView.createdBy}
  200. renderGraph={() => (
  201. <MiniGraph
  202. location={location}
  203. eventView={eventView}
  204. organization={organization}
  205. referrer="api.discover.homepage.prebuilt"
  206. />
  207. )}
  208. onEventClick={() => {
  209. trackAnalytics('discover_v2.prebuilt_query_click', {
  210. organization,
  211. query_name: eventView.name,
  212. });
  213. }}
  214. renderContextMenu={() => (
  215. <Feature organization={organization} features="dashboards-edit">
  216. {({hasFeature}) => {
  217. return hasFeature && this.renderDropdownMenu(menuItems);
  218. }}
  219. </Feature>
  220. )}
  221. />
  222. );
  223. });
  224. return list;
  225. }
  226. renderSavedQueries() {
  227. const {api, savedQueries, location, organization, router} = this.props;
  228. if (!savedQueries || !Array.isArray(savedQueries) || savedQueries.length === 0) {
  229. return [];
  230. }
  231. return savedQueries.map((query, index) => {
  232. const savedQuery = organization.features.includes(
  233. 'performance-discover-dataset-selector'
  234. )
  235. ? (getSavedQueryWithDataset(query) as SavedQuery)
  236. : query;
  237. const eventView = EventView.fromSavedQuery(savedQuery);
  238. const recentTimeline = t('Last ') + eventView.statsPeriod;
  239. const customTimeline =
  240. moment(eventView.start).format('MMM D, YYYY h:mm A') +
  241. ' - ' +
  242. moment(eventView.end).format('MMM D, YYYY h:mm A');
  243. const to = eventView.getResultsViewShortUrlTarget(organization.slug);
  244. const dateStatus = <TimeSince date={savedQuery.dateUpdated} />;
  245. const referrer = `api.discover.${eventView.getDisplayMode()}-chart`;
  246. const menuItems = (canAddToDashboard: boolean): MenuItemProps[] => [
  247. ...(canAddToDashboard
  248. ? [
  249. {
  250. key: 'add-to-dashboard',
  251. label: t('Add to Dashboard'),
  252. onAction: () =>
  253. handleAddQueryToDashboard({
  254. eventView,
  255. location,
  256. query: savedQuery,
  257. organization,
  258. yAxis: savedQuery?.yAxis ?? eventView.yAxis,
  259. router,
  260. widgetType: hasDatasetSelector(organization)
  261. ? // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  262. SAVED_QUERY_DATASET_TO_WIDGET_TYPE[
  263. getSavedQueryDataset(organization, location, savedQuery)
  264. ]
  265. : undefined,
  266. }),
  267. },
  268. ]
  269. : []),
  270. {
  271. key: 'set-as-default',
  272. label: t('Set as Default'),
  273. onAction: () => {
  274. handleUpdateHomepageQuery(api, organization, eventView.toNewQuery());
  275. trackAnalytics('discover_v2.set_as_default', {
  276. organization,
  277. source: 'context-menu',
  278. type: 'saved-query',
  279. });
  280. },
  281. },
  282. {
  283. key: 'duplicate',
  284. label: t('Duplicate Query'),
  285. onAction: () =>
  286. this.handleDuplicateQuery(eventView, decodeList(savedQuery.yAxis)),
  287. },
  288. {
  289. key: 'delete',
  290. label: t('Delete Query'),
  291. priority: 'danger',
  292. onAction: () => this.handleDeleteQuery(eventView),
  293. },
  294. ];
  295. return (
  296. <QueryCard
  297. key={`${index}-${eventView.id}`}
  298. to={to}
  299. title={eventView.name}
  300. subtitle={eventView.statsPeriod ? recentTimeline : customTimeline}
  301. queryDetail={eventView.query}
  302. createdBy={eventView.createdBy}
  303. dateStatus={dateStatus}
  304. onEventClick={() => {
  305. trackAnalytics('discover_v2.saved_query_click', {organization});
  306. }}
  307. renderGraph={() => (
  308. <MiniGraph
  309. location={location}
  310. eventView={eventView}
  311. organization={organization}
  312. referrer={referrer}
  313. yAxis={savedQuery.yAxis?.length ? savedQuery.yAxis : ['count()']}
  314. />
  315. )}
  316. renderContextMenu={() => (
  317. <Feature organization={organization} features="dashboards-edit">
  318. {({hasFeature}) => this.renderDropdownMenu(menuItems(hasFeature))}
  319. </Feature>
  320. )}
  321. />
  322. );
  323. });
  324. }
  325. render() {
  326. const {pageLinks} = this.props;
  327. return (
  328. <Fragment>
  329. <QueryGrid>{this.renderQueries()}</QueryGrid>
  330. <PaginationRow
  331. pageLinks={pageLinks}
  332. onCursor={(cursor, path, query, direction) => {
  333. const offset = Number(cursor?.split(':')?.[1] ?? 0);
  334. const newQuery: Query & {cursor?: string} = {...query, cursor};
  335. const isPrevious = direction === -1;
  336. if (offset <= 0 && isPrevious) {
  337. delete newQuery.cursor;
  338. }
  339. browserHistory.push({
  340. pathname: path,
  341. query: newQuery,
  342. });
  343. }}
  344. />
  345. </Fragment>
  346. );
  347. }
  348. }
  349. const PaginationRow = styled(Pagination)`
  350. margin-bottom: 20px;
  351. `;
  352. const QueryGrid = styled('div')`
  353. display: grid;
  354. grid-template-columns: minmax(100px, 1fr);
  355. gap: ${space(2)};
  356. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  357. grid-template-columns: repeat(2, minmax(100px, 1fr));
  358. }
  359. @media (min-width: ${p => p.theme.breakpoints.large}) {
  360. grid-template-columns: repeat(3, minmax(100px, 1fr));
  361. }
  362. `;
  363. const DropdownTrigger = styled(Button)`
  364. transform: translateX(${space(1)});
  365. `;
  366. const StyledEmptyStateWarning = styled(EmptyStateWarning)`
  367. grid-column: 1 / 4;
  368. `;
  369. export default withApi(QueryList);