eventInputName.tsx 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import {browserHistory} from 'react-router';
  2. import EditableText from 'sentry/components/editableText';
  3. import * as Layout from 'sentry/components/layouts/thirds';
  4. import {t} from 'sentry/locale';
  5. import {Organization, SavedQuery} from 'sentry/types';
  6. import EventView from 'sentry/utils/discover/eventView';
  7. import useApi from 'sentry/utils/useApi';
  8. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  9. import {handleUpdateQueryName} from './savedQuery/utils';
  10. type Props = {
  11. eventView: EventView;
  12. organization: Organization;
  13. isHomepage?: boolean;
  14. savedQuery?: SavedQuery;
  15. };
  16. const NAME_DEFAULT = t('Untitled query');
  17. const HOMEPAGE_DEFAULT = t('New Query');
  18. /**
  19. * Allows user to edit the name of the query.
  20. * By pressing Enter or clicking outside the component, the changes will be saved, if valid.
  21. */
  22. function EventInputName({organization, eventView, savedQuery, isHomepage}: Props) {
  23. const api = useApi();
  24. function handleChange(nextQueryName: string) {
  25. // Do not update automatically if
  26. // 1) It is a new query
  27. // 2) The new name is same as the old name
  28. if (!savedQuery || savedQuery.name === nextQueryName) {
  29. return;
  30. }
  31. // This ensures that we are updating SavedQuery.name only.
  32. // Changes on QueryBuilder table will not be saved.
  33. const nextEventView = EventView.fromSavedQuery({
  34. ...savedQuery,
  35. name: nextQueryName,
  36. });
  37. handleUpdateQueryName(api, organization, nextEventView).then(
  38. (_updatedQuery: SavedQuery) => {
  39. // The current eventview may have changes that are not explicitly saved.
  40. // So, we just preserve them and change its name
  41. const renamedEventView = eventView.clone();
  42. renamedEventView.name = nextQueryName;
  43. browserHistory.push(
  44. normalizeUrl(renamedEventView.getResultsViewUrlTarget(organization.slug))
  45. );
  46. }
  47. );
  48. }
  49. const value = isHomepage ? HOMEPAGE_DEFAULT : eventView.name || NAME_DEFAULT;
  50. return (
  51. <Layout.Title data-test-id={`discover2-query-name-${value}`}>
  52. <EditableText
  53. value={value}
  54. onChange={handleChange}
  55. isDisabled={!eventView.id || isHomepage}
  56. errorMessage={t('Please set a name for this query')}
  57. />
  58. </Layout.Title>
  59. );
  60. }
  61. export default EventInputName;