queryList.tsx 13 KB

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