import { useEffect, useState } from "react"; import { Input, Select } from "../../components/ui/Field"; import { columnLabel } from "../../lib/format"; const NUMBER = /^-?\d[\d,]*(\.\d+)?$/; const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; /** * A small box in the table that is typed into directly. Saves when the user leaves it (or * presses Enter) and only if the value changed; Escape puts the saved value back. A refresh * of the list never overwrites what is being typed. */ export function InlineCell({ value, column, onSave }: { value: string; column: string; onSave: (value: string) => Promise; }) { if (column === "month") return ; return ; } /** The month, picked from the list; saved as soon as it is chosen. */ function MonthCell({ value, onSave }: { value: string; onSave: (value: string) => Promise }) { const [draft, setDraft] = useState(value); const [saving, setSaving] = useState(false); useEffect(() => { if (!saving) setDraft(value); }, [value, saving]); async function choose(next: string) { if (next === value) return; setDraft(next); setSaving(true); const ok = await onSave(next); setSaving(false); if (!ok) setDraft(value); } return ( ); } function NumberCell({ value, column, onSave }: { value: string; column: string; onSave: (value: string) => Promise; }) { const [draft, setDraft] = useState(value); const [editing, setEditing] = useState(false); const [saving, setSaving] = useState(false); const [invalid, setInvalid] = useState(false); useEffect(() => { if (!editing && !saving) setDraft(value); }, [value, editing, saving]); async function commit() { setEditing(false); const next = draft.trim(); if (next === value.trim()) { setInvalid(false); return; } if (next && !NUMBER.test(next)) { setInvalid(true); return; } setInvalid(false); setSaving(true); const ok = await onSave(next); setSaving(false); if (!ok) setDraft(value); } return ( setEditing(true)} onChange={(e) => setDraft(e.target.value)} onBlur={() => void commit()} onKeyDown={(e) => { if (e.key === "Enter") e.currentTarget.blur(); if (e.key === "Escape") { setDraft(value); setInvalid(false); e.currentTarget.blur(); } }} /> ); }