feat(recipe): Edit-Modus für Zutaten, Schritte und Meta
All checks were successful
Build & Publish Docker Image / build-and-push (push) Successful in 1m18s

Auf der Rezept-Detail-Seite ein neuer „Bearbeiten"-Button (Pencil-Icon)
in der Action-Bar. Klick schaltet RecipeView auf RecipeEditor um.

Im Editor:
- Titel, Beschreibung, Portionen, Vorbereitungs-/Koch-/Gesamtzeit als
  inline-Inputs.
- Zutaten: pro Zeile Menge, Einheit, Name, Notiz + Trash-Icon zum
  Entfernen. „+ Zutat hinzufügen"-Dashed-Button am Listenende.
- Schritte: nummerierte Textareas, Trash-Icon, „+ Schritt hinzufügen".
- Mengen akzeptieren Komma- oder Punkt-Dezimalen.
- Empty-Items werden beim Speichern automatisch aussortiert.

Backend:
- Neue Repo-Funktionen updateRecipeMeta(id, patch), replaceIngredients,
  replaceSteps — letztere in einer Transaction mit delete+insert und
  FTS-Refresh.
- PATCH /api/recipes/[id] akzeptiert jetzt zusätzlich description,
  servings_default, servings_unit, prep_time_min, cook_time_min,
  total_time_min, cuisine, category, ingredients[], steps[]. Vorher
  nur title/hidden_from_recent; diese beiden bleiben als
  Kurz-Fall erhalten, damit bestehende Aufrufer unverändert laufen.
- Zod-Schema mit expliziten Grenzen (max-Länge, positive Mengen).

Tests: 3 neue Cases für updateRecipeMeta, replaceIngredients (inkl.
FTS-Update), replaceSteps.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
hsiegeln
2026-04-18 12:41:10 +02:00
parent ee783ff50b
commit 9a5c626890
5 changed files with 668 additions and 11 deletions

View File

@@ -0,0 +1,403 @@
<script lang="ts">
import { Plus, Trash2, GripVertical } from 'lucide-svelte';
import type { Recipe, Ingredient, Step } from '$lib/types';
type Props = {
recipe: Recipe;
saving?: boolean;
onsave: (patch: {
title: string;
description: string | null;
servings_default: number | null;
prep_time_min: number | null;
cook_time_min: number | null;
total_time_min: number | null;
ingredients: Ingredient[];
steps: Step[];
}) => void | Promise<void>;
oncancel: () => void;
};
let { recipe, saving = false, onsave, oncancel }: Props = $props();
let title = $state(recipe.title);
let description = $state(recipe.description ?? '');
let servings = $state<number | ''>(recipe.servings_default ?? '');
let prepMin = $state<number | ''>(recipe.prep_time_min ?? '');
let cookMin = $state<number | ''>(recipe.cook_time_min ?? '');
let totalMin = $state<number | ''>(recipe.total_time_min ?? '');
type DraftIng = {
qty: string;
unit: string;
name: string;
note: string;
};
type DraftStep = { text: string };
let ingredients = $state<DraftIng[]>(
recipe.ingredients.map((i) => ({
qty: i.quantity !== null ? String(i.quantity).replace('.', ',') : '',
unit: i.unit ?? '',
name: i.name,
note: i.note ?? ''
}))
);
let steps = $state<DraftStep[]>(
recipe.steps.map((s) => ({ text: s.text }))
);
function addIngredient() {
ingredients = [...ingredients, { qty: '', unit: '', name: '', note: '' }];
}
function removeIngredient(idx: number) {
ingredients = ingredients.filter((_, i) => i !== idx);
}
function addStep() {
steps = [...steps, { text: '' }];
}
function removeStep(idx: number) {
steps = steps.filter((_, i) => i !== idx);
}
function parseQty(raw: string): number | null {
const cleaned = raw.trim().replace(',', '.');
if (!cleaned) return null;
const n = Number(cleaned);
return Number.isFinite(n) ? n : null;
}
function toNumOrNull(v: number | ''): number | null {
return v === '' ? null : v;
}
async function save() {
const cleanedIngredients: Ingredient[] = ingredients
.filter((i) => i.name.trim())
.map((i, idx) => {
const qty = parseQty(i.qty);
const unit = i.unit.trim() || null;
const name = i.name.trim();
const note = i.note.trim() || null;
const rawParts: string[] = [];
if (qty !== null) rawParts.push(String(qty).replace('.', ','));
if (unit) rawParts.push(unit);
rawParts.push(name);
return {
position: idx + 1,
quantity: qty,
unit,
name,
note,
raw_text: rawParts.join(' ')
};
});
const cleanedSteps: Step[] = steps
.filter((s) => s.text.trim())
.map((s, idx) => ({ position: idx + 1, text: s.text.trim() }));
await onsave({
title: title.trim() || recipe.title,
description: description.trim() || null,
servings_default: toNumOrNull(servings),
prep_time_min: toNumOrNull(prepMin),
cook_time_min: toNumOrNull(cookMin),
total_time_min: toNumOrNull(totalMin),
ingredients: cleanedIngredients,
steps: cleanedSteps
});
}
</script>
<div class="editor">
<div class="meta">
<label class="field">
<span class="lbl">Titel</span>
<input type="text" bind:value={title} placeholder="Rezeptname" />
</label>
<label class="field">
<span class="lbl">Beschreibung</span>
<textarea bind:value={description} rows="2" placeholder="Kurze Beschreibung (optional)"></textarea>
</label>
<div class="row">
<label class="field small">
<span class="lbl">Portionen</span>
<input
type="number"
min="1"
bind:value={servings}
placeholder="—"
/>
</label>
<label class="field small">
<span class="lbl">Vorb. (min)</span>
<input type="number" min="0" bind:value={prepMin} placeholder="—" />
</label>
<label class="field small">
<span class="lbl">Kochen (min)</span>
<input type="number" min="0" bind:value={cookMin} placeholder="—" />
</label>
<label class="field small">
<span class="lbl">Gesamt (min)</span>
<input type="number" min="0" bind:value={totalMin} placeholder="—" />
</label>
</div>
</div>
<section class="block">
<h2>Zutaten</h2>
<ul class="ing-list">
{#each ingredients as ing, idx (idx)}
<li class="ing-row">
<span class="grip" aria-hidden="true"><GripVertical size={16} /></span>
<input class="qty" type="text" bind:value={ing.qty} placeholder="Menge" aria-label="Menge" />
<input class="unit" type="text" bind:value={ing.unit} placeholder="Einheit" aria-label="Einheit" />
<input class="name" type="text" bind:value={ing.name} placeholder="Zutat" aria-label="Zutat" />
<input class="note" type="text" bind:value={ing.note} placeholder="Notiz" aria-label="Notiz" />
<button class="del" type="button" aria-label="Zutat entfernen" onclick={() => removeIngredient(idx)}>
<Trash2 size={16} strokeWidth={2} />
</button>
</li>
{/each}
</ul>
<button class="add" type="button" onclick={addIngredient}>
<Plus size={16} strokeWidth={2} />
<span>Zutat hinzufügen</span>
</button>
</section>
<section class="block">
<h2>Zubereitung</h2>
<ol class="step-list">
{#each steps as step, idx (idx)}
<li class="step-row">
<span class="num">{idx + 1}</span>
<textarea
bind:value={step.text}
rows="3"
placeholder="Schritt beschreiben …"
></textarea>
<button class="del" type="button" aria-label="Schritt entfernen" onclick={() => removeStep(idx)}>
<Trash2 size={16} strokeWidth={2} />
</button>
</li>
{/each}
</ol>
<button class="add" type="button" onclick={addStep}>
<Plus size={16} strokeWidth={2} />
<span>Schritt hinzufügen</span>
</button>
</section>
<div class="foot">
<button class="btn ghost" type="button" onclick={oncancel} disabled={saving}>
Abbrechen
</button>
<button class="btn primary" type="button" onclick={save} disabled={saving}>
{saving ? 'Speichere …' : 'Speichern'}
</button>
</div>
</div>
<style>
.editor {
display: flex;
flex-direction: column;
gap: 1rem;
}
.meta {
display: flex;
flex-direction: column;
gap: 0.75rem;
background: white;
border: 1px solid #e4eae7;
border-radius: 12px;
padding: 1rem;
}
.field {
display: flex;
flex-direction: column;
gap: 0.3rem;
}
.lbl {
font-size: 0.8rem;
color: #666;
font-weight: 600;
}
.field input,
.field textarea {
padding: 0.55rem 0.7rem;
font-size: 0.95rem;
border: 1px solid #cfd9d1;
border-radius: 8px;
font-family: inherit;
background: white;
min-height: 40px;
}
.field textarea {
resize: vertical;
}
.row {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.small {
flex: 1;
min-width: 100px;
}
.block {
background: white;
border: 1px solid #e4eae7;
border-radius: 12px;
padding: 1rem;
}
.block h2 {
font-size: 1.05rem;
margin: 0 0 0.75rem;
color: #2b6a3d;
}
.ing-list,
.step-list {
list-style: none;
padding: 0;
margin: 0 0 0.6rem;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.ing-row {
display: grid;
grid-template-columns: 16px 70px 70px 1fr 90px 40px;
gap: 0.35rem;
align-items: center;
}
.grip {
color: #bbb;
display: inline-flex;
justify-content: center;
}
.ing-row input {
padding: 0.5rem 0.55rem;
border: 1px solid #cfd9d1;
border-radius: 8px;
font-size: 0.9rem;
min-height: 38px;
font-family: inherit;
min-width: 0;
}
.step-row {
display: grid;
grid-template-columns: 32px 1fr 40px;
gap: 0.5rem;
align-items: start;
}
.num {
width: 32px;
height: 32px;
background: #2b6a3d;
color: white;
border-radius: 50%;
display: grid;
place-items: center;
font-weight: 600;
font-size: 0.9rem;
margin-top: 0.25rem;
}
.step-row textarea {
padding: 0.55rem 0.7rem;
border: 1px solid #cfd9d1;
border-radius: 8px;
font-size: 0.95rem;
font-family: inherit;
resize: vertical;
min-height: 70px;
}
.del {
width: 40px;
height: 40px;
border: 1px solid #f1b4b4;
background: white;
color: #c53030;
border-radius: 8px;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
}
.del:hover {
background: #fdf3f3;
}
.add {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.55rem 0.9rem;
border: 1px dashed #cfd9d1;
background: white;
color: #2b6a3d;
border-radius: 8px;
cursor: pointer;
font-size: 0.9rem;
font-family: inherit;
}
.add:hover {
background: #f4f8f5;
}
.foot {
display: flex;
justify-content: space-between;
gap: 0.5rem;
padding-top: 0.5rem;
}
.btn {
padding: 0.7rem 1.25rem;
border-radius: 10px;
border: 1px solid #cfd9d1;
background: white;
cursor: pointer;
font-family: inherit;
font-size: 0.95rem;
min-height: 44px;
}
.btn.ghost {
color: #666;
}
.btn.primary {
background: #2b6a3d;
color: white;
border-color: #2b6a3d;
font-weight: 600;
}
.btn:disabled {
opacity: 0.6;
cursor: progress;
}
@media (max-width: 560px) {
.ing-row {
grid-template-columns: 70px 1fr 40px;
grid-template-areas:
'qty name del'
'unit unit del'
'note note note';
}
.grip {
display: none;
}
.ing-row .qty {
grid-area: qty;
}
.ing-row .unit {
grid-area: unit;
}
.ing-row .name {
grid-area: name;
}
.ing-row .note {
grid-area: note;
}
.ing-row .del {
grid-area: del;
}
}
</style>

View File

@@ -155,3 +155,79 @@ export function getRecipeIdBySourceUrl(
export function deleteRecipe(db: Database.Database, id: number): void {
db.prepare('DELETE FROM recipe WHERE id = ?').run(id);
}
export type RecipeMetaPatch = {
title?: string;
description?: string | null;
servings_default?: number | null;
servings_unit?: string | null;
prep_time_min?: number | null;
cook_time_min?: number | null;
total_time_min?: number | null;
cuisine?: string | null;
category?: string | null;
};
export function updateRecipeMeta(
db: Database.Database,
id: number,
patch: RecipeMetaPatch
): void {
const fields: string[] = [];
const values: unknown[] = [];
for (const key of [
'title',
'description',
'servings_default',
'servings_unit',
'prep_time_min',
'cook_time_min',
'total_time_min',
'cuisine',
'category'
] as const) {
if (patch[key] !== undefined) {
fields.push(`${key} = ?`);
values.push(patch[key]);
}
}
if (fields.length === 0) return;
fields.push('updated_at = CURRENT_TIMESTAMP');
db.prepare(`UPDATE recipe SET ${fields.join(', ')} WHERE id = ?`).run(...values, id);
}
export function replaceIngredients(
db: Database.Database,
recipeId: number,
ingredients: Ingredient[]
): void {
const tx = db.transaction(() => {
db.prepare('DELETE FROM ingredient WHERE recipe_id = ?').run(recipeId);
const ins = db.prepare(
`INSERT INTO ingredient(recipe_id, position, quantity, unit, name, note, raw_text)
VALUES (?, ?, ?, ?, ?, ?, ?)`
);
for (const ing of ingredients) {
ins.run(recipeId, ing.position, ing.quantity, ing.unit, ing.name, ing.note, ing.raw_text);
}
refreshFts(db, recipeId);
});
tx();
}
export function replaceSteps(
db: Database.Database,
recipeId: number,
steps: Step[]
): void {
const tx = db.transaction(() => {
db.prepare('DELETE FROM step WHERE recipe_id = ?').run(recipeId);
const ins = db.prepare(
'INSERT INTO step(recipe_id, position, text) VALUES (?, ?, ?)'
);
for (const step of steps) {
ins.run(recipeId, step.position, step.text);
}
});
tx();
}

View File

@@ -2,7 +2,13 @@ import type { RequestHandler } from './$types';
import { json, error } from '@sveltejs/kit';
import { z } from 'zod';
import { getDb } from '$lib/server/db';
import { deleteRecipe, getRecipeById } from '$lib/server/recipes/repository';
import {
deleteRecipe,
getRecipeById,
replaceIngredients,
replaceSteps,
updateRecipeMeta
} from '$lib/server/recipes/repository';
import {
listComments,
listCookingLog,
@@ -11,14 +17,36 @@ import {
setRecipeHiddenFromRecent
} from '$lib/server/recipes/actions';
const IngredientSchema = z.object({
position: z.number().int().nonnegative(),
quantity: z.number().nullable(),
unit: z.string().max(30).nullable(),
name: z.string().min(1).max(200),
note: z.string().max(300).nullable(),
raw_text: z.string().max(500)
});
const StepSchema = z.object({
position: z.number().int().positive(),
text: z.string().min(1).max(4000)
});
const PatchSchema = z
.object({
title: z.string().min(1).max(200).optional(),
description: z.string().max(2000).nullable().optional(),
servings_default: z.number().int().positive().nullable().optional(),
servings_unit: z.string().max(30).nullable().optional(),
prep_time_min: z.number().int().nonnegative().nullable().optional(),
cook_time_min: z.number().int().nonnegative().nullable().optional(),
total_time_min: z.number().int().nonnegative().nullable().optional(),
cuisine: z.string().max(60).nullable().optional(),
category: z.string().max(60).nullable().optional(),
ingredients: z.array(IngredientSchema).optional(),
steps: z.array(StepSchema).optional(),
hidden_from_recent: z.boolean().optional()
})
.refine((v) => v.title !== undefined || v.hidden_from_recent !== undefined, {
message: 'Need title or hidden_from_recent'
});
.refine((v) => Object.keys(v).length > 0, { message: 'Empty patch' });
function parseId(raw: string): number {
const id = Number(raw);
@@ -45,13 +73,51 @@ export const PATCH: RequestHandler = async ({ params, request }) => {
const parsed = PatchSchema.safeParse(body);
if (!parsed.success) error(400, { message: 'Invalid body' });
const db = getDb();
if (parsed.data.title !== undefined) {
renameRecipe(db, id, parsed.data.title);
const p = parsed.data;
// Spezielle Kurz-Updates (bleiben als Sonderfall, weil sie FTS triggern
// bzw. andere Tabellen mitpflegen).
if (p.title !== undefined && Object.keys(p).length === 1) {
renameRecipe(db, id, p.title);
return json({ ok: true });
}
if (parsed.data.hidden_from_recent !== undefined) {
setRecipeHiddenFromRecent(db, id, parsed.data.hidden_from_recent);
if (p.hidden_from_recent !== undefined && Object.keys(p).length === 1) {
setRecipeHiddenFromRecent(db, id, p.hidden_from_recent);
return json({ ok: true });
}
return json({ ok: true });
// Voller Edit-Modus-Patch.
const hasMeta =
p.title !== undefined ||
p.description !== undefined ||
p.servings_default !== undefined ||
p.servings_unit !== undefined ||
p.prep_time_min !== undefined ||
p.cook_time_min !== undefined ||
p.total_time_min !== undefined ||
p.cuisine !== undefined ||
p.category !== undefined;
if (hasMeta) {
updateRecipeMeta(db, id, {
title: p.title,
description: p.description,
servings_default: p.servings_default,
servings_unit: p.servings_unit,
prep_time_min: p.prep_time_min,
cook_time_min: p.cook_time_min,
total_time_min: p.total_time_min,
cuisine: p.cuisine,
category: p.category
});
}
if (p.ingredients !== undefined) {
replaceIngredients(db, id, p.ingredients);
}
if (p.steps !== undefined) {
replaceSteps(db, id, p.steps);
}
if (p.hidden_from_recent !== undefined) {
setRecipeHiddenFromRecent(db, id, p.hidden_from_recent);
}
return json({ ok: true, recipe: getRecipeById(db, id) });
};
export const DELETE: RequestHandler = async ({ params }) => {

View File

@@ -14,6 +14,7 @@
LightbulbOff
} from 'lucide-svelte';
import RecipeView from '$lib/components/RecipeView.svelte';
import RecipeEditor from '$lib/components/RecipeEditor.svelte';
import StarRating from '$lib/components/StarRating.svelte';
import { profileStore } from '$lib/client/profile.svelte';
import { wishlistStore } from '$lib/client/wishlist.svelte';
@@ -35,6 +36,46 @@
let titleDraft = $state('');
let titleInput: HTMLInputElement | null = $state(null);
let editMode = $state(false);
let saving = $state(false);
let recipeState = $state(data.recipe);
async function saveRecipe(patch: {
title: string;
description: string | null;
servings_default: number | null;
prep_time_min: number | null;
cook_time_min: number | null;
total_time_min: number | null;
ingredients: typeof data.recipe.ingredients;
steps: typeof data.recipe.steps;
}) {
saving = true;
try {
const res = await fetch(`/api/recipes/${data.recipe.id}`, {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(patch)
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
await alertAction({
title: 'Speichern fehlgeschlagen',
message: body.message ?? `HTTP ${res.status}`
});
return;
}
const body = await res.json();
if (body.recipe) {
recipeState = body.recipe;
title = body.recipe.title;
}
editMode = false;
} finally {
saving = false;
}
}
$effect(() => {
ratings = [...data.ratings];
comments = [...data.comments];
@@ -42,6 +83,7 @@
favoriteProfileIds = [...data.favorite_profile_ids];
wishlistProfileIds = [...data.wishlist_profile_ids];
title = data.recipe.title;
recipeState = data.recipe;
});
const myRating = $derived(
@@ -290,7 +332,15 @@
});
</script>
<RecipeView recipe={data.recipe}>
{#if editMode}
<RecipeEditor
recipe={recipeState}
{saving}
onsave={saveRecipe}
oncancel={() => (editMode = false)}
/>
{:else}
<RecipeView recipe={recipeState}>
{#snippet titleSlot()}
<div class="title-row">
{#if editingTitle}
@@ -369,6 +419,10 @@
<span>Bildschirm aus</span>
{/if}
</button>
<button class="btn" onclick={() => (editMode = true)}>
<Pencil size={18} strokeWidth={2} />
<span>Bearbeiten</span>
</button>
<button class="btn danger" onclick={deleteRecipe}>
<Trash2 size={18} strokeWidth={2} />
<span>Löschen</span>
@@ -377,6 +431,7 @@
</div>
{/snippet}
</RecipeView>
{/if}
<section class="comments">
<h2>Kommentare</h2>

View File

@@ -7,7 +7,10 @@ import {
insertRecipe,
getRecipeById,
getRecipeIdBySourceUrl,
deleteRecipe
deleteRecipe,
updateRecipeMeta,
replaceIngredients,
replaceSteps
} from '../../src/lib/server/recipes/repository';
import { extractRecipeFromHtml } from '../../src/lib/server/parsers/json-ld-recipe';
import type { Recipe } from '../../src/lib/types';
@@ -97,4 +100,58 @@ describe('recipe repository', () => {
deleteRecipe(db, id);
expect(getRecipeById(db, id)).toBeNull();
});
it('updateRecipeMeta patches only supplied fields', () => {
const db = openInMemoryForTest();
const id = insertRecipe(db, baseRecipe({ title: 'A', prep_time_min: 10 }));
updateRecipeMeta(db, id, { description: 'neu', prep_time_min: 15 });
const loaded = getRecipeById(db, id);
expect(loaded?.title).toBe('A'); // unverändert
expect(loaded?.description).toBe('neu');
expect(loaded?.prep_time_min).toBe(15);
});
it('replaceIngredients swaps full list and rebuilds FTS', () => {
const db = openInMemoryForTest();
const id = insertRecipe(
db,
baseRecipe({
title: 'Pasta',
ingredients: [
{ position: 1, quantity: 200, unit: 'g', name: 'Pancetta', note: null, raw_text: '200 g Pancetta' }
]
})
);
replaceIngredients(db, id, [
{ position: 1, quantity: 500, unit: 'g', name: 'Nudeln', note: null, raw_text: '500 g Nudeln' },
{ position: 2, quantity: 2, unit: null, name: 'Eier', note: null, raw_text: '2 Eier' }
]);
const loaded = getRecipeById(db, id);
expect(loaded?.ingredients.length).toBe(2);
expect(loaded?.ingredients[0].name).toBe('Nudeln');
// FTS index should reflect new ingredient
const hit = db
.prepare("SELECT rowid FROM recipe_fts WHERE recipe_fts MATCH 'nudeln'")
.all();
expect(hit.length).toBe(1);
});
it('replaceSteps swaps full list', () => {
const db = openInMemoryForTest();
const id = insertRecipe(
db,
baseRecipe({
title: 'S',
steps: [
{ position: 1, text: 'Alt' }
]
})
);
replaceSteps(db, id, [
{ position: 1, text: 'Erst' },
{ position: 2, text: 'Dann' }
]);
const loaded = getRecipeById(db, id);
expect(loaded?.steps.map((s) => s.text)).toEqual(['Erst', 'Dann']);
});
});