index.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. import {Fragment, PureComponent} from 'react';
  2. import type {InjectedRouter} from 'react-router';
  3. import {browserHistory} from 'react-router';
  4. import {useTheme} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import {FocusScope} from '@react-aria/focus';
  7. import {AnimatePresence} from 'framer-motion';
  8. import type {Location} from 'history';
  9. import isEqual from 'lodash/isEqual';
  10. import type {Client} from 'sentry/api';
  11. import Feature from 'sentry/components/acl/feature';
  12. import FeatureDisabled from 'sentry/components/acl/featureDisabled';
  13. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  14. import Banner from 'sentry/components/banner';
  15. import {Button} from 'sentry/components/button';
  16. import ButtonBar from 'sentry/components/buttonBar';
  17. import {CreateAlertFromViewButton} from 'sentry/components/createAlertButton';
  18. import type {MenuItemProps} from 'sentry/components/dropdownMenu';
  19. import {DropdownMenu} from 'sentry/components/dropdownMenu';
  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 type {Organization, Project, SavedQuery} from 'sentry/types';
  27. import {trackAnalytics} from 'sentry/utils/analytics';
  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 {handleAddQueryToDashboard} from 'sentry/views/discover/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(
  231. normalizeUrl(view.getResultsViewUrlTarget(organization.slug))
  232. );
  233. }
  234. );
  235. };
  236. handleUpdateQuery = (event: React.MouseEvent<Element>) => {
  237. event.preventDefault();
  238. event.stopPropagation();
  239. const {api, organization, eventView, updateCallback, yAxis, setSavedQuery} =
  240. this.props;
  241. handleUpdateQuery(api, organization, eventView, yAxis).then(
  242. (savedQuery: SavedQuery) => {
  243. const view = EventView.fromSavedQuery(savedQuery);
  244. setSavedQuery(savedQuery);
  245. this.setState({queryName: ''});
  246. browserHistory.push(view.getResultsViewShortUrlTarget(organization.slug));
  247. updateCallback();
  248. }
  249. );
  250. };
  251. handleDeleteQuery = (event?: React.MouseEvent<Element>) => {
  252. event?.preventDefault();
  253. event?.stopPropagation();
  254. const {api, organization, eventView} = this.props;
  255. handleDeleteQuery(api, organization, eventView).then(() => {
  256. browserHistory.push(
  257. normalizeUrl({
  258. pathname: getDiscoverQueriesUrl(organization),
  259. query: {},
  260. })
  261. );
  262. });
  263. };
  264. handleCreateAlertSuccess = () => {
  265. const {organization} = this.props;
  266. trackAnalytics('discover_v2.create_alert_clicked', {
  267. organization,
  268. status: 'success',
  269. });
  270. };
  271. renderButtonViewSaved(disabled: boolean) {
  272. const {organization} = this.props;
  273. return (
  274. <Button
  275. onClick={() => {
  276. trackAnalytics('discover_v2.view_saved_queries', {organization});
  277. }}
  278. data-test-id="discover2-savedquery-button-view-saved"
  279. disabled={disabled}
  280. size="sm"
  281. icon={<IconStar isSolid />}
  282. to={getDiscoverQueriesUrl(organization)}
  283. >
  284. {t('Saved Queries')}
  285. </Button>
  286. );
  287. }
  288. renderButtonSaveAs(disabled: boolean) {
  289. const {queryName} = this.state;
  290. return (
  291. <SaveAsDropdown
  292. queryName={queryName}
  293. onChangeInput={this.onChangeInput}
  294. modifiedHandleCreateQuery={this.handleCreateQuery}
  295. disabled={disabled}
  296. />
  297. );
  298. }
  299. renderButtonSave(disabled: boolean) {
  300. const {isNewQuery, isEditingQuery} = this.state;
  301. if (!isNewQuery && !isEditingQuery) {
  302. return null;
  303. }
  304. // Existing query with edits, show save and save as.
  305. if (!isNewQuery && isEditingQuery) {
  306. return (
  307. <Fragment>
  308. <Button
  309. onClick={this.handleUpdateQuery}
  310. data-test-id="discover2-savedquery-button-update"
  311. disabled={disabled}
  312. size="sm"
  313. >
  314. <IconUpdate />
  315. {t('Save Changes')}
  316. </Button>
  317. {this.renderButtonSaveAs(disabled)}
  318. </Fragment>
  319. );
  320. }
  321. // Is a new query enable saveas
  322. return this.renderButtonSaveAs(disabled);
  323. }
  324. renderButtonDelete(disabled: boolean) {
  325. const {isNewQuery} = this.state;
  326. if (isNewQuery) {
  327. return null;
  328. }
  329. return (
  330. <Button
  331. data-test-id="discover2-savedquery-button-delete"
  332. onClick={this.handleDeleteQuery}
  333. disabled={disabled}
  334. size="sm"
  335. icon={<IconDelete />}
  336. aria-label={t('Delete')}
  337. />
  338. );
  339. }
  340. renderButtonCreateAlert() {
  341. const {eventView, organization, projects} = this.props;
  342. return (
  343. <GuideAnchor target="create_alert_from_discover">
  344. <CreateAlertFromViewButton
  345. eventView={eventView}
  346. organization={organization}
  347. projects={projects}
  348. onClick={this.handleCreateAlertSuccess}
  349. referrer="discover"
  350. size="sm"
  351. aria-label={t('Create Alert')}
  352. data-test-id="discover2-create-from-discover"
  353. />
  354. </GuideAnchor>
  355. );
  356. }
  357. renderButtonAddToDashboard() {
  358. const {organization, eventView, savedQuery, yAxis, router, location} = this.props;
  359. return (
  360. <Button
  361. key="add-dashboard-widget-from-discover"
  362. data-test-id="add-dashboard-widget-from-discover"
  363. size="sm"
  364. onClick={() =>
  365. handleAddQueryToDashboard({
  366. organization,
  367. location,
  368. eventView,
  369. query: savedQuery,
  370. yAxis,
  371. router,
  372. })
  373. }
  374. >
  375. {t('Add to Dashboard')}
  376. </Button>
  377. );
  378. }
  379. renderSaveAsHomepage(disabled: boolean) {
  380. const {
  381. api,
  382. organization,
  383. eventView,
  384. location,
  385. isHomepage,
  386. setHomepageQuery,
  387. homepageQuery,
  388. queryDataLoading,
  389. } = this.props;
  390. const buttonDisabled = disabled || queryDataLoading;
  391. const analyticsEventSource = isHomepage
  392. ? 'homepage'
  393. : eventView.id
  394. ? 'saved-query'
  395. : 'prebuilt-query';
  396. if (
  397. homepageQuery &&
  398. eventView.isEqualTo(EventView.fromSavedQuery(homepageQuery), ['id', 'name'])
  399. ) {
  400. return (
  401. <Button
  402. key="reset-discover-homepage"
  403. data-test-id="reset-discover-homepage"
  404. onClick={async () => {
  405. await handleResetHomepageQuery(api, organization);
  406. trackAnalytics('discover_v2.remove_default', {
  407. organization,
  408. source: analyticsEventSource,
  409. });
  410. setHomepageQuery(undefined);
  411. if (isHomepage) {
  412. const nextEventView = EventView.fromNewQueryWithLocation(
  413. DEFAULT_EVENT_VIEW,
  414. location
  415. );
  416. browserHistory.push({
  417. pathname: location.pathname,
  418. query: nextEventView.generateQueryStringObject(),
  419. });
  420. }
  421. }}
  422. size="sm"
  423. icon={<IconBookmark isSolid />}
  424. disabled={buttonDisabled}
  425. >
  426. {t('Remove Default')}
  427. </Button>
  428. );
  429. }
  430. return (
  431. <Button
  432. key="set-as-default"
  433. data-test-id="set-as-default"
  434. onClick={async () => {
  435. const updatedHomepageQuery = await handleUpdateHomepageQuery(
  436. api,
  437. organization,
  438. eventView.toNewQuery()
  439. );
  440. trackAnalytics('discover_v2.set_as_default', {
  441. organization,
  442. source: analyticsEventSource,
  443. });
  444. if (updatedHomepageQuery) {
  445. setHomepageQuery(updatedHomepageQuery);
  446. }
  447. }}
  448. size="sm"
  449. icon={<IconBookmark />}
  450. disabled={buttonDisabled}
  451. >
  452. {t('Set as Default')}
  453. </Button>
  454. );
  455. }
  456. renderQueryButton(renderFunc: (disabled: boolean) => React.ReactNode) {
  457. const {organization} = this.props;
  458. return (
  459. <Feature
  460. organization={organization}
  461. features="discover-query"
  462. hookName="feature-disabled:discover-saved-query-create"
  463. renderDisabled={renderDisabled}
  464. >
  465. {({hasFeature}) => renderFunc(!hasFeature || this.props.disabled)}
  466. </Feature>
  467. );
  468. }
  469. render() {
  470. const {organization, eventView, savedQuery, yAxis, router, location, isHomepage} =
  471. this.props;
  472. const contextMenuItems: MenuItemProps[] = [];
  473. if (organization.features.includes('dashboards-edit')) {
  474. contextMenuItems.push({
  475. key: 'add-to-dashboard',
  476. label: t('Add to Dashboard'),
  477. onAction: () => {
  478. handleAddQueryToDashboard({
  479. organization,
  480. location,
  481. eventView,
  482. query: savedQuery,
  483. yAxis,
  484. router,
  485. });
  486. },
  487. });
  488. }
  489. if (!isHomepage && savedQuery) {
  490. contextMenuItems.push({
  491. key: 'delete-saved-query',
  492. label: t('Delete Saved Query'),
  493. onAction: () => this.handleDeleteQuery(),
  494. });
  495. }
  496. const contextMenu = (
  497. <DropdownMenu
  498. items={contextMenuItems}
  499. trigger={triggerProps => (
  500. <Button
  501. {...triggerProps}
  502. aria-label={t('Discover Context Menu')}
  503. size="sm"
  504. onClick={e => {
  505. e.stopPropagation();
  506. e.preventDefault();
  507. triggerProps.onClick?.(e);
  508. }}
  509. icon={<IconEllipsis />}
  510. />
  511. )}
  512. position="bottom-end"
  513. offset={4}
  514. />
  515. );
  516. return (
  517. <ResponsiveButtonBar gap={1}>
  518. {this.renderQueryButton(disabled => this.renderSaveAsHomepage(disabled))}
  519. {this.renderQueryButton(disabled => this.renderButtonSave(disabled))}
  520. <Feature organization={organization} features="incidents">
  521. {({hasFeature}) => hasFeature && this.renderButtonCreateAlert()}
  522. </Feature>
  523. {contextMenuItems.length > 0 && contextMenu}
  524. {this.renderQueryButton(disabled => this.renderButtonViewSaved(disabled))}
  525. </ResponsiveButtonBar>
  526. );
  527. }
  528. }
  529. const ResponsiveButtonBar = styled(ButtonBar)`
  530. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  531. margin-top: 0;
  532. }
  533. `;
  534. const StyledOverlay = styled(Overlay)`
  535. padding: ${space(1)};
  536. `;
  537. const SaveAsButton = styled(Button)`
  538. width: 100%;
  539. `;
  540. const SaveAsInput = styled(InputControl)`
  541. margin-bottom: ${space(1)};
  542. `;
  543. const IconUpdate = styled('div')`
  544. display: inline-block;
  545. width: 10px;
  546. height: 10px;
  547. margin-right: ${space(0.75)};
  548. border-radius: 5px;
  549. background-color: ${p => p.theme.yellow300};
  550. `;
  551. export default withProjects(withApi(SavedQueryButtonGroup));