index.tsx 17 KB

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