monitorCreateForm.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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, {FieldValue} from 'sentry/components/forms/model';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import Placeholder from 'sentry/components/placeholder';
  15. import {timezoneOptions} from 'sentry/data/timezones';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  19. import {useApiQuery} from 'sentry/utils/queryClient';
  20. import commonTheme from 'sentry/utils/theme';
  21. import {useDimensions} from 'sentry/utils/useDimensions';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import usePageFilters from 'sentry/utils/usePageFilters';
  24. import useProjects from 'sentry/utils/useProjects';
  25. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  26. import {
  27. DEFAULT_CRONTAB,
  28. DEFAULT_MONITOR_TYPE,
  29. mapMonitorFormErrors,
  30. transformMonitorFormData,
  31. } from 'sentry/views/monitors/components/monitorForm';
  32. import {MockCheckInTimeline} from 'sentry/views/monitors/components/overviewTimeline/checkInTimeline';
  33. import {
  34. GridLineOverlay,
  35. GridLineTimeLabels,
  36. } from 'sentry/views/monitors/components/overviewTimeline/gridLines';
  37. import {TimelinePlaceholder} from 'sentry/views/monitors/components/overviewTimeline/timelinePlaceholder';
  38. import {getConfigFromTimeRange} from 'sentry/views/monitors/components/overviewTimeline/utils';
  39. import {Monitor, ScheduleType} from 'sentry/views/monitors/types';
  40. import {crontabAsText, getScheduleIntervals} from 'sentry/views/monitors/utils';
  41. const NUM_SAMPLE_TICKS = 9;
  42. interface ScheduleConfig {
  43. cronSchedule?: FieldValue;
  44. intervalFrequency?: FieldValue;
  45. intervalUnit?: FieldValue;
  46. scheduleType?: FieldValue;
  47. }
  48. function isValidConfig(schedule: ScheduleConfig) {
  49. const {scheduleType, cronSchedule, intervalFrequency, intervalUnit} = schedule;
  50. return !!(
  51. (scheduleType === ScheduleType.CRONTAB && cronSchedule) ||
  52. (scheduleType === ScheduleType.INTERVAL && intervalFrequency && intervalUnit)
  53. );
  54. }
  55. const DEFAULT_SCHEDULE_CONFIG = {
  56. scheduleType: 'crontab',
  57. cronSchedule: DEFAULT_CRONTAB,
  58. intervalFrequency: '1',
  59. intervalUnit: 'day',
  60. };
  61. function MockTimelineVisualization(props: ScheduleConfig) {
  62. const {scheduleType, cronSchedule, intervalFrequency, intervalUnit} = props;
  63. const organization = useOrganization();
  64. const query = {
  65. num_ticks: NUM_SAMPLE_TICKS,
  66. schedule_type: scheduleType,
  67. schedule:
  68. scheduleType === 'interval' ? [intervalFrequency, intervalUnit] : cronSchedule,
  69. };
  70. const elementRef = useRef<HTMLDivElement>(null);
  71. const {width: timelineWidth} = useDimensions<HTMLDivElement>({elementRef});
  72. const sampleDataQueryKey = [
  73. `/organizations/${organization.slug}/monitors-schedule-data/`,
  74. {query},
  75. ] as const;
  76. const {data, isLoading} = useApiQuery<number[]>(sampleDataQueryKey, {
  77. staleTime: 0,
  78. enabled: isValidConfig(props),
  79. });
  80. const mockTimestamps = data?.map(ts => new Date(ts * 1000));
  81. const start = mockTimestamps?.[0];
  82. const end = mockTimestamps?.[mockTimestamps.length - 1];
  83. const timeWindowConfig =
  84. start && end ? getConfigFromTimeRange(start, end, timelineWidth) : undefined;
  85. return (
  86. <TimelineContainer>
  87. <TimelineWidthTracker ref={elementRef} />
  88. {isLoading || !start || !end || !timeWindowConfig || !mockTimestamps ? (
  89. <Fragment>
  90. {/* TODO(davidenwang): Improve loading placeholder */}
  91. <Placeholder height="40px" />
  92. <TimelinePlaceholder />
  93. </Fragment>
  94. ) : (
  95. <Fragment>
  96. <StyledGridLineTimeLabels
  97. timeWindowConfig={timeWindowConfig}
  98. start={start}
  99. end={end}
  100. width={timelineWidth}
  101. />
  102. <StyledGridLineOverlay
  103. showCursor={!isLoading}
  104. timeWindowConfig={timeWindowConfig}
  105. start={start}
  106. end={end}
  107. width={timelineWidth}
  108. />
  109. <MockCheckInTimeline
  110. width={timelineWidth}
  111. mockTimestamps={mockTimestamps.slice(1, mockTimestamps.length - 1)}
  112. start={start}
  113. end={end}
  114. timeWindowConfig={timeWindowConfig}
  115. />
  116. </Fragment>
  117. )}
  118. </TimelineContainer>
  119. );
  120. }
  121. const TimelineContainer = styled(Panel)`
  122. display: grid;
  123. grid-template-columns: 1fr;
  124. grid-template-rows: 40px 100px;
  125. align-items: center;
  126. `;
  127. const StyledGridLineTimeLabels = styled(GridLineTimeLabels)`
  128. grid-column: 0;
  129. `;
  130. const StyledGridLineOverlay = styled(GridLineOverlay)`
  131. grid-column: 0;
  132. `;
  133. const TimelineWidthTracker = styled('div')`
  134. position: absolute;
  135. width: 100%;
  136. grid-row: 1;
  137. grid-column: 0;
  138. `;
  139. export default function MonitorCreateForm() {
  140. const organization = useOrganization();
  141. const {projects} = useProjects();
  142. const {selection} = usePageFilters();
  143. const form = useRef(
  144. new FormModel({
  145. transformData: transformMonitorFormData,
  146. mapFormErrors: mapMonitorFormErrors,
  147. })
  148. );
  149. const selectedProjectId = selection.projects[0];
  150. const selectedProject = selectedProjectId
  151. ? projects.find(p => p.id === selectedProjectId + '')
  152. : null;
  153. const isSuperuser = isActiveSuperuser();
  154. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  155. function onCreateMonitor(data: Monitor) {
  156. const endpointOptions = {
  157. query: {
  158. project: selection.projects,
  159. environment: selection.environments,
  160. },
  161. };
  162. browserHistory.push(
  163. normalizeUrl({
  164. pathname: `/organizations/${organization.slug}/crons/${data.slug}/`,
  165. query: endpointOptions.query,
  166. })
  167. );
  168. }
  169. function changeScheduleType(type: ScheduleType) {
  170. form.current.setValue('config.schedule_type', type);
  171. }
  172. return (
  173. <Form
  174. allowUndo
  175. requireChanges
  176. apiEndpoint={`/organizations/${organization.slug}/monitors/`}
  177. apiMethod="POST"
  178. model={form.current}
  179. initialData={{
  180. project: selectedProject ? selectedProject.slug : null,
  181. type: DEFAULT_MONITOR_TYPE,
  182. 'config.schedule_type': DEFAULT_SCHEDULE_CONFIG.scheduleType,
  183. }}
  184. onSubmitSuccess={onCreateMonitor}
  185. submitLabel={t('Next')}
  186. >
  187. <FieldContainer>
  188. <MultiColumnInput columns="250px 1fr">
  189. <StyledSentryProjectSelectorField
  190. name="project"
  191. projects={filteredProjects}
  192. placeholder={t('Choose Project')}
  193. disabledReason={t('Existing monitors cannot be moved between projects')}
  194. valueIsSlug
  195. required
  196. stacked
  197. inline={false}
  198. />
  199. <StyledTextField
  200. name="name"
  201. placeholder={t('My Cron Job')}
  202. required
  203. stacked
  204. inline={false}
  205. />
  206. </MultiColumnInput>
  207. <LabelText>{t('SCHEDULE')}</LabelText>
  208. <ScheduleOptions>
  209. <Observer>
  210. {() => {
  211. const currScheduleType = form.current.getValue('config.schedule_type');
  212. const parsedSchedule = crontabAsText(
  213. form.current.getValue('config.schedule')?.toString() ?? ''
  214. );
  215. return (
  216. <Fragment>
  217. <SchedulePanel
  218. highlighted={currScheduleType === ScheduleType.CRONTAB}
  219. onClick={() => changeScheduleType(ScheduleType.CRONTAB)}
  220. >
  221. <PanelBody withPadding>
  222. <ScheduleLabel>{t('Crontab Schedule')}</ScheduleLabel>
  223. <MultiColumnInput columns="1fr 1fr">
  224. <StyledTextField
  225. name="config.schedule"
  226. placeholder="* * * * *"
  227. defaultValue={DEFAULT_SCHEDULE_CONFIG.cronSchedule}
  228. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  229. required={currScheduleType === ScheduleType.CRONTAB}
  230. stacked
  231. inline={false}
  232. />
  233. <StyledSelectField
  234. name="config.timezone"
  235. defaultValue="UTC"
  236. options={timezoneOptions}
  237. required={currScheduleType === ScheduleType.CRONTAB}
  238. stacked
  239. inline={false}
  240. />
  241. <CronstrueText>{parsedSchedule}</CronstrueText>
  242. </MultiColumnInput>
  243. </PanelBody>
  244. </SchedulePanel>
  245. <SchedulePanel
  246. highlighted={currScheduleType === ScheduleType.INTERVAL}
  247. onClick={() => changeScheduleType(ScheduleType.INTERVAL)}
  248. >
  249. <PanelBody withPadding>
  250. <ScheduleLabel>{t('Interval Schedule')}</ScheduleLabel>
  251. <MultiColumnInput columns="auto 1fr 2fr">
  252. <Label>{t('Every')}</Label>
  253. <StyledNumberField
  254. name="config.schedule.frequency"
  255. placeholder="e.g. 1"
  256. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalFrequency}
  257. required={currScheduleType === ScheduleType.INTERVAL}
  258. stacked
  259. inline={false}
  260. />
  261. <StyledSelectField
  262. name="config.schedule.interval"
  263. options={getScheduleIntervals(
  264. Number(
  265. form.current.getValue('config.schedule.frequency') ?? 1
  266. )
  267. )}
  268. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalUnit}
  269. required={currScheduleType === ScheduleType.INTERVAL}
  270. stacked
  271. inline={false}
  272. />
  273. </MultiColumnInput>
  274. </PanelBody>
  275. </SchedulePanel>
  276. </Fragment>
  277. );
  278. }}
  279. </Observer>
  280. </ScheduleOptions>
  281. <Observer>
  282. {() => {
  283. const scheduleType = form.current.getValue('config.schedule_type');
  284. const cronSchedule = form.current.getValue('config.schedule');
  285. const intervalFrequency = form.current.getValue('config.schedule.frequency');
  286. const intervalUnit = form.current.getValue('config.schedule.interval');
  287. return (
  288. <MockTimelineVisualization
  289. scheduleType={scheduleType}
  290. cronSchedule={cronSchedule}
  291. intervalFrequency={intervalFrequency}
  292. intervalUnit={intervalUnit}
  293. />
  294. );
  295. }}
  296. </Observer>
  297. </FieldContainer>
  298. </Form>
  299. );
  300. }
  301. const FieldContainer = styled('div')`
  302. width: 800px;
  303. `;
  304. const SchedulePanel = styled(Panel)<{highlighted: boolean}>`
  305. border-radius: 0 ${space(0.75)} ${space(0.75)} 0;
  306. ${p =>
  307. p.highlighted &&
  308. css`
  309. border: 2px solid ${p.theme.purple300};
  310. `};
  311. &:first-child {
  312. border-radius: ${space(0.75)} 0 0 ${space(0.75)};
  313. }
  314. `;
  315. const ScheduleLabel = styled('div')`
  316. font-weight: bold;
  317. margin-bottom: ${space(2)};
  318. `;
  319. const Label = styled('div')`
  320. font-weight: bold;
  321. color: ${p => p.theme.subText};
  322. `;
  323. const LabelText = styled(Label)`
  324. margin-top: ${space(2)};
  325. margin-bottom: ${space(1)};
  326. `;
  327. const ScheduleOptions = styled('div')`
  328. display: grid;
  329. grid-template-columns: 1fr 1fr;
  330. `;
  331. const MultiColumnInput = styled('div')<{columns?: string}>`
  332. display: grid;
  333. align-items: center;
  334. gap: ${space(1)};
  335. grid-template-columns: ${p => p.columns};
  336. `;
  337. const CronstrueText = styled(LabelText)`
  338. font-weight: normal;
  339. font-size: ${p => p.theme.fontSizeExtraSmall};
  340. font-family: ${p => p.theme.text.familyMono};
  341. grid-column: auto / span 2;
  342. `;
  343. const StyledNumberField = styled(NumberField)`
  344. padding: 0;
  345. `;
  346. const StyledSelectField = styled(SelectField)`
  347. padding: 0;
  348. `;
  349. const StyledTextField = styled(TextField)`
  350. padding: 0;
  351. `;
  352. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  353. padding: 0;
  354. `;