queryList.tsx 13 KB

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