queryList.tsx 9.5 KB

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