index.tsx 15 KB

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