queryList.tsx 12 KB

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