monitorCreateForm.tsx 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import {Fragment, useRef} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {css} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import {Observer} from 'mobx-react';
  6. import NumberField from 'sentry/components/forms/fields/numberField';
  7. import SelectField from 'sentry/components/forms/fields/selectField';
  8. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  9. import TextField from 'sentry/components/forms/fields/textField';
  10. import Form from 'sentry/components/forms/form';
  11. import FormModel from 'sentry/components/forms/model';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import {timezoneOptions} from 'sentry/data/timezones';
  15. import {t} from 'sentry/locale';
  16. import HookStore from 'sentry/stores/hookStore';
  17. import {space} from 'sentry/styles/space';
  18. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  19. import commonTheme from 'sentry/utils/theme';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import usePageFilters from 'sentry/utils/usePageFilters';
  22. import useProjects from 'sentry/utils/useProjects';
  23. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  24. import {MockTimelineVisualization} from 'sentry/views/monitors/components/mockTimelineVisualization';
  25. import {
  26. DEFAULT_CRONTAB,
  27. DEFAULT_MONITOR_TYPE,
  28. mapMonitorFormErrors,
  29. transformMonitorFormData,
  30. } from 'sentry/views/monitors/components/monitorForm';
  31. import type {Monitor} from 'sentry/views/monitors/types';
  32. import {ScheduleType} from 'sentry/views/monitors/types';
  33. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  34. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  35. const DEFAULT_SCHEDULE_CONFIG = {
  36. scheduleType: 'crontab',
  37. cronSchedule: DEFAULT_CRONTAB,
  38. intervalFrequency: '1',
  39. intervalUnit: 'day',
  40. };
  41. export default function MonitorCreateForm() {
  42. const organization = useOrganization();
  43. const {projects} = useProjects();
  44. const {selection} = usePageFilters();
  45. const monitorCreationCallbacks = HookStore.get('callback:on-monitor-created');
  46. const form = useRef(
  47. new FormModel({
  48. transformData: transformMonitorFormData,
  49. mapFormErrors: mapMonitorFormErrors,
  50. })
  51. );
  52. const selectedProjectId = selection.projects[0];
  53. const selectedProject = selectedProjectId
  54. ? projects.find(p => p.id === selectedProjectId + '')
  55. : null;
  56. const isSuperuser = isActiveSuperuser();
  57. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  58. function onCreateMonitor(data: Monitor) {
  59. const endpointOptions = {
  60. query: {
  61. project: selection.projects,
  62. environment: selection.environments,
  63. },
  64. };
  65. browserHistory.push(
  66. normalizeUrl({
  67. pathname: `/organizations/${organization.slug}/crons/${data.project.slug}/${data.slug}/`,
  68. query: endpointOptions.query,
  69. })
  70. );
  71. monitorCreationCallbacks.map(cb => cb(organization));
  72. }
  73. function changeScheduleType(type: ScheduleType) {
  74. form.current.setValue('config.schedule_type', type);
  75. }
  76. return (
  77. <Form
  78. allowUndo
  79. requireChanges
  80. apiEndpoint={`/organizations/${organization.slug}/monitors/`}
  81. apiMethod="POST"
  82. model={form.current}
  83. initialData={{
  84. project: selectedProject ? selectedProject.slug : null,
  85. type: DEFAULT_MONITOR_TYPE,
  86. 'config.schedule_type': DEFAULT_SCHEDULE_CONFIG.scheduleType,
  87. }}
  88. onSubmitSuccess={onCreateMonitor}
  89. submitLabel={t('Create')}
  90. >
  91. <FieldContainer>
  92. <MultiColumnInput columns="250px 1fr">
  93. <StyledSentryProjectSelectorField
  94. name="project"
  95. projects={filteredProjects}
  96. placeholder={t('Choose Project')}
  97. disabledReason={t('Existing monitors cannot be moved between projects')}
  98. valueIsSlug
  99. required
  100. stacked
  101. inline={false}
  102. />
  103. <StyledTextField
  104. name="name"
  105. placeholder={t('My Cron Job')}
  106. required
  107. stacked
  108. inline={false}
  109. />
  110. </MultiColumnInput>
  111. <LabelText>{t('SCHEDULE')}</LabelText>
  112. <ScheduleOptions>
  113. <Observer>
  114. {() => {
  115. const currScheduleType = form.current.getValue('config.schedule_type');
  116. const selectedCrontab = currScheduleType === ScheduleType.CRONTAB;
  117. const parsedSchedule = form.current.getError('config.schedule')
  118. ? ''
  119. : crontabAsText(
  120. form.current.getValue('config.schedule')?.toString() ?? ''
  121. );
  122. return (
  123. <Fragment>
  124. <SchedulePanel
  125. highlighted={selectedCrontab}
  126. onClick={() => changeScheduleType(ScheduleType.CRONTAB)}
  127. >
  128. <PanelBody withPadding>
  129. <ScheduleLabel>{t('Crontab Schedule')}</ScheduleLabel>
  130. <MultiColumnInput columns="1fr 1fr">
  131. <StyledTextField
  132. name="config.schedule"
  133. placeholder="* * * * *"
  134. defaultValue={DEFAULT_SCHEDULE_CONFIG.cronSchedule}
  135. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  136. required={selectedCrontab}
  137. stacked
  138. inline={false}
  139. hideControlState={!selectedCrontab}
  140. />
  141. <StyledSelectField
  142. name="config.timezone"
  143. defaultValue="UTC"
  144. options={timezoneOptions}
  145. required={selectedCrontab}
  146. stacked
  147. inline={false}
  148. />
  149. <CronstrueText>{parsedSchedule}</CronstrueText>
  150. </MultiColumnInput>
  151. </PanelBody>
  152. </SchedulePanel>
  153. <SchedulePanel
  154. highlighted={!selectedCrontab}
  155. onClick={() => changeScheduleType(ScheduleType.INTERVAL)}
  156. >
  157. <PanelBody withPadding>
  158. <ScheduleLabel>{t('Interval Schedule')}</ScheduleLabel>
  159. <MultiColumnInput columns="auto 1fr 2fr">
  160. <Label>{t('Every')}</Label>
  161. <StyledNumberField
  162. name="config.schedule.frequency"
  163. placeholder="e.g. 1"
  164. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalFrequency}
  165. required={!selectedCrontab}
  166. stacked
  167. inline={false}
  168. hideControlState={selectedCrontab}
  169. />
  170. <StyledSelectField
  171. name="config.schedule.interval"
  172. options={getScheduleIntervals(
  173. Number(
  174. form.current.getValue('config.schedule.frequency') ?? 1
  175. )
  176. )}
  177. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalUnit}
  178. required={!selectedCrontab}
  179. stacked
  180. inline={false}
  181. />
  182. </MultiColumnInput>
  183. </PanelBody>
  184. </SchedulePanel>
  185. </Fragment>
  186. );
  187. }}
  188. </Observer>
  189. </ScheduleOptions>
  190. <Observer>
  191. {() => {
  192. const scheduleType = form.current.getValue('config.schedule_type');
  193. const cronSchedule = form.current.getValue('config.schedule');
  194. const intervalFrequency = form.current.getValue('config.schedule.frequency');
  195. const intervalUnit = form.current.getValue('config.schedule.interval');
  196. const schedule = {
  197. scheduleType,
  198. cronSchedule,
  199. intervalFrequency,
  200. intervalUnit,
  201. };
  202. return <MockTimelineVisualization schedule={schedule} />;
  203. }}
  204. </Observer>
  205. </FieldContainer>
  206. </Form>
  207. );
  208. }
  209. const FieldContainer = styled('div')`
  210. width: 800px;
  211. `;
  212. const SchedulePanel = styled(Panel)<{highlighted: boolean}>`
  213. border-radius: 0 ${space(0.75)} ${space(0.75)} 0;
  214. ${p =>
  215. p.highlighted
  216. ? css`
  217. border: 2px solid ${p.theme.purple300};
  218. `
  219. : css`
  220. padding: 1px;
  221. `};
  222. &:first-child {
  223. border-radius: ${space(0.75)} 0 0 ${space(0.75)};
  224. }
  225. `;
  226. const ScheduleLabel = styled('div')`
  227. font-weight: bold;
  228. margin-bottom: ${space(2)};
  229. `;
  230. const Label = styled('div')`
  231. font-weight: bold;
  232. color: ${p => p.theme.subText};
  233. `;
  234. const LabelText = styled(Label)`
  235. margin-top: ${space(2)};
  236. margin-bottom: ${space(1)};
  237. `;
  238. const ScheduleOptions = styled('div')`
  239. display: grid;
  240. grid-template-columns: 1fr 1fr;
  241. `;
  242. const MultiColumnInput = styled('div')<{columns?: string}>`
  243. display: grid;
  244. align-items: center;
  245. gap: ${space(1)};
  246. grid-template-columns: ${p => p.columns};
  247. `;
  248. const CronstrueText = styled(LabelText)`
  249. font-weight: normal;
  250. font-size: ${p => p.theme.fontSizeExtraSmall};
  251. font-family: ${p => p.theme.text.familyMono};
  252. grid-column: auto / span 2;
  253. `;
  254. const StyledNumberField = styled(NumberField)`
  255. padding: 0;
  256. `;
  257. const StyledSelectField = styled(SelectField)`
  258. padding: 0;
  259. `;
  260. const StyledTextField = styled(TextField)`
  261. padding: 0;
  262. `;
  263. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  264. padding: 0;
  265. `;