diff --git a/frontend/src/components/RecipeEditor.tsx b/frontend/src/components/RecipeEditor.tsx index d52ab7c..dec8f64 100644 --- a/frontend/src/components/RecipeEditor.tsx +++ b/frontend/src/components/RecipeEditor.tsx @@ -14,11 +14,47 @@ type RecipeEditorProps = { * ingredients (with amount, unit, name), instructions, and image URL. */ export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorProps) { + /** draft of the new recipe */ const [draft, setDraft] = useState(recipe) + /** Error list */ + const [errors, setErrors] = useState<{ title?: boolean; ingredients?: boolean }>({}) + /** + * Update ingredients + * @param ingredients new ingredients + */ const updateIngredients = (ingredients: Ingredient[]) => { setDraft({ ...draft, ingredients }) } + /** + * Validate recipe + * @returns Information on the errors the validation encountered + */ + const validate = () => { + const newErrors: { title?: boolean; ingredients?: boolean } = {} + + // each recipe requires a title + if (!draft.title.trim()) { + newErrors.title = true + } + + // the incredient list must not be empty + // @todo enhance validation and visualization of ingredient errors + if (!draft.ingredients || draft.ingredients.length === 0) { + newErrors.ingredients = true + } + + setErrors(newErrors) + + return Object.keys(newErrors).length === 0 + } + /** Handles saving and ensures that the draft is only saved if valid */ + const handleSave = (draft: Recipe) => { + if (validate()) { + onSave(draft) + } + } + // ensure that there is a recipe and show error otherwise if (!recipe) return
Oops, there's no recipe in RecipeEditor...
// @todo add handling of images return ( @@ -30,7 +66,7 @@ export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorP {/* Title */}

Title

setDraft({ ...draft, title: e.target.value })} @@ -61,11 +97,13 @@ export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorP }} /> - {/* Ingredient List */} + {/* Ingredient List - @todo better visualization of errors! */} +
+

Instructions

{/* Instructions */} @@ -80,7 +118,7 @@ export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorP {/* Save Button */}