import React, {useState} from 'react'; import {postJson} from '../api'; import {daysBefore, localToday} from '../dates'; import Modal from './Modal'; import WhenPicker from './WhenPicker'; const WHEN_CHOICES = [['today', 'Today'], ['tomorrow', 'Tomorrow'], ['other', 'Another day']]; function humanize(field) { return field.replace(/_/g, ' ').replace(/^./, (c) => c.toUpperCase()); } function errorMessages(status, data) { if (status === 422 && data && data.errors) { const messages = Object.entries(data.errors).flatMap(([field, list]) => list.map((m) => `${humanize(field)} ${m}`)); if (messages.length > 0) return messages; } if (status === 401) return ['Please sign in again to add this job.']; return ['Something went wrong saving that. Please try again.']; } // Adding a job, as a dialog over the page: what needs doing, when, and a note // if they want one. Saves with POST /jobs.json and hands the job to onSaved. export default function AddJobModal({onClose, onSaved}) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [noting, setNoting] = useState(false); // the notes box is open const [when, setWhen] = useState('today'); const [customDate, setCustomDate] = useState(''); const [saving, setSaving] = useState(false); const [errors, setErrors] = useState([]); const today = localToday(); const dueOn = {today, tomorrow: daysBefore(today, -1), other: customDate}[when]; function chooseWhen(choice) { setWhen(choice); if (choice === 'other' && !customDate) setCustomDate(today); } async function save(event) { event.preventDefault(); setSaving(true); setErrors([]); try { const {ok, status, data} = await postJson('/jobs.json', { job: {name, description, due_date: dueOn}, }); if (ok) { onSaved(data); return; } setErrors(errorMessages(status, data)); } catch (error) { setErrors(['Couldn\'t reach the server. Please try again.']); } setSaving(false); } return (
{errors.length > 0 && (