index.tsx 17 KB

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