monitorCreateForm.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 type {Monitor} from 'sentry/views/monitors/types';
  25. import {ScheduleType} from 'sentry/views/monitors/types';
  26. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  27. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  28. import {MockTimelineVisualization} from './mockTimelineVisualization';
  29. import {
  30. DEFAULT_CRONTAB,
  31. DEFAULT_MONITOR_TYPE,
  32. mapMonitorFormErrors,
  33. transformMonitorFormData,
  34. } from './monitorForm';
  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.scheduleType', 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.scheduleType': 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.scheduleType');
  116. const selectedCrontab = currScheduleType === ScheduleType.CRONTAB;
  117. const parsedSchedule = form.current.getError('config.schedule')
  118. ? null
  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>
  150. {parsedSchedule ?? t('(invalid schedule)')}
  151. </CronstrueText>
  152. </MultiColumnInput>
  153. </PanelBody>
  154. </SchedulePanel>
  155. <SchedulePanel
  156. highlighted={!selectedCrontab}
  157. onClick={() => changeScheduleType(ScheduleType.INTERVAL)}
  158. >
  159. <PanelBody withPadding>
  160. <ScheduleLabel>{t('Interval Schedule')}</ScheduleLabel>
  161. <MultiColumnInput columns="auto 1fr 2fr">
  162. <Label>{t('Every')}</Label>
  163. <StyledNumberField
  164. name="config.schedule.frequency"
  165. placeholder="e.g. 1"
  166. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalFrequency}
  167. required={!selectedCrontab}
  168. stacked
  169. inline={false}
  170. hideControlState={selectedCrontab}
  171. />
  172. <StyledSelectField
  173. name="config.schedule.interval"
  174. options={getScheduleIntervals(
  175. Number(
  176. form.current.getValue('config.schedule.frequency') ?? 1
  177. )
  178. )}
  179. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalUnit}
  180. required={!selectedCrontab}
  181. stacked
  182. inline={false}
  183. />
  184. </MultiColumnInput>
  185. </PanelBody>
  186. </SchedulePanel>
  187. </Fragment>
  188. );
  189. }}
  190. </Observer>
  191. </ScheduleOptions>
  192. <Observer>
  193. {() => {
  194. const scheduleType = form.current.getValue('config.scheduleType');
  195. const cronSchedule = form.current.getValue('config.schedule');
  196. const timezone = form.current.getValue('config.timezone');
  197. const intervalFrequency = form.current.getValue('config.schedule.frequency');
  198. const intervalUnit = form.current.getValue('config.schedule.interval');
  199. const schedule = {
  200. scheduleType,
  201. timezone,
  202. cronSchedule,
  203. intervalFrequency,
  204. intervalUnit,
  205. };
  206. return <MockTimelineVisualization schedule={schedule} />;
  207. }}
  208. </Observer>
  209. </FieldContainer>
  210. </Form>
  211. );
  212. }
  213. const FieldContainer = styled('div')`
  214. max-width: 800px;
  215. `;
  216. const SchedulePanel = styled(Panel)<{highlighted: boolean}>`
  217. border-radius: 0 ${space(0.75)} ${space(0.75)} 0;
  218. ${p =>
  219. p.highlighted
  220. ? css`
  221. border: 2px solid ${p.theme.purple300};
  222. `
  223. : css`
  224. padding: 1px;
  225. `};
  226. &:first-child {
  227. border-radius: ${space(0.75)} 0 0 ${space(0.75)};
  228. }
  229. `;
  230. const ScheduleLabel = styled('div')`
  231. font-weight: bold;
  232. margin-bottom: ${space(2)};
  233. `;
  234. const Label = styled('div')`
  235. font-weight: bold;
  236. color: ${p => p.theme.subText};
  237. `;
  238. const LabelText = styled(Label)`
  239. margin-top: ${space(2)};
  240. margin-bottom: ${space(1)};
  241. `;
  242. const ScheduleOptions = styled('div')`
  243. display: grid;
  244. grid-template-columns: 1fr 1fr;
  245. `;
  246. const MultiColumnInput = styled('div')<{columns?: string}>`
  247. display: grid;
  248. align-items: center;
  249. gap: ${space(1)};
  250. grid-template-columns: ${p => p.columns};
  251. `;
  252. const CronstrueText = styled(LabelText)`
  253. font-weight: normal;
  254. font-size: ${p => p.theme.fontSizeExtraSmall};
  255. font-family: ${p => p.theme.text.familyMono};
  256. grid-column: auto / span 2;
  257. `;
  258. const StyledNumberField = styled(NumberField)`
  259. padding: 0;
  260. `;
  261. const StyledSelectField = styled(SelectField)`
  262. padding: 0;
  263. `;
  264. const StyledTextField = styled(TextField)`
  265. padding: 0;
  266. `;
  267. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  268. padding: 0;
  269. `;