Refactoring

This commit is contained in:
araemer 2025-10-21 09:08:08 +02:00
parent 34bbaa9df4
commit 9b53f6e676
11 changed files with 501 additions and 515 deletions

View file

@ -21,15 +21,15 @@
}
.content-title {
@apply text-3xl font-black mb-8 text-blue-900;
@apply text-3xl font-black pb-6 text-blue-900;
}
.section-heading {
@apply text-xl font-bold mb-2;
@apply text-xl font-bold pb-2 pt-4;
}
.subsection-heading {
@apply font-semibold mb-2 mt-4;
@apply font-semibold pb-2 pt-4;
}
/* icons */
@ -50,7 +50,7 @@
/* buttons */
.basic-button {
@apply px-4 py-2 shadow-md rounded-lg whitespace-nowrap;
@apply px-4 py-2 shadow-md rounded-lg whitespace-nowrap disabled:opacity-50 disabled:cursor-not-allowed;
}
.default-button-bg {
@ -105,9 +105,9 @@
}
.ingredient-group-card {
@apply py-4 border-b border-gray-400;
@apply pb-4 border-b border-gray-400;
}
.circular-container {
@apply flex-shrink-0 w-7 h-7 rounded-full bg-blue-300 text-white flex items-center justify-center shadow-sm;
}

View file

@ -1,35 +1,38 @@
import { defaultIconSize } from "./SvgIcon";
import { ButtonType, type BasicButtonProps } from "./BasicButtonDefinitions";
import {defaultIconSize} from "./SvgIcon";
import {type BasicButtonProps, ButtonType} from "./BasicButtonDefinitions";
type ButtonProps = BasicButtonProps & {
onClick: () => void;
type ButtonProps = BasicButtonProps & {
onClick: () => void;
disabled?: boolean;
};
/**
* Button component. Styles are defined in BasicButtonDefinitions.ts
*/
export default function Button({
onClick,
icon: Icon,
text,
buttonType = ButtonType.DefaultButton,
className = "",
...props
}: ButtonProps) {
return (
<button
className={`basic-button bg-primary-button-bg ${buttonType.backgroundColor} ${buttonType.textColor} ${className}`}
onClick={onClick}
{...props}
>
<div className="flex items-center gap-2">
{Icon && (
<Icon
size={defaultIconSize}
/>
)}
{text}
</div>
</button>
);
onClick,
icon: Icon,
text,
buttonType = ButtonType.DefaultButton,
className = "",
disabled = false,
...props
}: ButtonProps) {
return (
<button
className={`basic-button bg-primary-button-bg ${buttonType.backgroundColor} ${buttonType.textColor} ${className}`}
onClick={onClick}
disabled={disabled}
{...props}
>
<div className="flex items-center gap-2">
{Icon && (
<Icon
size={defaultIconSize}
/>
)}
{text}
</div>
</button>
);
}

View file

@ -1,6 +1,6 @@
type NumberedListItemProps = {
/** Number to be displayed in front of text */
elementNumber: number;
/** Index of the element. Index + 1 is displayed in circle */
index: number;
/** List item text */
text: string;
}
@ -10,11 +10,11 @@ type NumberedListItemProps = {
* @param elementNumber Number to be displayed
* @param text Text to be displayed
*/
export function NumberedListItem({elementNumber, text}: NumberedListItemProps) {
export function NumberedListItem({index, text}: NumberedListItemProps) {
return <li className="flex items-start gap-4">
{/* Step number circle */}
<div className="circular-container">
{elementNumber}
{index + 1}
</div>
{/* Step text */}

View file

@ -2,85 +2,68 @@
* Editor for ingredient groups
*/
import type { IngredientModel } from "../../models/IngredientModel"
import type { IngredientGroupModel } from "../../models/IngredientGroupModel"
import type {IngredientModel} from "../../models/IngredientModel"
import type {IngredientGroupModel} from "../../models/IngredientGroupModel"
import Button from "../basics/Button"
import { IngredientListEditor } from "./IngredientListEditor"
import { Plus } from "lucide-react"
import { ButtonType } from "../basics/BasicButtonDefinitions"
import {IngredientListEditor} from "./IngredientListEditor"
import {Plus} from "lucide-react"
import {ButtonType} from "../basics/BasicButtonDefinitions"
type IngredientGroupListEditorProps = {
ingredientGroupList: IngredientGroupModel[]
onChange: (ingredientGroupList: IngredientGroupModel[]) => void
ingredientGroupList: IngredientGroupModel[]
onChange: (ingredientGroupList: IngredientGroupModel[]) => void
}
export function IngredientGroupListEditor({ ingredientGroupList, onChange }: IngredientGroupListEditorProps) {
const handleUpdate = (index: number, field: keyof IngredientGroupModel, value: string|IngredientModel[] ) => {
const updated = ingredientGroupList.map((ingGrp, i) =>
i === index ? { ...ingGrp, [field]: value} : ingGrp
export function IngredientGroupListEditor({ingredientGroupList, onChange}: IngredientGroupListEditorProps) {
const handleUpdate = (index: number, field: keyof IngredientGroupModel, value: string | IngredientModel[]) => {
const updated = ingredientGroupList.map((ingGrp, i) =>
i === index ? {...ingGrp, [field]: value} : ingGrp
)
onChange(updated)
}
const updateIngredientList = (index: number, ingredientList: IngredientModel[]) => {
handleUpdate(index, "ingredientList", ingredientList)
}
const handleAdd = () => {
onChange([...ingredientGroupList, {title: "", ingredientList: []}])
}
const handleRemove = (index: number) => {
onChange(ingredientGroupList.filter((_, i) => i !== index))
}
return (
<div>
<h2 className="section-heading">Zutaten</h2>
<div>
{ingredientGroupList.map((ingGrp, index) => (
<div key={index} className="ingredient-group-card mb-4">
<div className="horizontal-input-group columns-2">
<input
className="input-field"
placeholder="Titel (Optional)"
value={ingGrp.title}
onChange={e => handleUpdate(index, "title", e.target.value)}
/>
<Button
onClick={() => handleRemove(index)}
text={"Gruppe entfernen"}
buttonType={ButtonType.DarkButton}
/>
</div>
<IngredientListEditor
ingredients={ingGrp.ingredientList}
onChange={list => updateIngredientList(index, list)}
/>
</div>
))}
</div>
<Button
onClick={handleAdd}
icon={Plus}
text={"Gruppe hinzufügen"}
buttonType={ButtonType.PrimaryButton}
/>
</div>
)
onChange(updated)
}
const updateIngredientList = (index: number, ingredientList: IngredientModel[]) => {
handleUpdate(index, "ingredientList", ingredientList)
}
const handleAdd = () => {
onChange([...ingredientGroupList, { title: "", ingredientList: [] }])
}
const handleRemove = (index: number) => {
onChange(ingredientGroupList.filter((_, i) => i !== index))
}
return (
<div>
{/* remove bottom margin from this headings the group card has a top padding */}
<h3 className="subsection-heading" >Ingredient Groups</h3>
{ingredientGroupList.map((ingGrp, index) => (
<div key={index} className="ingredient-group-card mb-4">
<div className="horizontal-input-group columns-2">
<input
className="input-field"
placeholder="Group title (Optional)"
value = {ingGrp.title}
onChange={ e => handleUpdate(index, "title", e.target.value)}
/>
<Button
onClick={() => handleRemove(index)}
text={"Remove Group"}
buttonType={ButtonType.DarkButton}
/>
</div>
<IngredientListEditor
ingredients={ingGrp.ingredientList}
onChange={list => updateIngredientList(index,list)}
/>
</div>
))}
<Button
onClick={handleAdd}
icon={Plus}
text={"Add Ingredient Group"}
buttonType={ButtonType.PrimaryButton}
/>
</div>
)
}
/*
<button
type="button"
className="primary-button mt-4"
onClick={handleAdd}
>
<div
className="flex col-2 gap-2 -ml-1"
>
<SvgIcon
icon={Icon.Plus}
color={"text-gray-600"}
/>
Add Ingredient Group
</div>
</button>*/
}

View file

@ -1,70 +1,69 @@
import { Plus, X } from "lucide-react"
import type { IngredientModel } from "../../models/IngredientModel"
import {Plus, X} from "lucide-react"
import type {IngredientModel} from "../../models/IngredientModel"
import Button from "../basics/Button"
import { ButtonType } from "../basics/BasicButtonDefinitions"
import {ButtonType} from "../basics/BasicButtonDefinitions"
/**
/**
* Editor for handling the ingredient list
* Ingredients can be edited, added and removed
*/
type IngredientListEditorProps = {
ingredients: IngredientModel[]
onChange: (ingredients: IngredientModel[]) => void
ingredients: IngredientModel[]
onChange: (ingredients: IngredientModel[]) => void
}
export function IngredientListEditor({ ingredients, onChange }: IngredientListEditorProps) {
const handleUpdate = (index: number, field: keyof IngredientModel, value: string | number) => {
const updated = ingredients.map((ing, i) =>
i === index ? { ...ing, [field]: field === "amount" ? Number(value) : value } : ing
)
onChange(updated)
}
export function IngredientListEditor({ingredients, onChange}: IngredientListEditorProps) {
const handleUpdate = (index: number, field: keyof IngredientModel, value: string | number) => {
const updated = ingredients.map((ing, i) =>
i === index ? {...ing, [field]: field === "amount" ? Number(value) : value} : ing
)
onChange(updated)
}
const handleAdd = () => {
onChange([...ingredients, { name: "", amount: 0, unit: "" }])
}
const handleAdd = () => {
onChange([...ingredients, {name: "", amount: 0, unit: ""}])
}
const handleRemove = (index: number) => {
onChange(ingredients.filter((_, i) => i !== index))
}
const handleRemove = (index: number) => {
onChange(ingredients.filter((_, i) => i !== index))
}
return (
<div>
<h3 className="subsection-heading">Ingredients</h3>
{ingredients.map((ing, index) => (
<div key={index} className="horizontal-input-group">
<input
type="number"
className="input-field"
placeholder="Amount"
value={ing.amount}
onChange={e => handleUpdate(index, "amount", e.target.value)}
/>
<input
className="input-field w-20"
placeholder="Unit"
value={ing.unit ?? ""}
onChange={e => handleUpdate(index, "unit", e.target.value)}
/>
<input
className="input-field"
placeholder="Name"
value={ing.name}
onChange={e => handleUpdate(index, "name", e.target.value)}
/>
<Button
onClick={() => handleRemove(index)}
icon={X}
buttonType={ButtonType.DarkButton}
/>
return (
<div>
{ingredients.map((ing, index) => (
<div key={index} className="horizontal-input-group">
<input
type="number"
className="input-field"
placeholder="Menge"
value={ing.amount}
onChange={e => handleUpdate(index, "amount", e.target.value)}
/>
<input
className="input-field w-20"
placeholder="Einheit"
value={ing.unit ?? ""}
onChange={e => handleUpdate(index, "unit", e.target.value)}
/>
<input
className="input-field"
placeholder="Name"
value={ing.name}
onChange={e => handleUpdate(index, "name", e.target.value)}
/>
<Button
onClick={() => handleRemove(index)}
icon={X}
buttonType={ButtonType.DarkButton}
/>
</div>
))}
<Button
onClick={handleAdd}
icon={Plus}
text={"Zutat hinzufügen"}
buttonType={ButtonType.PrimaryButton}
/>
</div>
))}
<Button
onClick={handleAdd}
icon={Plus}
text={"Add Ingredient"}
buttonType={ButtonType.PrimaryButton}
/>
</div>
)
)
}

View file

@ -2,86 +2,76 @@
* Desktop editor using drag-and-drop via @dnd-kit
*/
import {
DndContext,
closestCenter,
PointerSensor,
useSensor,
useSensors,
} from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import type { InstructionStepModel } from "../../models/InstructionStepModel";
import { InstructionStepDesktopListItem } from "./InstructionStepDesktopListItem";
import { instructionStepListEditorMethods } from "./InstructionStepListEditor";
import {closestCenter, DndContext, PointerSensor, useSensor, useSensors,} from "@dnd-kit/core";
import {arrayMove, SortableContext, verticalListSortingStrategy,} from "@dnd-kit/sortable";
import type {InstructionStepModel} from "../../models/InstructionStepModel";
import {InstructionStepDesktopListItem} from "./InstructionStepDesktopListItem";
import Button from "../basics/Button";
import { Plus } from "lucide-react";
import { ButtonType } from "../basics/BasicButtonDefinitions";
import {Plus} from "lucide-react";
import {ButtonType} from "../basics/BasicButtonDefinitions";
import {instructionStepListEditorMethods} from "./InstructionStepListEditorMethods.ts";
type InstructionStepListDesktopEditorProps = {
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
};
export function InstructionStepListDesktopEditor({
instructionStepList,
onChange,
}: InstructionStepListDesktopEditorProps) {
const { handleUpdate, handleAdd, handleRemove } = instructionStepListEditorMethods(
instructionStepList,
onChange
);
instructionStepList,
onChange,
}: InstructionStepListDesktopEditorProps) {
const {handleUpdate, handleAdd, handleRemove} = instructionStepListEditorMethods(
instructionStepList,
onChange
);
const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 8 } }));
const sensors = useSensors(useSensor(PointerSensor, {activationConstraint: {distance: 8}}));
const handleDragEnd = (event: any) => {
const { active, over } = event;
if (active.id !== over.id) {
/* find element by internal id
* Caution! Due to new elements not having a real ID yet, each list item has an internal ID
* in order to give it a unique identifier before saving it to the backend. We have to compare
* the id of the drag item to the internalId of the list item here!
*/
const oldIndex = instructionStepList.findIndex((i) => i.internalId === active.id);
const newIndex = instructionStepList.findIndex((i) => i.internalId === over.id);
// move element to new position
const newOrder = arrayMove(instructionStepList, oldIndex, newIndex);
onChange(newOrder);
}
};
const handleDragEnd = (event: any) => {
const {active, over} = event;
if (active.id !== over.id) {
/* find element by internal id
* Caution! Due to new elements not having a real ID yet, each list item has an internal ID
* in order to give it a unique identifier before saving it to the backend. We have to compare
* the id of the drag item to the internalId of the list item here!
*/
const oldIndex = instructionStepList.findIndex((i) => i.internalId === active.id);
const newIndex = instructionStepList.findIndex((i) => i.internalId === over.id);
// move element to new position
const newOrder = arrayMove(instructionStepList, oldIndex, newIndex);
onChange(newOrder);
}
};
return (
<div>
<h3 className="subsection-heading mb-3">Zubereitung</h3>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext
items={instructionStepList.map((i) => i.internalId)}
strategy={verticalListSortingStrategy}
>
<div className="flex flex-col gap-3">
{instructionStepList.map((step, index) => (
<InstructionStepDesktopListItem
key={step.internalId}
id={step.internalId}
index={index}
step={step}
onUpdate={handleUpdate}
onRemove={handleRemove}
/>
))}
</div>
</SortableContext>
</DndContext>
<Button
onClick={handleAdd}
icon={Plus}
text="Schritt hinzufügen"
buttonType={ButtonType.PrimaryButton}
className="mt-4"
/>
</div>
);
return (
<div>
<h2 className="section-heading mb-2">Zubereitung</h2>
<DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext
items={instructionStepList.map((i) => i.internalId)}
strategy={verticalListSortingStrategy}
>
<div className="flex flex-col gap-3">
{instructionStepList.map((step, index) => (
<InstructionStepDesktopListItem
key={step.internalId}
id={step.internalId}
index={index}
step={step}
onUpdate={handleUpdate}
onRemove={handleRemove}
/>
))}
</div>
</SortableContext>
</DndContext>
<Button
onClick={handleAdd}
icon={Plus}
text="Schritt hinzufügen"
buttonType={ButtonType.PrimaryButton}
className="mt-4"
/>
</div>
);
}

View file

@ -6,81 +6,42 @@
* - Common functionality for adding, removing, and updating steps is centralized.
*/
import { useState, useEffect } from "react";
import type { InstructionStepModel } from "../../models/InstructionStepModel";
import { InstructionStepListDesktopEditor } from "./InstructionStepListDesktopEditor";
import { InstructionStepListMobileEditor } from "./InstructionStepListMobileEditor";
import {useEffect, useState} from "react";
import type {InstructionStepModel} from "../../models/InstructionStepModel";
import {InstructionStepListDesktopEditor} from "./InstructionStepListDesktopEditor";
import {InstructionStepListMobileEditor} from "./InstructionStepListMobileEditor";
/**
* Props for the hybrid InstructionStepListEditor
*/
type InstructionStepListEditorProps = {
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
};
/**
* Hybrid wrapper that decides between desktop (drag-and-drop) or mobile (buttons)
*/
export function InstructionStepListEditor({
instructionStepList,
onChange,
}: InstructionStepListEditorProps) {
const [isTouch, setIsTouch] = useState(false);
instructionStepList,
onChange,
}: InstructionStepListEditorProps) {
const [isTouch, setIsTouch] = useState(false);
useEffect(() => {
setIsTouch("ontouchstart" in window || navigator.maxTouchPoints > 0);
}, []);
useEffect(() => {
setIsTouch("ontouchstart" in window || navigator.maxTouchPoints > 0);
}, []);
return isTouch ? (
<InstructionStepListMobileEditor
instructionStepList={instructionStepList}
onChange={onChange}
/>
) : (
<InstructionStepListDesktopEditor
instructionStepList={instructionStepList}
onChange={onChange}
/>
);
}
/**
* ======= Shared hook for common logic =======
*
* Provides add/remove/update functionality used by both mobile and desktop editors.
*/
export function instructionStepListEditorMethods(
instructionStepList: InstructionStepModel[],
onChange: (steps: InstructionStepModel[]) => void
) {
/**
* Update the text of a specific step
*/
const handleUpdate = (index: number, value: string) => {
const updated = instructionStepList.map((step, i) =>
i === index ? { ...step, text: value } : step
return isTouch ? (
<InstructionStepListMobileEditor
instructionStepList={instructionStepList}
onChange={onChange}
/>
) : (
<InstructionStepListDesktopEditor
instructionStepList={instructionStepList}
onChange={onChange}
/>
);
onChange(updated);
};
/**
* Add a new step at the end
*/
const handleAdd = () => {
onChange([...instructionStepList,
{
text: "",
internalId: crypto.randomUUID() // add internalId required for drag & drop
}]);
};
/**
* Remove a step by index
*/
const handleRemove = (index: number) => {
onChange(instructionStepList.filter((_, i) => i !== index));
};
return { handleUpdate, handleAdd, handleRemove };
}

View file

@ -0,0 +1,41 @@
import type {InstructionStepModel} from "../../models/InstructionStepModel.ts";
/**
* ======= Shared hook for common logic =======
*
* Provides add/remove/update functionality used by both mobile and desktop editors.
*/
export function instructionStepListEditorMethods(
instructionStepList: InstructionStepModel[],
onChange: (steps: InstructionStepModel[]) => void
) {
/**
* Update the text of a specific step
*/
const handleUpdate = (index: number, value: string) => {
const updated = instructionStepList.map((step, i) =>
i === index ? {...step, text: value} : step
);
onChange(updated);
};
/**
* Add a new step at the end
*/
const handleAdd = () => {
onChange([...instructionStepList,
{
text: "",
internalId: crypto.randomUUID() // add internalId required for drag & drop
}]);
};
/**
* Remove a step by index
*/
const handleRemove = (index: number) => {
onChange(instructionStepList.filter((_, i) => i !== index));
};
return {handleUpdate, handleAdd, handleRemove};
}

View file

@ -2,86 +2,91 @@
* Mobile editor using Up/Down buttons for reordering
*/
import { ArrowDown, ArrowUp, Plus, X } from "lucide-react";
import type { InstructionStepModel } from "../../models/InstructionStepModel";
import {ArrowDown, ArrowUp, Plus, X} from "lucide-react";
import type {InstructionStepModel} from "../../models/InstructionStepModel";
import Button from "../basics/Button";
import { instructionStepListEditorMethods } from "./InstructionStepListEditor";
import { ButtonType } from "../basics/BasicButtonDefinitions";
import {ButtonType} from "../basics/BasicButtonDefinitions";
import {instructionStepListEditorMethods} from "./InstructionStepListEditorMethods.ts";
type InstructionStepListEditorMobileProps = {
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
instructionStepList: InstructionStepModel[];
onChange: (steps: InstructionStepModel[]) => void;
};
export function InstructionStepListMobileEditor({
instructionStepList,
onChange,
}: InstructionStepListEditorMobileProps) {
const { handleUpdate, handleAdd, handleRemove } = instructionStepListEditorMethods(
instructionStepList,
onChange
);
instructionStepList,
onChange,
}: InstructionStepListEditorMobileProps) {
const {handleUpdate, handleAdd, handleRemove} = instructionStepListEditorMethods(
instructionStepList,
onChange
);
const moveStep = (index: number, direction: "up" | "down") => {
const newIndex = direction === "up" ? index - 1 : index + 1;
if (newIndex < 0 || newIndex >= instructionStepList.length) return;
const newList = [...instructionStepList];
const [moved] = newList.splice(index, 1);
newList.splice(newIndex, 0, moved);
onChange(newList);
};
const moveStep = (index: number, direction: "up" | "down") => {
const newIndex = direction === "up" ? index - 1 : index + 1;
if (newIndex < 0 || newIndex >= instructionStepList.length) return;
const newList = [...instructionStepList];
const [moved] = newList.splice(index, 1);
newList.splice(newIndex, 0, moved);
onChange(newList);
};
return (
<div className="flex flex-col gap-3">
{instructionStepList.map((step, index) => (
<div
key={step.id}
className="flex items-start gap-3 bg-gray-50 rounded-xl p-3 shadow-sm"
>
<div className="flex flex-col items-center pt-1">
<div className="w-8 h-8 rounded-full bg-gray-300 flex items-center justify-center text-sm font-semibold text-gray-800">
{index + 1}
return (
<div>
<h2 className="section-heading mb-2">Zubereitung</h2>
<div className="flex flex-col gap-3">
{instructionStepList.map((step, index) => (
<div
key={step.id}
className="flex items-start gap-3 bg-gray-50 rounded-xl p-3 shadow-sm"
>
<div className="flex flex-col items-center pt-1">
<div className="circular-container">
{index + 1}
</div>
<div className="flex flex-col mt-2">
<Button
icon={ArrowUp}
onClick={() => moveStep(index, "up")}
buttonType={ButtonType.TransparentButton}
disabled={index === 0} // disable if first item
/>
<Button
icon={ArrowDown}
onClick={() => moveStep(index, "down")}
buttonType={ButtonType.TransparentButton}
disabled={index === instructionStepList.length - 1} // disable if last item
/>
</div>
</div>
<textarea
className="input-field w-full min-h-[120px] resize-none overflow-hidden"
placeholder={`Schritt ${index + 1}`}
value={step.text}
onChange={(e) => handleUpdate(index, e.target.value)}
onInput={(e) => {
const el = e.target as HTMLTextAreaElement;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}}
/>
<Button
onClick={() => handleRemove(index)}
icon={X}
buttonType={ButtonType.DarkButton}
/>
</div>
))}
<Button
onClick={handleAdd}
icon={Plus}
text="Schritt hinzufügen"
buttonType={ButtonType.PrimaryButton}
className="mt-4"
/>
</div>
<div className="flex flex-col mt-2">
<Button
icon={ArrowUp}
onClick={() => moveStep(index, "up")}
buttonType={ButtonType.TransparentButton}
/>
<Button
icon={ArrowDown}
onClick={() => moveStep(index, "down")}
buttonType={ButtonType.TransparentButton}
/>
</div>
</div>
<textarea
className="input-field w-full min-h-[60px] resize-none overflow-hidden"
placeholder={`Schritt ${index + 1}`}
value={step.text}
onChange={(e) => handleUpdate(index, e.target.value)}
onInput={(e) => {
const el = e.target as HTMLTextAreaElement;
el.style.height = "auto";
el.style.height = `${el.scrollHeight}px`;
}}
/>
<Button
onClick={() => handleRemove(index)}
icon={X}
buttonType={ButtonType.DarkButton}
/>
</div>
))}
<Button
onClick={handleAdd}
icon={Plus}
text="Schritt hinzufügen"
buttonType={ButtonType.PrimaryButton}
className="mt-4"
/>
</div>
);
);
}

View file

@ -80,7 +80,7 @@ export default function RecipeDetailPage() {
<div className="content-container">
{/* Header - remains in position when scrolling */}
<div className="sticky-header">
<h1 className="content-title mb-0">{recipeWorkingCopy.title}</h1>
<h1 className="content-title mb-0 pb-0">{recipeWorkingCopy.title}</h1>
</div>
{/* Content */}
@ -132,7 +132,7 @@ export default function RecipeDetailPage() {
{/* Instructions - @todo add reasonable list delegate component*/}
<ol className="space-y-4">
{recipe.instructionStepList.map((step, j) => (
<NumberedListItem key={j} elementNumber={j + 1} text={step.text}/>
<NumberedListItem key={j} index={j} text={step.text}/>
))}
</ol>

View file

@ -1,16 +1,16 @@
import { useState } from "react"
import type { RecipeModel } from "../../models/RecipeModel"
import type { IngredientGroupModel } from "../../models/IngredientGroupModel"
import { IngredientGroupListEditor } from "./IngredientGroupListEditor"
import {useState} from "react"
import type {RecipeModel} from "../../models/RecipeModel"
import type {IngredientGroupModel} from "../../models/IngredientGroupModel"
import {IngredientGroupListEditor} from "./IngredientGroupListEditor"
import Button from "../basics/Button"
import { InstructionStepListEditor } from "./InstructionStepListEditor"
import type { InstructionStepModel } from "../../models/InstructionStepModel"
import { ButtonType } from "../basics/BasicButtonDefinitions"
import {InstructionStepListEditor} from "./InstructionStepListEditor"
import type {InstructionStepModel} from "../../models/InstructionStepModel"
import {ButtonType} from "../basics/BasicButtonDefinitions"
type RecipeEditorProps = {
recipe: RecipeModel
onSave: (recipe: RecipeModel) => void
onCancel: () => void
recipe: RecipeModel
onSave: (recipe: RecipeModel) => void
onCancel: () => void
}
/**
@ -18,138 +18,142 @@ type RecipeEditorProps = {
* ingredients (with amount, unit, name), instructions, and image URL.
* @todo adapt to ingredientGroups!
*/
export default function RecipeEditor({ recipe, onSave, onCancel }: RecipeEditorProps) {
/** draft of the new recipe */
const [draft, setDraft] = useState<RecipeModel>(recipe)
/** Error list */
const [errors, setErrors] = useState<{ title?: boolean; ingredients?: boolean }>({})
export default function RecipeEditor({recipe, onSave, onCancel}: RecipeEditorProps) {
/** draft of the new recipe */
const [draft, setDraft] = useState<RecipeModel>(recipe)
/** Error list */
const [errors, setErrors] = useState<{ title?: boolean; ingredients?: boolean }>({})
/**
* Update ingredients
* @param ingredientGroupList updated ingredient groups and ingredients
*/
const updateIngredientGroupList = (ingredientGroupList: IngredientGroupModel[]) => {
setDraft({ ...draft, ingredientGroupList })
}
/**
* Update instruction steps
* @param instructionStepList updated instructions
*/
const updateInstructionList = (instructionStepList: InstructionStepModel[]) => {
setDraft({ ...draft, instructionStepList })
}
/**
* 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
}
/* there must be at least one ingredient group
* no group may contain an empty ingredient list
* @todo check whether all ingredients are valid
* @todo enhance visualization of ingredient errors
/**
* Update ingredients
* @param ingredientGroupList updated ingredient groups and ingredients
*/
if (!draft.ingredientGroupList || draft.ingredientGroupList.length === 0) {
newErrors.ingredients = true
} else {
let isAnyIngredientListEmpty = draft.ingredientGroupList.some(
ingGrp => {
return !ingGrp.ingredientList || ingGrp.ingredientList.length === 0
const updateIngredientGroupList = (ingredientGroupList: IngredientGroupModel[]) => {
setDraft({...draft, ingredientGroupList})
}
/**
* Update instruction steps
* @param instructionStepList updated instructions
*/
const updateInstructionList = (instructionStepList: InstructionStepModel[]) => {
setDraft({...draft, instructionStepList})
}
/**
* 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
}
)
if(isAnyIngredientListEmpty){
newErrors.ingredients = true
}
/* there must be at least one ingredient group
* no group may contain an empty ingredient list
* @todo check whether all ingredients are valid
* @todo enhance visualization of ingredient errors
*/
if (!draft.ingredientGroupList || draft.ingredientGroupList.length === 0) {
newErrors.ingredients = true
} else {
const isAnyIngredientListEmpty = draft.ingredientGroupList.some(
ingGrp => {
return !ingGrp.ingredientList || ingGrp.ingredientList.length === 0
}
)
if (isAnyIngredientListEmpty) {
newErrors.ingredients = true
}
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
setErrors(newErrors)
return Object.keys(newErrors).length === 0
}
/** Handles saving and ensures that the draft is only saved if valid */
const handleSave = (draft: RecipeModel) => {
if (validate()) {
onSave(draft)
/** Handles saving and ensures that the draft is only saved if valid */
const handleSave = (draft: RecipeModel) => {
if (validate()) {
onSave(draft)
}
}
}
// ensure that there is a recipe and show error otherwise
if (!recipe) return <div>Oops, there's no recipe in RecipeEditor...</div>
// @todo add handling of images
return (
<div className="p-4 gap-10">
<h2 className="content-title">
{recipe.id ? "Edit Recipe" : "New Recipe"}
</h2>
// ensure that there is a recipe and show error otherwise
if (!recipe) return <div>Oops, there's no recipe in RecipeEditor...</div>
// @todo add handling of images
return (
/*Container spanning entire screen used to center content horizontally */
<div className="app-bg">
{/* Container defining the maximum width of the content */}
<div className="content-container">
<h1 className="content-title border-b-2 border-gray-300">
{recipe.id ? "Rezept bearbeiten" : "Neues Rezept"}
</h1>
{/* Title */}
<h3 className="subsection-heading">Title</h3>
<input
className={`input-field ${errors.title ? "error-text" : ""}`}
placeholder="Title"
value={draft.title}
onChange={e => setDraft({ ...draft, title: e.target.value })}
/>
{/* Servings */}
<h3 className="subsection-heading">Servings</h3>
<div className="columns-3 gap-2 flex items-center">
<label>For</label>
<input
type="number"
className="input-field w-20"
placeholder="1"
value={draft.servings.amount}
onChange={e => {
const tempServings = draft.servings
tempServings.amount = Number(e.target.value)
setDraft({...draft, servings: tempServings})
}}
/>
<input
className="input-field"
placeholder="Persons"
value={draft.servings.unit}
onChange={e => {
const tempServings = draft.servings
tempServings.unit = e.target.value
setDraft({...draft, servings: tempServings})
}}
/>
</div>
{/* Ingredient List - @todo better visualization of errors! */}
<div className={errors.ingredients ? "border error-text rounded p-2" : ""}>
<IngredientGroupListEditor
ingredientGroupList={draft.ingredientGroupList}
onChange={updateIngredientGroupList}
/>
</div>
{/* Title */}
<h2 className="section-heading">Titel</h2>
<input
className={`input-field ${errors.title ? "error-text" : ""}`}
placeholder="Titel"
value={draft.title}
onChange={e => setDraft({...draft, title: e.target.value})}
/>
{/* Servings */}
<h2 className="section-heading">Portionen</h2>
<div className="columns-3 gap-2 flex items-center">
<label>Für</label>
<input
type="number"
className="input-field w-20"
placeholder="1"
value={draft.servings.amount}
onChange={e => {
const tempServings = draft.servings
tempServings.amount = Number(e.target.value)
setDraft({...draft, servings: tempServings})
}}
/>
<input
className="input-field"
placeholder="Personen"
value={draft.servings.unit}
onChange={e => {
const tempServings = draft.servings
tempServings.unit = e.target.value
setDraft({...draft, servings: tempServings})
}}
/>
</div>
{/* Ingredient List - @todo better visualization of errors! */}
<div className={errors.ingredients ? "border error-text rounded p-2" : ""}>
<IngredientGroupListEditor
ingredientGroupList={draft.ingredientGroupList}
onChange={updateIngredientGroupList}
/>
</div>
{/* Instruction List*/ }
<InstructionStepListEditor
instructionStepList={draft.instructionStepList}
onChange={updateInstructionList}
/>
{/* Instruction List*/}
<InstructionStepListEditor
instructionStepList={draft.instructionStepList}
onChange={updateInstructionList}
/>
<div className="button-group">
{/* Save Button */}
<Button
onClick={() => handleSave(draft)}
text={"Save"}
buttonType={ButtonType.PrimaryButton}
/>
<Button
onClick={() => onCancel()}
text={"Cancel"}
/>
</div>
</div>
<div className="button-group">
{/* Save Button */}
<Button
onClick={() => handleSave(draft)}
text={"Speichern"}
buttonType={ButtonType.PrimaryButton}
/>
<Button
onClick={() => onCancel()}
text={"Abbrechen"}
/>
</div>
</div>
</div>
)
}