index.tsx 19 KB

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