monitorCreateForm.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 url = normalizeUrl(`/organizations/${organization.slug}/crons/${data.slug}/`);
  157. browserHistory.push(url);
  158. }
  159. function changeScheduleType(type: ScheduleType) {
  160. form.current.setValue('config.schedule_type', type);
  161. }
  162. return (
  163. <Form
  164. allowUndo
  165. requireChanges
  166. apiEndpoint={`/organizations/${organization.slug}/monitors/`}
  167. apiMethod="POST"
  168. model={form.current}
  169. initialData={{
  170. project: selectedProject ? selectedProject.slug : null,
  171. type: DEFAULT_MONITOR_TYPE,
  172. 'config.schedule_type': DEFAULT_SCHEDULE_CONFIG.scheduleType,
  173. }}
  174. onSubmitSuccess={onCreateMonitor}
  175. submitLabel={t('Next')}
  176. >
  177. <FieldContainer>
  178. <MultiColumnInput columns="250px 1fr">
  179. <StyledSentryProjectSelectorField
  180. name="project"
  181. projects={filteredProjects}
  182. placeholder={t('Choose Project')}
  183. disabledReason={t('Existing monitors cannot be moved between projects')}
  184. valueIsSlug
  185. required
  186. stacked
  187. inline={false}
  188. />
  189. <StyledTextField
  190. name="name"
  191. placeholder={t('My Cron Job')}
  192. required
  193. stacked
  194. inline={false}
  195. />
  196. </MultiColumnInput>
  197. <LabelText>{t('SCHEDULE')}</LabelText>
  198. <ScheduleOptions>
  199. <Observer>
  200. {() => {
  201. const currScheduleType = form.current.getValue('config.schedule_type');
  202. const parsedSchedule = crontabAsText(
  203. form.current.getValue('config.schedule')?.toString() ?? ''
  204. );
  205. return (
  206. <Fragment>
  207. <SchedulePanel
  208. highlighted={currScheduleType === ScheduleType.CRONTAB}
  209. onClick={() => changeScheduleType(ScheduleType.CRONTAB)}
  210. >
  211. <PanelBody withPadding>
  212. <ScheduleLabel>{t('Crontab Schedule')}</ScheduleLabel>
  213. <MultiColumnInput columns="1fr 1fr">
  214. <StyledTextField
  215. name="config.schedule"
  216. placeholder="* * * * *"
  217. defaultValue={DEFAULT_SCHEDULE_CONFIG.cronSchedule}
  218. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  219. required={currScheduleType === ScheduleType.CRONTAB}
  220. stacked
  221. inline={false}
  222. />
  223. <StyledSelectField
  224. name="config.timezone"
  225. defaultValue="UTC"
  226. options={timezoneOptions}
  227. required={currScheduleType === ScheduleType.CRONTAB}
  228. stacked
  229. inline={false}
  230. />
  231. <CronstrueText>{parsedSchedule}</CronstrueText>
  232. </MultiColumnInput>
  233. </PanelBody>
  234. </SchedulePanel>
  235. <SchedulePanel
  236. highlighted={currScheduleType === ScheduleType.INTERVAL}
  237. onClick={() => changeScheduleType(ScheduleType.INTERVAL)}
  238. >
  239. <PanelBody withPadding>
  240. <ScheduleLabel>{t('Interval Schedule')}</ScheduleLabel>
  241. <MultiColumnInput columns="auto 1fr 2fr">
  242. <Label>{t('Every')}</Label>
  243. <StyledNumberField
  244. name="config.schedule.frequency"
  245. placeholder="e.g. 1"
  246. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalFrequency}
  247. required={currScheduleType === ScheduleType.INTERVAL}
  248. stacked
  249. inline={false}
  250. />
  251. <StyledSelectField
  252. name="config.schedule.interval"
  253. options={getScheduleIntervals(
  254. Number(
  255. form.current.getValue('config.schedule.frequency') ?? 1
  256. )
  257. )}
  258. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalUnit}
  259. required={currScheduleType === ScheduleType.INTERVAL}
  260. stacked
  261. inline={false}
  262. />
  263. </MultiColumnInput>
  264. </PanelBody>
  265. </SchedulePanel>
  266. </Fragment>
  267. );
  268. }}
  269. </Observer>
  270. </ScheduleOptions>
  271. <Observer>
  272. {() => {
  273. const scheduleType = form.current.getValue('config.schedule_type');
  274. const cronSchedule = form.current.getValue('config.schedule');
  275. const intervalFrequency = form.current.getValue('config.schedule.frequency');
  276. const intervalUnit = form.current.getValue('config.schedule.interval');
  277. return (
  278. <MockTimelineVisualization
  279. scheduleType={scheduleType}
  280. cronSchedule={cronSchedule}
  281. intervalFrequency={intervalFrequency}
  282. intervalUnit={intervalUnit}
  283. />
  284. );
  285. }}
  286. </Observer>
  287. </FieldContainer>
  288. </Form>
  289. );
  290. }
  291. const FieldContainer = styled('div')`
  292. width: 800px;
  293. `;
  294. const SchedulePanel = styled(Panel)<{highlighted: boolean}>`
  295. border-radius: 0 ${space(0.75)} ${space(0.75)} 0;
  296. ${p =>
  297. p.highlighted &&
  298. css`
  299. border: 2px solid ${p.theme.purple300};
  300. `};
  301. &:first-child {
  302. border-radius: ${space(0.75)} 0 0 ${space(0.75)};
  303. }
  304. `;
  305. const ScheduleLabel = styled('div')`
  306. font-weight: bold;
  307. margin-bottom: ${space(2)};
  308. `;
  309. const Label = styled('div')`
  310. font-weight: bold;
  311. color: ${p => p.theme.subText};
  312. `;
  313. const LabelText = styled(Label)`
  314. margin-top: ${space(2)};
  315. margin-bottom: ${space(1)};
  316. `;
  317. const ScheduleOptions = styled('div')`
  318. display: grid;
  319. grid-template-columns: 1fr 1fr;
  320. `;
  321. const MultiColumnInput = styled('div')<{columns?: string}>`
  322. display: grid;
  323. align-items: center;
  324. gap: ${space(1)};
  325. grid-template-columns: ${p => p.columns};
  326. `;
  327. const CronstrueText = styled(LabelText)`
  328. font-weight: normal;
  329. font-size: ${p => p.theme.fontSizeExtraSmall};
  330. font-family: ${p => p.theme.text.familyMono};
  331. grid-column: auto / span 2;
  332. `;
  333. const StyledNumberField = styled(NumberField)`
  334. padding: 0;
  335. `;
  336. const StyledSelectField = styled(SelectField)`
  337. padding: 0;
  338. `;
  339. const StyledTextField = styled(TextField)`
  340. padding: 0;
  341. `;
  342. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  343. padding: 0;
  344. `;