import { Button, Form } from "react-bootstrap"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faPlus, faTrash } from "@fortawesome/free-solid-svg-icons"; import { RecipeIngredient } from "../../../types"; import { formatCalories, formatPriceInput, getIngredientCalories, parseIntInput, parsePriceInput } from "../Utils"; /** Rozpracovaná surovina — hodnoty jsou texty, protože se editují v polích. */ export type DraftIngredient = { name: string, weight: string, caloriesPer100g: string, calories: string, price: string, }; export const emptyIngredient = (): DraftIngredient => ({ name: '', weight: '', caloriesPer100g: '', calories: '', price: '', }); /** Převede uloženou surovinu na rozpracovanou pro editaci. */ export const toDraftIngredient = (ingredient: RecipeIngredient): DraftIngredient => ({ name: ingredient.name, weight: ingredient.weight != null ? String(ingredient.weight) : '', caloriesPer100g: ingredient.caloriesPer100g != null ? String(ingredient.caloriesPer100g) : '', calories: ingredient.calories != null ? String(ingredient.calories) : '', price: formatPriceInput(ingredient.price), }); /** Převede rozpracovanou surovinu na hodnoty pro výpočet a uložení. */ export const toIngredient = (draft: DraftIngredient): RecipeIngredient => ({ name: draft.name.trim(), weight: parseIntInput(draft.weight), caloriesPer100g: parseIntInput(draft.caloriesPer100g), calories: parseIntInput(draft.calories), price: parsePriceInput(draft.price), }); type Props = { ingredients: DraftIngredient[], onChange: (ingredients: DraftIngredient[]) => void, }; /** * Editor surovin receptu. * * Energie suroviny se dopočte z gramáže a hodnoty na 100 g; ručně jde zadat jen * tam, kde dopočítat nejde (třeba „lžíce oleje" bez vážení). */ const RecipeIngredientsEditor = ({ ingredients, onChange }: Readonly) => { const updateAt = (index: number, changes: Partial) => onChange(ingredients.map((item, i) => (i === index ? { ...item, ...changes } : item))); return ( <> {ingredients.map((ingredient, index) => { const derived = getIngredientCalories({ weight: parseIntInput(ingredient.weight), caloriesPer100g: parseIntInput(ingredient.caloriesPer100g), }); return ( // Suroviny nemají vlastní id, v rámci rozpracovaného receptu je index jediný klíč
updateAt(index, { name: event.target.value })} />
updateAt(index, { weight: event.target.value.replace(/\D/g, '') })} /> g
updateAt(index, { caloriesPer100g: event.target.value.replace(/\D/g, '') })} /> {derived != null ? (
{formatCalories(derived)}
) : ( updateAt(index, { calories: event.target.value.replace(/\D/g, '') })} /> )}
updateAt(index, { price: event.target.value })} /> Kč
); })} ); }; export default RecipeIngredientsEditor;