index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. import {Fragment, PureComponent} from 'react';
  2. import {browserHistory, InjectedRouter} from 'react-router';
  3. import {useTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {FocusScope} from '@react-aria/focus';
  6. import {AnimatePresence} from 'framer-motion';
  7. import {Location} from 'history';
  8. import isEqual from 'lodash/isEqual';
  9. import {Client} from 'sentry/api';
  10. import Feature from 'sentry/components/acl/feature';
  11. import FeatureDisabled from 'sentry/components/acl/featureDisabled';
  12. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  13. import Banner from 'sentry/components/banner';
  14. import {Button} from 'sentry/components/button';
  15. import ButtonBar from 'sentry/components/buttonBar';
  16. import {CreateAlertFromViewButton} from 'sentry/components/createAlertButton';
  17. import {DropdownMenu, MenuItemProps} from 'sentry/components/dropdownMenu';
  18. import {Hovercard} from 'sentry/components/hovercard';
  19. import InputControl from 'sentry/components/input';
  20. import {Overlay, PositionWrapper} from 'sentry/components/overlay';
  21. import {IconBookmark, IconDelete, IconEllipsis, IconStar} from 'sentry/icons';
  22. import {t} from 'sentry/locale';
  23. import {space} from 'sentry/styles/space';
  24. import {Organization, Project, SavedQuery} from 'sentry/types';
  25. import {trackAnalytics} from 'sentry/utils/analytics';
  26. import EventView from 'sentry/utils/discover/eventView';
  27. import {getDiscoverQueriesUrl} from 'sentry/utils/discover/urls';
  28. import useOverlay from 'sentry/utils/useOverlay';
  29. import withApi from 'sentry/utils/withApi';
  30. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  31. import withProjects from 'sentry/utils/withProjects';
  32. import {handleAddQueryToDashboard} from 'sentry/views/discover/utils';
  33. import {DEFAULT_EVENT_VIEW} from '../data';
  34. import {
  35. handleCreateQuery,
  36. handleDeleteQuery,
  37. handleResetHomepageQuery,
  38. handleUpdateHomepageQuery,
  39. handleUpdateQuery,
  40. } from './utils';
  41. const renderDisabled = p => (
  42. <Hovercard
  43. body={
  44. <FeatureDisabled
  45. features={p.features}
  46. hideHelpToggle
  47. message={t('Discover queries are disabled')}
  48. featureName={t('Discover queries')}
  49. />
  50. }
  51. >
  52. {p.children(p)}
  53. </Hovercard>
  54. );
  55. type SaveAsDropdownProps = {
  56. disabled: boolean;
  57. modifiedHandleCreateQuery: (e: React.MouseEvent<Element>) => void;
  58. onChangeInput: (e: React.FormEvent<HTMLInputElement>) => void;
  59. queryName: string;
  60. };
  61. function SaveAsDropdown({
  62. queryName,
  63. disabled,
  64. onChangeInput,
  65. modifiedHandleCreateQuery,
  66. }: SaveAsDropdownProps) {
  67. const {isOpen, triggerProps, overlayProps, arrowProps} = useOverlay();
  68. const theme = useTheme();
  69. return (
  70. <div>
  71. <Button
  72. {...triggerProps}
  73. size="sm"
  74. icon={<IconStar />}
  75. aria-label={t('Save as')}
  76. disabled={disabled}
  77. >
  78. {`${t('Save as')}\u2026`}
  79. </Button>
  80. <AnimatePresence>
  81. {isOpen && (
  82. <FocusScope contain restoreFocus autoFocus>
  83. <PositionWrapper zIndex={theme.zIndex.dropdown} {...overlayProps}>
  84. <StyledOverlay arrowProps={arrowProps} animated>
  85. <SaveAsInput
  86. type="text"
  87. name="query_name"
  88. placeholder={t('Display name')}
  89. value={queryName || ''}
  90. onChange={onChangeInput}
  91. disabled={disabled}
  92. />
  93. <SaveAsButton
  94. onClick={modifiedHandleCreateQuery}
  95. priority="primary"
  96. disabled={disabled || !queryName}
  97. >
  98. {t('Save for Org')}
  99. </SaveAsButton>
  100. </StyledOverlay>
  101. </PositionWrapper>
  102. </FocusScope>
  103. )}
  104. </AnimatePresence>
  105. </div>
  106. );
  107. }
  108. type DefaultProps = {
  109. disabled: boolean;
  110. };
  111. type Props = DefaultProps & {
  112. api: Client;
  113. eventView: EventView;
  114. /**
  115. * DO NOT USE `Location` TO GENERATE `EventView` IN THIS COMPONENT.
  116. *
  117. * In this component, state is generated from EventView and SavedQueriesStore.
  118. * Using Location to rebuild EventView will break the tests. `Location` is
  119. * passed down only because it is needed for navigation.
  120. */
  121. location: Location;
  122. organization: Organization;
  123. projects: Project[];
  124. queryDataLoading: boolean;
  125. router: InjectedRouter;
  126. savedQuery: SavedQuery | undefined;
  127. setHomepageQuery: (homepageQuery?: SavedQuery) => void;
  128. setSavedQuery: (savedQuery: SavedQuery) => void;
  129. updateCallback: () => void;
  130. yAxis: string[];
  131. homepageQuery?: SavedQuery;
  132. isHomepage?: boolean;
  133. };
  134. type State = {
  135. isEditingQuery: boolean;
  136. isNewQuery: boolean;
  137. queryName: string;
  138. };
  139. class SavedQueryButtonGroup extends PureComponent<Props, State> {
  140. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  141. const {eventView: nextEventView, savedQuery, queryDataLoading, yAxis} = nextProps;
  142. // For a new unsaved query
  143. if (!savedQuery) {
  144. return {
  145. isNewQuery: true,
  146. isEditingQuery: false,
  147. queryName: prevState.queryName || '',
  148. };
  149. }
  150. if (queryDataLoading) {
  151. return prevState;
  152. }
  153. const savedEventView = EventView.fromSavedQuery(savedQuery);
  154. // Switching from a SavedQuery to another SavedQuery
  155. if (savedEventView.id !== nextEventView.id) {
  156. return {
  157. isNewQuery: false,
  158. isEditingQuery: false,
  159. queryName: '',
  160. };
  161. }
  162. // For modifying a SavedQuery
  163. const isEqualQuery = nextEventView.isEqualTo(savedEventView);
  164. // undefined saved yAxis defaults to count() and string values are converted to array
  165. const isEqualYAxis = isEqual(
  166. yAxis,
  167. !savedQuery.yAxis
  168. ? ['count()']
  169. : typeof savedQuery.yAxis === 'string'
  170. ? [savedQuery.yAxis]
  171. : savedQuery.yAxis
  172. );
  173. return {
  174. isNewQuery: false,
  175. isEditingQuery: !isEqualQuery || !isEqualYAxis,
  176. // HACK(leedongwei): See comment at SavedQueryButtonGroup.onFocusInput
  177. queryName: prevState.queryName || '',
  178. };
  179. }
  180. /**
  181. * Stop propagation for the input and container so people can interact with
  182. * the inputs in the dropdown.
  183. */
  184. static stopEventPropagation = (event: React.MouseEvent) => {
  185. const capturedElements = ['LI', 'INPUT'];
  186. if (
  187. event.target instanceof Element &&
  188. capturedElements.includes(event.target.nodeName)
  189. ) {
  190. event.preventDefault();
  191. event.stopPropagation();
  192. }
  193. };
  194. static defaultProps: DefaultProps = {
  195. disabled: false,
  196. };
  197. state: State = {
  198. isNewQuery: true,
  199. isEditingQuery: false,
  200. queryName: '',
  201. };
  202. onChangeInput = (event: React.FormEvent<HTMLInputElement>) => {
  203. const target = event.target as HTMLInputElement;
  204. this.setState({queryName: target.value});
  205. };
  206. /**
  207. * There are two ways to create a query
  208. * 1) Creating a query from scratch and saving it
  209. * 2) Modifying an existing query and saving it
  210. */
  211. handleCreateQuery = (event: React.MouseEvent<Element>) => {
  212. event.preventDefault();
  213. event.stopPropagation();
  214. const {api, organization, eventView, yAxis} = this.props;
  215. if (!this.state.queryName) {
  216. return;
  217. }
  218. const nextEventView = eventView.clone();
  219. nextEventView.name = this.state.queryName;
  220. // Checks if "Save as" button is clicked from a clean state, or it is
  221. // clicked while modifying an existing query
  222. const isNewQuery = !eventView.id;
  223. handleCreateQuery(api, organization, nextEventView, yAxis, isNewQuery).then(
  224. (savedQuery: SavedQuery) => {
  225. const view = EventView.fromSavedQuery(savedQuery);
  226. Banner.dismiss('discover');
  227. this.setState({queryName: ''});
  228. browserHistory.push(
  229. normalizeUrl(view.getResultsViewUrlTarget(organization.slug))
  230. );
  231. }
  232. );
  233. };
  234. handleUpdateQuery = (event: React.MouseEvent<Element>) => {
  235. event.preventDefault();
  236. event.stopPropagation();
  237. const {api, organization, eventView, updateCallback, yAxis, setSavedQuery} =
  238. this.props;
  239. handleUpdateQuery(api, organization, eventView, yAxis).then(
  240. (savedQuery: SavedQuery) => {
  241. const view = EventView.fromSavedQuery(savedQuery);
  242. setSavedQuery(savedQuery);
  243. this.setState({queryName: ''});
  244. browserHistory.push(view.getResultsViewShortUrlTarget(organization.slug));
  245. updateCallback();
  246. }
  247. );
  248. };
  249. handleDeleteQuery = (event?: React.MouseEvent<Element>) => {
  250. event?.preventDefault();
  251. event?.stopPropagation();
  252. const {api, organization, eventView} = this.props;
  253. handleDeleteQuery(api, organization, eventView).then(() => {
  254. browserHistory.push(
  255. normalizeUrl({
  256. pathname: getDiscoverQueriesUrl(organization),
  257. query: {},
  258. })
  259. );
  260. });
  261. };
  262. handleCreateAlertSuccess = () => {
  263. const {organization} = this.props;
  264. trackAnalytics('discover_v2.create_alert_clicked', {
  265. organization,
  266. status: 'success',
  267. });
  268. };
  269. renderButtonViewSaved(disabled: boolean) {
  270. const {organization} = this.props;
  271. return (
  272. <Button
  273. onClick={() => {
  274. trackAnalytics('discover_v2.view_saved_queries', {organization});
  275. }}
  276. data-test-id="discover2-savedquery-button-view-saved"
  277. disabled={disabled}
  278. size="sm"
  279. icon={<IconStar isSolid />}
  280. to={getDiscoverQueriesUrl(organization)}
  281. >
  282. {t('Saved Queries')}
  283. </Button>
  284. );
  285. }
  286. renderButtonSaveAs(disabled: boolean) {
  287. const {queryName} = this.state;
  288. return (
  289. <SaveAsDropdown
  290. queryName={queryName}
  291. onChangeInput={this.onChangeInput}
  292. modifiedHandleCreateQuery={this.handleCreateQuery}
  293. disabled={disabled}
  294. />
  295. );
  296. }
  297. renderButtonSave(disabled: boolean) {
  298. const {isNewQuery, isEditingQuery} = this.state;
  299. if (!isNewQuery && !isEditingQuery) {
  300. return null;
  301. }
  302. // Existing query with edits, show save and save as.
  303. if (!isNewQuery && isEditingQuery) {
  304. return (
  305. <Fragment>
  306. <Button
  307. onClick={this.handleUpdateQuery}
  308. data-test-id="discover2-savedquery-button-update"
  309. disabled={disabled}
  310. size="sm"
  311. >
  312. <IconUpdate />
  313. {t('Save Changes')}
  314. </Button>
  315. {this.renderButtonSaveAs(disabled)}
  316. </Fragment>
  317. );
  318. }
  319. // Is a new query enable saveas
  320. return this.renderButtonSaveAs(disabled);
  321. }
  322. renderButtonDelete(disabled: boolean) {
  323. const {isNewQuery} = this.state;
  324. if (isNewQuery) {
  325. return null;
  326. }
  327. return (
  328. <Button
  329. data-test-id="discover2-savedquery-button-delete"
  330. onClick={this.handleDeleteQuery}
  331. disabled={disabled}
  332. size="sm"
  333. icon={<IconDelete />}
  334. aria-label={t('Delete')}
  335. />
  336. );
  337. }
  338. renderButtonCreateAlert() {
  339. const {eventView, organization, projects} = this.props;
  340. return (
  341. <GuideAnchor target="create_alert_from_discover">
  342. <CreateAlertFromViewButton
  343. eventView={eventView}
  344. organization={organization}
  345. projects={projects}
  346. onClick={this.handleCreateAlertSuccess}
  347. referrer="discover"
  348. size="sm"
  349. aria-label={t('Create Alert')}
  350. data-test-id="discover2-create-from-discover"
  351. />
  352. </GuideAnchor>
  353. );
  354. }
  355. renderButtonAddToDashboard() {
  356. const {organization, eventView, savedQuery, yAxis, router, location} = this.props;
  357. return (
  358. <Button
  359. key="add-dashboard-widget-from-discover"
  360. data-test-id="add-dashboard-widget-from-discover"
  361. size="sm"
  362. onClick={() =>
  363. handleAddQueryToDashboard({
  364. organization,
  365. location,
  366. eventView,
  367. query: savedQuery,
  368. yAxis,
  369. router,
  370. })
  371. }
  372. >
  373. {t('Add to Dashboard')}
  374. </Button>
  375. );
  376. }
  377. renderSaveAsHomepage(disabled: boolean) {
  378. const {
  379. api,
  380. organization,
  381. eventView,
  382. location,
  383. isHomepage,
  384. setHomepageQuery,
  385. homepageQuery,
  386. queryDataLoading,
  387. } = this.props;
  388. const buttonDisabled = disabled || queryDataLoading;
  389. const analyticsEventSource = isHomepage
  390. ? 'homepage'
  391. : eventView.id
  392. ? 'saved-query'
  393. : 'prebuilt-query';
  394. if (
  395. homepageQuery &&
  396. eventView.isEqualTo(EventView.fromSavedQuery(homepageQuery), ['id', 'name'])
  397. ) {
  398. return (
  399. <Button
  400. key="reset-discover-homepage"
  401. data-test-id="reset-discover-homepage"
  402. onClick={async () => {
  403. await handleResetHomepageQuery(api, organization);
  404. trackAnalytics('discover_v2.remove_default', {
  405. organization,
  406. source: analyticsEventSource,
  407. });
  408. setHomepageQuery(undefined);
  409. if (isHomepage) {
  410. const nextEventView = EventView.fromNewQueryWithLocation(
  411. DEFAULT_EVENT_VIEW,
  412. location
  413. );
  414. browserHistory.push({
  415. pathname: location.pathname,
  416. query: nextEventView.generateQueryStringObject(),
  417. });
  418. }
  419. }}
  420. size="sm"
  421. icon={<IconBookmark isSolid />}
  422. disabled={buttonDisabled}
  423. >
  424. {t('Remove Default')}
  425. </Button>
  426. );
  427. }
  428. return (
  429. <Button
  430. key="set-as-default"
  431. data-test-id="set-as-default"
  432. onClick={async () => {
  433. const updatedHomepageQuery = await handleUpdateHomepageQuery(
  434. api,
  435. organization,
  436. eventView.toNewQuery()
  437. );
  438. trackAnalytics('discover_v2.set_as_default', {
  439. organization,
  440. source: analyticsEventSource,
  441. });
  442. if (updatedHomepageQuery) {
  443. setHomepageQuery(updatedHomepageQuery);
  444. }
  445. }}
  446. size="sm"
  447. icon={<IconBookmark />}
  448. disabled={buttonDisabled}
  449. >
  450. {t('Set as Default')}
  451. </Button>
  452. );
  453. }
  454. renderQueryButton(renderFunc: (disabled: boolean) => React.ReactNode) {
  455. const {organization} = this.props;
  456. return (
  457. <Feature
  458. organization={organization}
  459. features="discover-query"
  460. hookName="feature-disabled:discover-saved-query-create"
  461. renderDisabled={renderDisabled}
  462. >
  463. {({hasFeature}) => renderFunc(!hasFeature || this.props.disabled)}
  464. </Feature>
  465. );
  466. }
  467. render() {
  468. const {organization, eventView, savedQuery, yAxis, router, location, isHomepage} =
  469. this.props;
  470. const contextMenuItems: MenuItemProps[] = [];
  471. if (organization.features.includes('dashboards-edit')) {
  472. contextMenuItems.push({
  473. key: 'add-to-dashboard',
  474. label: t('Add to Dashboard'),
  475. onAction: () => {
  476. handleAddQueryToDashboard({
  477. organization,
  478. location,
  479. eventView,
  480. query: savedQuery,
  481. yAxis,
  482. router,
  483. });
  484. },
  485. });
  486. }
  487. if (!isHomepage && savedQuery) {
  488. contextMenuItems.push({
  489. key: 'delete-saved-query',
  490. label: t('Delete Saved Query'),
  491. onAction: () => this.handleDeleteQuery(),
  492. });
  493. }
  494. const contextMenu = (
  495. <DropdownMenu
  496. items={contextMenuItems}
  497. trigger={triggerProps => (
  498. <Button
  499. {...triggerProps}
  500. aria-label={t('Discover Context Menu')}
  501. size="sm"
  502. onClick={e => {
  503. e.stopPropagation();
  504. e.preventDefault();
  505. triggerProps.onClick?.(e);
  506. }}
  507. icon={<IconEllipsis />}
  508. />
  509. )}
  510. position="bottom-end"
  511. offset={4}
  512. />
  513. );
  514. return (
  515. <ResponsiveButtonBar gap={1}>
  516. {this.renderQueryButton(disabled => this.renderSaveAsHomepage(disabled))}
  517. {this.renderQueryButton(disabled => this.renderButtonSave(disabled))}
  518. <Feature organization={organization} features="incidents">
  519. {({hasFeature}) => hasFeature && this.renderButtonCreateAlert()}
  520. </Feature>
  521. {contextMenuItems.length > 0 && contextMenu}
  522. {this.renderQueryButton(disabled => this.renderButtonViewSaved(disabled))}
  523. </ResponsiveButtonBar>
  524. );
  525. }
  526. }
  527. const ResponsiveButtonBar = styled(ButtonBar)`
  528. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  529. margin-top: 0;
  530. }
  531. `;
  532. const StyledOverlay = styled(Overlay)`
  533. padding: ${space(1)};
  534. `;
  535. const SaveAsButton = styled(Button)`
  536. width: 100%;
  537. `;
  538. const SaveAsInput = styled(InputControl)`
  539. margin-bottom: ${space(1)};
  540. `;
  541. const IconUpdate = styled('div')`
  542. display: inline-block;
  543. width: 10px;
  544. height: 10px;
  545. margin-right: ${space(0.75)};
  546. border-radius: 5px;
  547. background-color: ${p => p.theme.yellow300};
  548. `;
  549. export default withProjects(withApi(SavedQueryButtonGroup));