import React from 'react'; import _ from 'lodash'; import cronstrue from 'cronstrue'; import * as Yup from 'yup'; import { Formik, Form, Field } from 'formik'; import { Grid, TextField, Button, Link } from '@material-ui/core'; import { post } from '../../requests'; import { Event } from '../../types'; interface PropTypes { mutate: () => void; } interface Fields { name: string; schedule: string; attendanceId: string; conferenceId: string; } const describeCrontab = (crontab: string) => { try { return cronstrue.toString(crontab); } catch { return false; } }; const validationSchema = Yup.object({ name: Yup.string().required('This field is required'), conferenceId: Yup.string().required('This field is required'), attendanceId: Yup.string(), schedule: Yup.string() .required('This field is required') .test('cron', 'Invalid crontab', value => !!describeCrontab(value || '')) }); const EventForm: React.FC = ({ mutate }) => { const describeSchedule = (schedule: string) => { const description = describeCrontab(schedule); if (description) return `Event will run ${_.lowerFirst(description)}`; const link = crontab.guru; return ( <> The schedule is invalid. Check out {link} for more help with cron scheduling. ); }; const handleSubmit = (fields: Fields, { resetForm }: any) => { const { name, schedule, attendanceId, conferenceId } = fields; if (schedule && conferenceId) { const event: Partial = { type: 'class', schedule, context: { name, attendanceId, conferenceId, participants: [] } }; return post('/events', event).then(() => { mutate(); resetForm(); }); } } return ( {({ values, errors, touched, isValid }) => (
{describeSchedule(values.schedule)}
)}
); }; export default EventForm;