queryList.tsx 13 KB

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