index.tsx 14 KB

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