index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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 {Hovercard} from 'sentry/components/hovercard';
  18. import InputControl from 'sentry/components/input';
  19. import {Overlay, PositionWrapper} from 'sentry/components/overlay';
  20. import {IconDelete, IconStar} from 'sentry/icons';
  21. import {t} from 'sentry/locale';
  22. import space from 'sentry/styles/space';
  23. import {Organization, Project, SavedQuery} from 'sentry/types';
  24. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  25. import EventView from 'sentry/utils/discover/eventView';
  26. import {getDiscoverQueriesUrl} from 'sentry/utils/discover/urls';
  27. import useOverlay from 'sentry/utils/useOverlay';
  28. import withApi from 'sentry/utils/withApi';
  29. import withProjects from 'sentry/utils/withProjects';
  30. import {handleAddQueryToDashboard} from 'sentry/views/eventsV2/utils';
  31. import {handleCreateQuery, handleDeleteQuery, handleUpdateQuery} from './utils';
  32. type SaveAsDropdownProps = {
  33. disabled: boolean;
  34. modifiedHandleCreateQuery: (e: React.MouseEvent<Element>) => void;
  35. onChangeInput: (e: React.FormEvent<HTMLInputElement>) => void;
  36. queryName: string;
  37. };
  38. function SaveAsDropdown({
  39. queryName,
  40. disabled,
  41. onChangeInput,
  42. modifiedHandleCreateQuery,
  43. }: SaveAsDropdownProps) {
  44. const {isOpen, triggerProps, overlayProps, arrowProps} = useOverlay();
  45. const theme = useTheme();
  46. return (
  47. <div>
  48. <Button
  49. {...triggerProps}
  50. icon={<IconStar />}
  51. aria-label={t('Save as')}
  52. disabled={disabled}
  53. >
  54. {`${t('Save as')}\u2026`}
  55. </Button>
  56. <AnimatePresence>
  57. {isOpen && (
  58. <FocusScope contain restoreFocus autoFocus>
  59. <PositionWrapper zIndex={theme.zIndex.dropdown} {...overlayProps}>
  60. <StyledOverlay arrowProps={arrowProps} animated>
  61. <SaveAsInput
  62. type="text"
  63. name="query_name"
  64. placeholder={t('Display name')}
  65. value={queryName || ''}
  66. onChange={onChangeInput}
  67. disabled={disabled}
  68. />
  69. <SaveAsButton
  70. onClick={modifiedHandleCreateQuery}
  71. priority="primary"
  72. disabled={disabled || !queryName}
  73. >
  74. {t('Save for Org')}
  75. </SaveAsButton>
  76. </StyledOverlay>
  77. </PositionWrapper>
  78. </FocusScope>
  79. )}
  80. </AnimatePresence>
  81. </div>
  82. );
  83. }
  84. type DefaultProps = {
  85. disabled: boolean;
  86. };
  87. type Props = DefaultProps & {
  88. api: Client;
  89. eventView: EventView;
  90. /**
  91. * DO NOT USE `Location` TO GENERATE `EventView` IN THIS COMPONENT.
  92. *
  93. * In this component, state is generated from EventView and SavedQueriesStore.
  94. * Using Location to rebuild EventView will break the tests. `Location` is
  95. * passed down only because it is needed for navigation.
  96. */
  97. location: Location;
  98. organization: Organization;
  99. projects: Project[];
  100. router: InjectedRouter;
  101. savedQuery: SavedQuery | undefined;
  102. savedQueryLoading: boolean;
  103. updateCallback: () => void;
  104. yAxis: string[];
  105. };
  106. type State = {
  107. isEditingQuery: boolean;
  108. isNewQuery: boolean;
  109. queryName: string;
  110. };
  111. class SavedQueryButtonGroup extends PureComponent<Props, State> {
  112. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State): State {
  113. const {eventView: nextEventView, savedQuery, savedQueryLoading, yAxis} = nextProps;
  114. // For a new unsaved query
  115. if (!savedQuery) {
  116. return {
  117. isNewQuery: true,
  118. isEditingQuery: false,
  119. queryName: prevState.queryName || '',
  120. };
  121. }
  122. if (savedQueryLoading) {
  123. return prevState;
  124. }
  125. const savedEventView = EventView.fromSavedQuery(savedQuery);
  126. // Switching from a SavedQuery to another SavedQuery
  127. if (savedEventView.id !== nextEventView.id) {
  128. return {
  129. isNewQuery: false,
  130. isEditingQuery: false,
  131. queryName: '',
  132. };
  133. }
  134. // For modifying a SavedQuery
  135. const isEqualQuery = nextEventView.isEqualTo(savedEventView);
  136. // undefined saved yAxis defaults to count() and string values are converted to array
  137. const isEqualYAxis = isEqual(
  138. yAxis,
  139. !savedQuery.yAxis
  140. ? ['count()']
  141. : typeof savedQuery.yAxis === 'string'
  142. ? [savedQuery.yAxis]
  143. : savedQuery.yAxis
  144. );
  145. return {
  146. isNewQuery: false,
  147. isEditingQuery: !isEqualQuery || !isEqualYAxis,
  148. // HACK(leedongwei): See comment at SavedQueryButtonGroup.onFocusInput
  149. queryName: prevState.queryName || '',
  150. };
  151. }
  152. /**
  153. * Stop propagation for the input and container so people can interact with
  154. * the inputs in the dropdown.
  155. */
  156. static stopEventPropagation = (event: React.MouseEvent) => {
  157. const capturedElements = ['LI', 'INPUT'];
  158. if (
  159. event.target instanceof Element &&
  160. capturedElements.includes(event.target.nodeName)
  161. ) {
  162. event.preventDefault();
  163. event.stopPropagation();
  164. }
  165. };
  166. static defaultProps: DefaultProps = {
  167. disabled: false,
  168. };
  169. state: State = {
  170. isNewQuery: true,
  171. isEditingQuery: false,
  172. queryName: '',
  173. };
  174. onChangeInput = (event: React.FormEvent<HTMLInputElement>) => {
  175. const target = event.target as HTMLInputElement;
  176. this.setState({queryName: target.value});
  177. };
  178. /**
  179. * There are two ways to create a query
  180. * 1) Creating a query from scratch and saving it
  181. * 2) Modifying an existing query and saving it
  182. */
  183. handleCreateQuery = (event: React.MouseEvent<Element>) => {
  184. event.preventDefault();
  185. event.stopPropagation();
  186. const {api, organization, eventView, yAxis} = this.props;
  187. if (!this.state.queryName) {
  188. return;
  189. }
  190. const nextEventView = eventView.clone();
  191. nextEventView.name = this.state.queryName;
  192. // Checks if "Save as" button is clicked from a clean state, or it is
  193. // clicked while modifying an existing query
  194. const isNewQuery = !eventView.id;
  195. handleCreateQuery(api, organization, nextEventView, yAxis, isNewQuery).then(
  196. (savedQuery: SavedQuery) => {
  197. const view = EventView.fromSavedQuery(savedQuery);
  198. Banner.dismiss('discover');
  199. this.setState({queryName: ''});
  200. browserHistory.push(view.getResultsViewUrlTarget(organization.slug));
  201. }
  202. );
  203. };
  204. handleUpdateQuery = (event: React.MouseEvent<Element>) => {
  205. event.preventDefault();
  206. event.stopPropagation();
  207. const {api, organization, eventView, updateCallback, yAxis} = this.props;
  208. handleUpdateQuery(api, organization, eventView, yAxis).then(
  209. (savedQuery: SavedQuery) => {
  210. const view = EventView.fromSavedQuery(savedQuery);
  211. this.setState({queryName: ''});
  212. browserHistory.push(view.getResultsViewShortUrlTarget(organization.slug));
  213. updateCallback();
  214. }
  215. );
  216. };
  217. handleDeleteQuery = (event: React.MouseEvent<Element>) => {
  218. event.preventDefault();
  219. event.stopPropagation();
  220. const {api, organization, eventView} = this.props;
  221. handleDeleteQuery(api, organization, eventView).then(() => {
  222. browserHistory.push({
  223. pathname: getDiscoverQueriesUrl(organization),
  224. query: {},
  225. });
  226. });
  227. };
  228. handleCreateAlertSuccess = () => {
  229. const {organization} = this.props;
  230. trackAnalyticsEvent({
  231. eventKey: 'discover_v2.create_alert_clicked',
  232. eventName: 'Discoverv2: Create alert clicked',
  233. status: 'success',
  234. organization_id: organization.id,
  235. url: window.location.href,
  236. });
  237. };
  238. renderButtonSaveAs(disabled: boolean) {
  239. const {queryName} = this.state;
  240. return (
  241. <SaveAsDropdown
  242. queryName={queryName}
  243. onChangeInput={this.onChangeInput}
  244. modifiedHandleCreateQuery={this.handleCreateQuery}
  245. disabled={disabled}
  246. />
  247. );
  248. }
  249. renderButtonSave(disabled: boolean) {
  250. const {isNewQuery, isEditingQuery} = this.state;
  251. // Existing query that hasn't been modified.
  252. if (!isNewQuery && !isEditingQuery) {
  253. return (
  254. <Button
  255. icon={<IconStar color="yellow100" isSolid size="sm" />}
  256. disabled
  257. data-test-id="discover2-savedquery-button-saved"
  258. >
  259. {t('Saved for Org')}
  260. </Button>
  261. );
  262. }
  263. // Existing query with edits, show save and save as.
  264. if (!isNewQuery && isEditingQuery) {
  265. return (
  266. <Fragment>
  267. <Button
  268. onClick={this.handleUpdateQuery}
  269. data-test-id="discover2-savedquery-button-update"
  270. disabled={disabled}
  271. >
  272. <IconUpdate />
  273. {t('Save Changes')}
  274. </Button>
  275. {this.renderButtonSaveAs(disabled)}
  276. </Fragment>
  277. );
  278. }
  279. // Is a new query enable saveas
  280. return this.renderButtonSaveAs(disabled);
  281. }
  282. renderButtonDelete(disabled: boolean) {
  283. const {isNewQuery} = this.state;
  284. if (isNewQuery) {
  285. return null;
  286. }
  287. return (
  288. <Button
  289. data-test-id="discover2-savedquery-button-delete"
  290. onClick={this.handleDeleteQuery}
  291. disabled={disabled}
  292. icon={<IconDelete />}
  293. aria-label={t('Delete')}
  294. />
  295. );
  296. }
  297. renderButtonCreateAlert() {
  298. const {eventView, organization, projects} = this.props;
  299. return (
  300. <GuideAnchor target="create_alert_from_discover">
  301. <CreateAlertFromViewButton
  302. eventView={eventView}
  303. organization={organization}
  304. projects={projects}
  305. onClick={this.handleCreateAlertSuccess}
  306. referrer="discover"
  307. aria-label={t('Create Alert')}
  308. data-test-id="discover2-create-from-discover"
  309. />
  310. </GuideAnchor>
  311. );
  312. }
  313. renderButtonAddToDashboard() {
  314. const {organization, eventView, savedQuery, yAxis, router, location} = this.props;
  315. return (
  316. <Button
  317. key="add-dashboard-widget-from-discover"
  318. data-test-id="add-dashboard-widget-from-discover"
  319. onClick={() =>
  320. handleAddQueryToDashboard({
  321. organization,
  322. location,
  323. eventView,
  324. query: savedQuery,
  325. yAxis,
  326. router,
  327. })
  328. }
  329. >
  330. {t('Add to Dashboard')}
  331. </Button>
  332. );
  333. }
  334. render() {
  335. const {organization} = this.props;
  336. const renderDisabled = p => (
  337. <Hovercard
  338. body={
  339. <FeatureDisabled
  340. features={p.features}
  341. hideHelpToggle
  342. message={t('Discover queries are disabled')}
  343. featureName={t('Discover queries')}
  344. />
  345. }
  346. >
  347. {p.children(p)}
  348. </Hovercard>
  349. );
  350. const renderQueryButton = (renderFunc: (disabled: boolean) => React.ReactNode) => {
  351. return (
  352. <Feature
  353. organization={organization}
  354. features={['discover-query']}
  355. hookName="feature-disabled:discover-saved-query-create"
  356. renderDisabled={renderDisabled}
  357. >
  358. {({hasFeature}) => renderFunc(!hasFeature || this.props.disabled)}
  359. </Feature>
  360. );
  361. };
  362. return (
  363. <ResponsiveButtonBar gap={1}>
  364. {renderQueryButton(disabled => this.renderButtonSave(disabled))}
  365. <Feature organization={organization} features={['incidents']}>
  366. {({hasFeature}) => hasFeature && this.renderButtonCreateAlert()}
  367. </Feature>
  368. <Feature organization={organization} features={['dashboards-edit']}>
  369. {({hasFeature}) => hasFeature && this.renderButtonAddToDashboard()}
  370. </Feature>
  371. {renderQueryButton(disabled => this.renderButtonDelete(disabled))}
  372. </ResponsiveButtonBar>
  373. );
  374. }
  375. }
  376. const ResponsiveButtonBar = styled(ButtonBar)`
  377. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  378. margin-top: 0;
  379. }
  380. `;
  381. const StyledOverlay = styled(Overlay)`
  382. padding: ${space(1)};
  383. `;
  384. const SaveAsButton = styled(Button)`
  385. width: 100%;
  386. `;
  387. const SaveAsInput = styled(InputControl)`
  388. height: 40px;
  389. margin-bottom: ${space(1)};
  390. `;
  391. const IconUpdate = styled('div')`
  392. display: inline-block;
  393. width: 10px;
  394. height: 10px;
  395. margin-right: ${space(0.75)};
  396. border-radius: 5px;
  397. background-color: ${p => p.theme.yellow300};
  398. `;
  399. export default withProjects(withApi(SavedQueryButtonGroup));