import { type CreateRecipeInput, type DietView, ErrorCode, type IngredientView, type RecipeVisibility, createRecipeSchema, } from "@batch-cooking/shared"; import { type FormEvent, useEffect, useState } from "react"; import { useTranslation } from "react-i18next"; import { useNavigate, useParams } from "react-router-dom"; import { ApiError, apiClient } from "../api/client"; import { DietTagSelect } from "../features/recipes/DietTagSelect"; import { IngredientPicker } from "../features/recipes/IngredientPicker"; import { IngredientRow } from "../features/recipes/IngredientRow"; import { type StepDraft, StepListEditor } from "../features/recipes/StepListEditor"; import "../features/recipes/recipes.scss"; import { makeClientKey } from "../lib/client-key"; import { errorMessageService } from "../services/error-message.service"; /** In display order — mirrors `RecipeVisibility` (schema.prisma/shared types). */ const VISIBILITY_OPTIONS: RecipeVisibility[] = ["PERSONAL", "HOUSE", "PUBLIC"]; /** One selected ingredient line — `key` is a client-only stable identity, same reasoning as `StepDraft`. */ interface IngredientLine { key: string; ingredient: IngredientView; quantity: string; unit: string; } /** Load state for the reference ingredient list (+ the existing recipe, when editing) this form needs before it can render. */ type LoadState = "loading" | "loaded" | "error"; /** * Create/edit form for one recipe — routed at `/recettes/nouvelle` and * `/recettes/:id/modifier`. Same component for both: edit mode is just * "there's an `:id` param", which also drives preloading the existing * recipe's fields. Saving always sends the recipe's *whole* content (name, * ingredients, steps) — there's no partial-field save here, matching the * API's `PATCH /recipes/:id` contract (see `recipe.service.ts`). */ export function RecipeFormPage() { const { t } = useTranslation(); const navigate = useNavigate(); const { id } = useParams<{ id: string }>(); const recipeId = id !== undefined ? Number(id) : null; const isEditing = recipeId !== null; const [loadState, setLoadState] = useState("loading"); const [ingredientsCatalog, setIngredientsCatalog] = useState([]); const [dietsCatalog, setDietsCatalog] = useState([]); const [name, setName] = useState(""); const [description, setDescription] = useState(""); const [picture, setPicture] = useState(""); const [visibility, setVisibility] = useState("PERSONAL"); const [dietIds, setDietIds] = useState([]); const [ingredientLines, setIngredientLines] = useState([]); const [steps, setSteps] = useState([]); const [formError, setFormError] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); useEffect(() => { let cancelled = false; setLoadState("loading"); Promise.all([ apiClient.getIngredients(), apiClient.getDiets(), recipeId !== null ? apiClient.getRecipe(recipeId) : Promise.resolve(null), ]) .then(([ingredients, diets, recipe]) => { if (cancelled) return; setIngredientsCatalog(ingredients); setDietsCatalog(diets); if (recipe) { setName(recipe.name); setDescription(recipe.description ?? ""); setPicture(recipe.picture ?? ""); setVisibility(recipe.visibility); setDietIds(recipe.diets.map((diet) => diet.id)); setIngredientLines( recipe.ingredients.map((line) => ({ key: makeClientKey(), ingredient: line.ingredient, quantity: String(line.quantity), unit: line.unit, })), ); setSteps( recipe.steps.map((step) => ({ key: makeClientKey(), description: step.description, picture: step.picture ?? "", })), ); } setLoadState("loaded"); }) .catch(() => { if (!cancelled) setLoadState("error"); }); return () => { cancelled = true; }; }, [recipeId]); function addIngredient(ingredient: IngredientView) { setIngredientLines((lines) => [ ...lines, { key: makeClientKey(), ingredient, quantity: "", unit: "" }, ]); } function updateIngredientLine( key: string, patch: Partial>, ) { setIngredientLines((lines) => lines.map((line) => (line.key === key ? { ...line, ...patch } : line)), ); } function removeIngredientLine(key: string) { setIngredientLines((lines) => lines.filter((line) => line.key !== key)); } // Gates the submit button — the schema (checked again on submit, see // `handleSubmit`) is the source of truth, this is just instant feedback // that doesn't need a round trip through zod on every keystroke. const canSubmit = name.trim().length > 0 && ingredientLines.length > 0 && ingredientLines.every((line) => Number(line.quantity) > 0 && line.unit.trim().length > 0) && steps.length > 0 && steps.every((step) => step.description.trim().length > 0); async function handleSubmit(e: FormEvent) { e.preventDefault(); setFormError(null); const payload: CreateRecipeInput = { name: name.trim(), description: description.trim() || null, picture: picture.trim() || null, visibility, dietIds, ingredients: ingredientLines.map((line) => ({ ingredientId: line.ingredient.id, quantity: Number(line.quantity), unit: line.unit.trim(), })), steps: steps.map((step) => ({ description: step.description.trim(), picture: step.picture.trim() || null, })), }; const result = createRecipeSchema.safeParse(payload); if (!result.success) { setFormError(result.error.issues[0]?.message ?? t("recipes.form.genericError")); return; } setIsSubmitting(true); try { const saved = recipeId !== null ? await apiClient.updateRecipe(recipeId, result.data) : await apiClient.createRecipe(result.data); navigate(`/recettes/${saved.id}`); } catch (err) { const code = err instanceof ApiError ? err.code : ErrorCode.INTERNAL_ERROR; setFormError(errorMessageService.getLabel(code)); } finally { setIsSubmitting(false); } } if (loadState === "loading") { return (

{t("recipes.loading")}

); } if (loadState === "error") { return (

{t("common.loadError")}

); } const selectedIds = ingredientLines.map((line) => line.ingredient.id); return (

{isEditing ? t("recipes.form.editTitle") : t("recipes.form.newTitle")}

setName(e.target.value)} />