index.tsx 18 KB

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