307 lines
15 KiB
TypeScript
307 lines
15 KiB
TypeScript
import { useEffect, useId, useState } from "react";
|
|
import { Alert, Button, Form, ToggleButton, ToggleButtonGroup } from "react-bootstrap";
|
|
import { MealTemplate, RecipeFlavor, getMealTemplates, saveMealTemplate } from "../../../types";
|
|
import { RECIPE_FLAVOR_NAMES, RECIPE_LINK_FIELDS, RECIPE_LINK_NAMES, RecipeLinkKind, getRecipeLinkIds } from "../enums";
|
|
import { deriveRecipe, formatCalories, formatPrepTime, formatPrice, formatWeight, parseIntInput } from "../Utils";
|
|
import SourceInput from "./SourceInput";
|
|
import RecipeCategoryInput from "./RecipeCategoryInput";
|
|
import RecipeNote from "./RecipeNote";
|
|
import RecipeLinksInput from "./RecipeLinksInput";
|
|
import RecipeIngredientsEditor, {
|
|
DraftIngredient, emptyIngredient, toDraftIngredient, toIngredient,
|
|
} from "./RecipeIngredientsEditor";
|
|
|
|
type Props = {
|
|
/** Upravovaný recept. Pokud chybí, zakládá se nový. */
|
|
template?: MealTemplate,
|
|
/**
|
|
* Jídlo ze seznamu jídel, ke kterému recept patří. Název a zdroj pak nejdou
|
|
* měnit — mění se přejmenováním jídla, aby recept zůstal u svých záznamů.
|
|
*/
|
|
meal?: { name: string, source?: string },
|
|
onSaved: (templates: MealTemplate[]) => void,
|
|
onCancel: () => void,
|
|
};
|
|
|
|
/** Ukázka Markdownu, dokud je postup prázdný. */
|
|
const NOTE_PLACEHOLDER = 'Jak se jídlo připravuje…\n\n## Příprava\n1. Cibuli nakrájejte nadrobno\n2. **Orestujte** dozlatova';
|
|
|
|
/** Naplní formulář z receptu, nebo ho nechá prázdný pro nový. */
|
|
const createForm = (template?: MealTemplate, meal?: Props['meal']) => ({
|
|
name: meal?.name ?? template?.name ?? '',
|
|
source: meal?.source ?? template?.source ?? '',
|
|
category: template?.category ?? '',
|
|
flavor: template?.flavor ?? RecipeFlavor.SLANE,
|
|
note: template?.note ?? '',
|
|
servings: template?.servings != null ? String(template.servings) : '',
|
|
cookedWeight: template?.cookedWeight != null ? String(template.cookedWeight) : '',
|
|
prepMinutes: template?.prepMinutes != null ? String(template.prepMinutes) : '',
|
|
});
|
|
|
|
/** Vazby receptu podle druhu, jak se editují ve formuláři. */
|
|
const createLinks = (template?: MealTemplate): Record<RecipeLinkKind, string[]> => ({
|
|
PRILOHY: template ? getRecipeLinkIds(template, RecipeLinkKind.PRILOHY) : [],
|
|
PRILOHOU_K: template ? getRecipeLinkIds(template, RecipeLinkKind.PRILOHOU_K) : [],
|
|
PODOBNE: template ? getRecipeLinkIds(template, RecipeLinkKind.PODOBNE) : [],
|
|
});
|
|
|
|
/** Jídlo nemůže být zároveň přílohou receptu i jídlem, ke kterému je recept přílohou. */
|
|
const getOppositeLinkIds = (links: Record<RecipeLinkKind, string[]>, kind: RecipeLinkKind): string[] => {
|
|
if (kind === RecipeLinkKind.PRILOHY) return links.PRILOHOU_K;
|
|
if (kind === RecipeLinkKind.PRILOHOU_K) return links.PRILOHY;
|
|
return [];
|
|
};
|
|
|
|
/** Výzva v nabídce receptů k propojení podle druhu vazby. */
|
|
const LINK_PLACEHOLDERS: Record<RecipeLinkKind, string> = {
|
|
PRILOHY: 'Přidat přílohu…',
|
|
PRILOHOU_K: 'Přidat jídlo, ke kterému se hodí…',
|
|
PODOBNE: 'Přidat podobný recept…',
|
|
};
|
|
|
|
/**
|
|
* Formulář receptu — vařeného jídla. Zapisují se suroviny a postup a hodnoty
|
|
* porce se z nich dopočtou — stejně jako na serveru, tady jen jako živý náhled.
|
|
* Vazby na jiné recepty jdou zapsat z kterékoli strany, server upraví i druhou.
|
|
*/
|
|
const MealTemplateForm = ({ template, meal, onSaved, onCancel }: Readonly<Props>) => {
|
|
const [form, setForm] = useState(() => createForm(template, meal));
|
|
const [ingredients, setIngredients] = useState<DraftIngredient[]>(() =>
|
|
template?.ingredients?.length ? template.ingredients.map(toDraftIngredient) : [emptyIngredient()]);
|
|
const [error, setError] = useState<string | undefined>();
|
|
const [busy, setBusy] = useState(false);
|
|
const [notePreview, setNotePreview] = useState(false);
|
|
const [links, setLinks] = useState(() => createLinks(template));
|
|
const [otherRecipeList, setOtherRecipeList] = useState<MealTemplate[]>([]);
|
|
const flavorId = useId();
|
|
|
|
useEffect(() => {
|
|
getMealTemplates().then(response =>
|
|
setOtherRecipeList((response.data ?? []).filter(recipe => recipe.id !== template?.id)));
|
|
}, [template?.id]);
|
|
|
|
const update = (changes: Partial<ReturnType<typeof createForm>>) =>
|
|
setForm(current => ({ ...current, ...changes }));
|
|
|
|
const filledIngredients = ingredients.filter(item => item.name.trim().length > 0).map(toIngredient);
|
|
const recipe = deriveRecipe(filledIngredients, parseIntInput(form.servings), parseIntInput(form.cookedWeight));
|
|
const ingredientWeight = filledIngredients.reduce((sum, item) => sum + (item.weight ?? 0), 0);
|
|
const prepMinutes = parseIntInput(form.prepMinutes);
|
|
|
|
// Suroviny ani postup nejsou povinné — neúplný recept se doplní později (třeba z PDF k doplnění)
|
|
const canSave = form.name.trim().length > 0 && !busy;
|
|
|
|
const save = async () => {
|
|
if (!canSave) return;
|
|
setBusy(true);
|
|
setError(undefined);
|
|
// Hodnoty porce si server dopočte ze surovin sám
|
|
const body = {
|
|
...(template ? { id: template.id } : {}),
|
|
name: form.name.trim(),
|
|
...(form.source.trim() ? { source: form.source.trim() } : {}),
|
|
...(form.category.trim() ? { category: form.category.trim() } : {}),
|
|
flavor: form.flavor,
|
|
...(form.note.trim() ? { note: form.note.trim() } : {}),
|
|
ingredients: filledIngredients,
|
|
servings: parseIntInput(form.servings),
|
|
cookedWeight: parseIntInput(form.cookedWeight),
|
|
prepMinutes,
|
|
...Object.fromEntries(Object.values(RecipeLinkKind).map(kind => [RECIPE_LINK_FIELDS[kind], links[kind]])),
|
|
};
|
|
const response = await saveMealTemplate({ body });
|
|
setBusy(false);
|
|
if (response.data) {
|
|
onSaved(response.data);
|
|
} else {
|
|
setError((response.error as { error?: string })?.error ?? 'Recept se nepodařilo uložit');
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div className="card-panel template-form">
|
|
<h2 className="chart-title">{template ? 'Úprava receptu' : 'Nový recept'}</h2>
|
|
|
|
{error && <Alert variant="danger" className="py-2 small">{error}</Alert>}
|
|
|
|
{!meal && (
|
|
<div className="row g-3 mb-3">
|
|
<div className="col-sm-7">
|
|
<Form.Label>Název</Form.Label>
|
|
<Form.Control
|
|
value={form.name}
|
|
placeholder="Např. Kuřecí rizoto"
|
|
onChange={event => update({ name: event.target.value })}
|
|
/>
|
|
</div>
|
|
<div className="col-sm-5">
|
|
<Form.Label>Zdroj</Form.Label>
|
|
<SourceInput
|
|
value={form.source}
|
|
placeholder="doma"
|
|
onChange={source => update({ source })}
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
<div className="row g-3 mb-3">
|
|
<div className="col-sm-5">
|
|
<Form.Label>Typ</Form.Label>
|
|
<RecipeCategoryInput value={form.category} onChange={category => update({ category })} />
|
|
</div>
|
|
<div className="col-sm-3">
|
|
<Form.Label>Čas přípravy</Form.Label>
|
|
<div className="input-group">
|
|
<Form.Control
|
|
inputMode="numeric"
|
|
value={form.prepMinutes}
|
|
placeholder="volitelné"
|
|
onChange={event => update({ prepMinutes: event.target.value.replace(/\D/g, '') })}
|
|
/>
|
|
<span className="input-group-text">min</span>
|
|
</div>
|
|
{!!prepMinutes && prepMinutes >= 60 && <Form.Text>{formatPrepTime(prepMinutes)}</Form.Text>}
|
|
</div>
|
|
<div className="col-sm-4">
|
|
<Form.Label className="d-block">Chuť</Form.Label>
|
|
<ToggleButtonGroup
|
|
type="radio"
|
|
name={flavorId}
|
|
value={form.flavor}
|
|
onChange={(flavor: RecipeFlavor) => update({ flavor })}
|
|
>
|
|
{Object.values(RecipeFlavor).map(flavor => (
|
|
<ToggleButton
|
|
key={flavor}
|
|
id={`${flavorId}-${flavor}`}
|
|
value={flavor}
|
|
variant="outline-secondary"
|
|
>
|
|
{RECIPE_FLAVOR_NAMES[flavor]}
|
|
</ToggleButton>
|
|
))}
|
|
</ToggleButtonGroup>
|
|
</div>
|
|
</div>
|
|
|
|
<fieldset className="meal-fieldset mb-3">
|
|
<legend>Suroviny</legend>
|
|
<RecipeIngredientsEditor ingredients={ingredients} onChange={setIngredients} />
|
|
</fieldset>
|
|
|
|
<fieldset className="meal-fieldset mb-3">
|
|
<legend>Výsledek</legend>
|
|
<div className="row g-3">
|
|
<div className="col-sm-3">
|
|
<Form.Label>Počet porcí</Form.Label>
|
|
<Form.Control
|
|
inputMode="numeric"
|
|
value={form.servings}
|
|
placeholder="1"
|
|
onChange={event => update({ servings: event.target.value.replace(/\D/g, '') })}
|
|
/>
|
|
</div>
|
|
<div className="col-sm-4">
|
|
<Form.Label>Hmotnost hotového jídla</Form.Label>
|
|
<div className="input-group">
|
|
<Form.Control
|
|
inputMode="numeric"
|
|
value={form.cookedWeight}
|
|
placeholder={ingredientWeight ? String(ingredientWeight) : 'volitelné'}
|
|
onChange={event => update({ cookedWeight: event.target.value.replace(/\D/g, '') })}
|
|
/>
|
|
<span className="input-group-text">g</span>
|
|
</div>
|
|
<Form.Text>vařením se mění, bez ní se vezme součet surovin</Form.Text>
|
|
</div>
|
|
<div className="col-sm-5">
|
|
<Form.Label>Celkem / jedna porce</Form.Label>
|
|
<div className="recipe-summary">
|
|
{formatCalories(recipe.totalCalories)}
|
|
{recipe.totalWeight != null && <> · {formatWeight(recipe.totalWeight)}</>}
|
|
{recipe.caloriesPer100g != null && <> · {recipe.caloriesPer100g} kcal/100 g</>}
|
|
<div className="recipe-summary-portion">
|
|
porce {formatWeight(recipe.weight)} · {formatCalories(recipe.calories)}
|
|
{recipe.price != null && <> · {formatPrice(recipe.price)}</>}
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</fieldset>
|
|
|
|
{!!otherRecipeList.length && (
|
|
<fieldset className="meal-fieldset mb-3">
|
|
<legend>Souvisí s</legend>
|
|
{Object.values(RecipeLinkKind).map(kind => (
|
|
<div className="row g-2 mb-2 align-items-center" key={kind}>
|
|
<Form.Label className="col-sm-3 mb-0">{RECIPE_LINK_NAMES[kind]}</Form.Label>
|
|
<div className="col-sm-9">
|
|
<RecipeLinksInput
|
|
value={links[kind]}
|
|
recipeList={otherRecipeList.filter(recipe =>
|
|
!getOppositeLinkIds(links, kind).includes(recipe.id))}
|
|
placeholder={LINK_PLACEHOLDERS[kind]}
|
|
onChange={value => setLinks(current => ({ ...current, [kind]: value }))}
|
|
/>
|
|
</div>
|
|
</div>
|
|
))}
|
|
</fieldset>
|
|
)}
|
|
|
|
<Form.Group className="mb-3">
|
|
<div className="recipe-note-label">
|
|
<Form.Label>Postup</Form.Label>
|
|
<ToggleButtonGroup
|
|
type="radio"
|
|
name={`${flavorId}-note`}
|
|
size="sm"
|
|
value={notePreview ? 'preview' : 'edit'}
|
|
onChange={(value: string) => setNotePreview(value === 'preview')}
|
|
>
|
|
<ToggleButton id={`${flavorId}-note-edit`} value="edit" variant="outline-secondary">
|
|
Psát
|
|
</ToggleButton>
|
|
<ToggleButton
|
|
id={`${flavorId}-note-preview`}
|
|
value="preview"
|
|
variant="outline-secondary"
|
|
disabled={!form.note.trim()}
|
|
>
|
|
Náhled
|
|
</ToggleButton>
|
|
</ToggleButtonGroup>
|
|
</div>
|
|
{notePreview && form.note.trim()
|
|
? <div className="recipe-note-preview"><RecipeNote note={form.note} /></div>
|
|
: (
|
|
<Form.Control
|
|
as="textarea"
|
|
rows={8}
|
|
value={form.note}
|
|
placeholder={NOTE_PLACEHOLDER}
|
|
onChange={event => update({ note: event.target.value })}
|
|
/>
|
|
)}
|
|
<Form.Text>
|
|
Markdown: <code>## nadpis</code>, <code>- odrážka</code>, <code>1. krok</code>,
|
|
{' '}<code>**tučně**</code>, <code>*kurzíva*</code>
|
|
</Form.Text>
|
|
</Form.Group>
|
|
|
|
<div className="workout-form-footer">
|
|
{recipe.calories != null && (
|
|
<span className="workout-draft-calories">porce {formatCalories(recipe.calories)}</span>
|
|
)}
|
|
<Button variant="outline-secondary" size="sm" onClick={() => onCancel()}>Zrušit</Button>
|
|
<Button size="sm" onClick={() => save()} disabled={!canSave}>
|
|
{template ? 'Uložit změny' : 'Vytvořit recept'}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default MealTemplateForm;
|