Merging in the React Refactor #56

Merged
azpect merged 51 commits from refactor/react into master 2025-12-28 22:27:52 -07:00
4 changed files with 278 additions and 143 deletions
Showing only changes of commit c9aa4e62fa - Show all commits

View File

@ -1,17 +1,108 @@
import type { RecipeIngredient } from "../../types/recipe"; import { Reorder, useDragControls } from "motion/react";
import { INGREDIENT_UNITS, type RecipeIngredient } from "../../types/recipe";
import DeleteIconSmall from "../icons/DeleteIconSmall";
import DragIconSmall from "../icons/DragIconSmall";
import { useEffect, useState } from "react";
interface IngredientItemProps { interface IngredientItemProps {
classes: string;
ingredient: RecipeIngredient; ingredient: RecipeIngredient;
onChange: (id: string, name: string) => void; onChange: (id: string, name: "Amount" | "Unit" | "Name", value: string) => void;
removeIngredientHandler: (id: string) => void;
allowDelete: boolean;
} }
export default function IngredientItem({ ingredient, onChange }: IngredientItemProps) { export default function IngredientItem({ classes, ingredient, onChange, removeIngredientHandler, allowDelete }: IngredientItemProps) {
const [dirty, setDirty] = useState<boolean>(false);
const [valid, setValid] = useState<boolean>(false);
const controls = useDragControls();
// HANDLERS
const changeHandler = (name: "Amount" | "Unit" | "Name", value: string) => {
if (!dirty) setDirty(true);
onChange(ingredient.Id, name, value);
}
useEffect(() => {
let _valid = true;
if (ingredient.Name.trim() === "") _valid = false;
if (ingredient.Unit === "") _valid = false;
if (ingredient.Amount <= 0) _valid = false;
setValid(_valid);
}, [ingredient]);
useEffect(() => {
console.log("@dirty", dirty);
}, [dirty]);
return ( return (
<input <Reorder.Item
type="text" key={ingredient.Id}
value={ingredient.Name} value={ingredient}
onChange={(e) => onChange(ingredient.Id, e.target.value)} dragListener={false}
placeholder="Ingredient name" dragControls={controls}
/> className="select-none p-2 flex gap-2 flex-col"
>
<div className="flex gap-2">
<div className="flex-col md:flex-row flex-grow flex gap-2">
<div className="flex gap-2">
<input
type="number"
step="0.25"
min="0"
placeholder="amount"
required
value={ingredient.Amount}
onChange={(e) => changeHandler("Amount", e.target.value)}
className={`w-1/2 md:w-28 ${classes} ${dirty && ingredient.Amount <= 0 ? "border-red-500" : ""}`}
/>
<select
onChange={(e) => changeHandler("Unit", e.target.value)}
className={`w-1/2 md:w-fit ${classes} ${dirty && ingredient.Unit === "" ? "border-red-500" : ""}`}
>
{INGREDIENT_UNITS.map(unit => (
<option key={unit} value={unit}>{unit ? unit : "Select"}</option>
))}
</select>
</div>
<input
type="text"
placeholder="Ingredient name"
required
value={ingredient.Name}
onChange={(e) => changeHandler("Name", e.target.value)}
className={`flex-grow ${classes} ${dirty && ingredient.Name.trim() === "" ? "border-red-500" : ""}`}
/>
</div>
<div className="flex-col md:flex-row flex gap-x-2 items-center justify-evenly md:justify-center">
<button
tabIndex={-1}
disabled={!allowDelete}
onClick={() => removeIngredientHandler(ingredient.Id)}
className="p-1 md:p-2 md:pr-0 cursor-pointer text-gray-500 hover:text-red-500 disabled:text-gray-200 disabled:cursor-not-allowed duration-300"
>
<DeleteIconSmall />
</button>
<div
tabIndex={-1}
onPointerDown={(e) => controls.start(e)}
className="p-1 md:p-0 cursor-pointer"
>
<DragIconSmall />
</div>
</div>
</div>
{(dirty && !valid) && (
<p className="text-sm text-red-500"> Please fill out all fields. </p>
)}
</Reorder.Item>
); );
} }

View File

@ -1,59 +1,40 @@
import type { Dispatch, SetStateAction } from "react";
import { type IngredientId, type IngredientsById, type RecipeIngredient, type RecipeIngredientSection, type SectionsById } from "../../types/recipe";
import IngredientSectionElement from "./IngredientSectionElement";
import { Reorder } from "motion/react"; import { Reorder } from "motion/react";
import type { RecipeIngredient, RecipeIngredientSection } from "../../types/recipe";
import IngredientItem from "./IngredientItem";
interface IngredientListProps { interface IngredientListProps {
classes: string;
section: RecipeIngredientSection;
ingredients: RecipeIngredient[];
setSectionIngredients: (sectionId: string, ingredients: RecipeIngredient[]) => void;
ingredientChangeHandler: (id: string, name: "Amount" | "Unit" | "Name", value: string) => void;
removeIngredientHandler: (id: string) => void;
} }
export default function IngredientList({ sectionOrder, setSectionOrder, sectionsById, ingredientsById, setIngredientsById }: IngredientListProps) { export default function IngredientList({ classes, section, ingredients, setSectionIngredients, ingredientChangeHandler, removeIngredientHandler }: IngredientListProps) {
const handleIngredientChange = ( const sectionIngredients = ingredients.filter(x => x.SectionId === section.Id);
ingredientId: IngredientId,
field: "Name" | "Amount" | "Unit",
value: string
) => {
setIngredientsById(prev => {
const ing = prev[ingredientId];
if (!ing) return prev;
const updated: RecipeIngredient = { const reorderHandler = (ingredients: RecipeIngredient[]) => {
...ing, setSectionIngredients(section.Id, ingredients);
[field]: }
field === "Amount"
? (value === "" ? 0 : Number(value))
: value,
};
// If nothing changed, keep same reference
if (updated === ing) return prev;
return { ...prev, [ingredientId]: updated };
});
};
return ( return (
<> <Reorder.Group
<Reorder.Group axis="y"
axis="y" values={ingredients}
values={sectionOrder} onReorder={reorderHandler}
onReorder={setSectionOrder} className="flex flex-col"
> >
{sectionOrder.map(sectionId => { {sectionIngredients.map(ing =>
const section = sectionsById[sectionId]; <IngredientItem
console.log("@section", section); key={ing.Id}
return ( classes={classes}
<Reorder.Item key={sectionId} value={sectionId}> ingredient={ing}
<IngredientSectionElement onChange={ingredientChangeHandler}
section={section} removeIngredientHandler={removeIngredientHandler}
ingredientsById={ingredientsById} allowDelete={sectionIngredients.length > 1}
onChange={handleIngredientChange} />
/> )}
</Reorder.Group>
</Reorder.Item>
)
})}
</Reorder.Group>
</>
); );
} }

View File

@ -1,36 +1,53 @@
import type { DragControls } from "motion/react"; import { Reorder, useDragControls } from "motion/react";
import type { RecipeIngredientSection } from "../../types/recipe"; import type { RecipeIngredientSection } from "../../types/recipe";
import DeleteIconSmall from "../icons/DeleteIconSmall"; import DeleteIconSmall from "../icons/DeleteIconSmall";
import DragIconSmall from "../icons/DragIconSmall"; import DragIconSmall from "../icons/DragIconSmall";
import type { ReactNode } from "react";
interface IngredientSectionProps { interface IngredientSectionProps {
section: RecipeIngredientSection; section: RecipeIngredientSection;
onChange: (id: string, name: string) => void; onChange: (id: string, name: string) => void;
index: number; removeIngredientSectionHandler: (id: string) => void;
controls: DragControls; allowDelete: boolean;
children?: ReactNode;
}; };
export default function IngredientSection({ section, onChange, index, controls }: IngredientSectionProps) { export default function IngredientSection({ section, onChange, removeIngredientSectionHandler, allowDelete, children }: IngredientSectionProps) {
const controls = useDragControls();
return ( return (
<div className="w-full bg-gray-100 p-3 flex items-center"> <Reorder.Item
<p className="font-semibold">Group:</p> key={section.Id}
<input value={section}
type="text" dragListener={false}
value={section.Name} dragControls={controls}
onChange={(e) => onChange(section.Id, e.target.value)} className="select-none"
placeholder="Section title" >
className="mx-2 px-2 py-1 border border-gray-300 flex-grow rounded-sm" <div className="w-full bg-gray-100 p-3 flex items-center my-2">
/> <p className="text-xs md:text-sm font-semibold">Group:</p>
<input
type="text"
value={section.Name}
onChange={(e) => onChange(section.Id, e.target.value)}
placeholder="Section title"
className="mx-2 px-2 py-1 border border-gray-300 flex-grow rounded-sm"
/>
<div className="w-1/10 flex justify-between"> <div className="flex gap-x-2 items-center">
<button className="cursor-pointer"> <button
<DeleteIconSmall /> disabled={!allowDelete}
</button> className="p-2 pr-0 cursor-pointer text-gray-500 hover:text-red-500 disabled:text-gray-200 disabled:cursor-not-allowed duration-300"
<div className="cursor-pointer" onPointerDown={(e) => controls.start(e)}> onClick={() => removeIngredientSectionHandler(section.Id)}
<DragIconSmall /> >
<DeleteIconSmall />
</button>
<div className="p-0 cursor-pointer" onPointerDown={(e) => controls.start(e)}>
<DragIconSmall />
</div>
</div> </div>
</div> </div>
</div> {children}
</Reorder.Item>
); );
} }

View File

@ -1,12 +1,11 @@
import { Fragment, useEffect, useState, type ChangeEvent, type FormEvent } from "react"; import { useEffect, useState, type ChangeEvent, type FormEvent } from "react";
import Banner from "../components/Banner"; import Banner from "../components/Banner";
import { isRecipeMeal, RecipeIngredient, type IngredientsById, type RecipeIngredientSection, type RecipeInstruction, type SectionId, type SectionsById } from "../types/recipe"; import { isRecipeMeal, type RecipeIngredient, type RecipeIngredientSection, type RecipeIngredientUnit, type RecipeInstruction } from "../types/recipe";
import InstructionList from "../components/forms/InstructionList"; import InstructionList from "../components/forms/InstructionList";
import ValidationErrorList from "../components/forms/ValidationErrorList"; import ValidationErrorList from "../components/forms/ValidationErrorList";
import IngredientSection from "../components/forms/IngredientSection"; import IngredientSection from "../components/forms/IngredientSection";
import { section } from "motion/react-client"; import { Reorder } from "motion/react";
import IngredientItem from "../components/forms/IngredientItem"; import IngredientList from "../components/forms/IngredientList";
import { Reorder, useDragControls } from "motion/react";
// TODO: Move this // TODO: Move this
interface CreateRecipeForm { interface CreateRecipeForm {
@ -59,41 +58,18 @@ export default function Create() {
image: null, image: null,
}); });
// Store complex values elsewhere // Store complex values elsewhere
const [instructions, setInstructions] = useState<RecipeInstruction[]>([{ Id: crypto.randomUUID(), Content: "" }, { Id: crypto.randomUUID(), Content: "" }]); const [instructions, setInstructions] = useState<RecipeInstruction[]>([
{ Id: crypto.randomUUID(), Content: "" }
]);
// Ingredients
const [sections, setSections] = useState<RecipeIngredientSection[]>([ const [sections, setSections] = useState<RecipeIngredientSection[]>([
{ Id: "a", Name: "Section 1" }, { Id: "initial-section", Name: "Unnamed group" },
{ Id: "b", Name: "Section 2" },
{ Id: "c", Name: "Section 3" }
]); ]);
const [ingredients, setIngredients] = useState<RecipeIngredient[]>([ const [ingredients, setIngredients] = useState<RecipeIngredient[]>([
{ Id: crypto.randomUUID(), SectionId: "a", Name: "Ingredient 1", Amount: 1, Unit: "lb" }, { Id: crypto.randomUUID(), SectionId: "initial-section", Name: "", Amount: 0, Unit: "" },
{ Id: crypto.randomUUID(), SectionId: "a", Name: "Ingredient 2", Amount: 1, Unit: "lb" },
{ Id: crypto.randomUUID(), SectionId: "b", Name: "Ingredient 3", Amount: 1, Unit: "lb" },
{ Id: crypto.randomUUID(), SectionId: "c", Name: "Ingredient 4", Amount: 1, Unit: "lb" },
{ Id: crypto.randomUUID(), SectionId: "c", Name: "Ingredient 5", Amount: 1, Unit: "lb" },
{ Id: crypto.randomUUID(), SectionId: "c", Name: "Ingredient 6", Amount: 1, Unit: "lb" },
]); ]);
const sectionChangeHandler = (id: string, name: string) => {
setSections(prev =>
prev.map(section =>
section.Id === id ? { ...section, Name: name } : section
)
);
}
const ingredientChangeHandler = (id: string, name: string) => {
setIngredients(prev =>
prev.map(ing =>
ing.Id === id ? { ...ing, Name: name } : ing
)
);
}
// VALIDATION STATE // VALIDATION STATE
const [validation, setValidation] = useState<CreateRecipeFormToggles>({ const [validation, setValidation] = useState<CreateRecipeFormToggles>({
title: true, title: true,
@ -136,7 +112,6 @@ export default function Create() {
setValidation(state); setValidation(state);
} }
// HANDLERS // HANDLERS
const changeHandler = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => { const changeHandler = (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
const { name, value } = e.target; const { name, value } = e.target;
@ -186,22 +161,76 @@ export default function Create() {
setInstructions([...instructions, { Id: crypto.randomUUID(), Content: "" }]); setInstructions([...instructions, { Id: crypto.randomUUID(), Content: "" }]);
} }
const sectionChangeHandler = (id: string, name: string) => {
setSections(prev =>
prev.map(section =>
section.Id === id ? { ...section, Name: name } : section
)
);
}
const ingredientChangeHandler = (id: string, name: "Amount" | "Unit" | "Name", value: string) => {
setIngredients(prev =>
prev.map(ing =>
ing.Id === id ? { ...ing, [name]: name === "Amount" ? Number(value) : value } : ing
)
);
}
const setSectionIngredients = (sectionId: string, new_ingredients: RecipeIngredient[]) => {
const sorted = [
...new_ingredients.filter(x => x.SectionId === sectionId),
...ingredients.filter(x => x.SectionId !== sectionId)
].sort((a, b) => a.SectionId.localeCompare(b.SectionId));
setIngredients(sorted);
}
const addIngredientHandler = (sectionId: string) => {
const new_ingredients = [...ingredients, {
Id: crypto.randomUUID(),
SectionId: sectionId,
Amount: 0,
Name: "",
Unit: "" as RecipeIngredientUnit
}];
// TODO: Should I be using spread?
setIngredients([...new_ingredients.sort((a, b) => a.SectionId.localeCompare(b.SectionId))]);
}
const removeIngredientHandler = (id: string) => {
setIngredients(prev => prev.filter(ing => ing.Id !== id));
}
const addIngredientSectionHandler = (i: number) => {
const id = crypto.randomUUID();
setSections(prev => [
...prev.slice(0, i + 1),
{ Id: id, Name: "Unnamed group" },
...prev.slice(i + 1),
]);
setIngredients([...ingredients, {
Id: crypto.randomUUID(),
SectionId: id,
Amount: 0,
Name: "",
Unit: "" as RecipeIngredientUnit,
}]);
}
const removeIngredientSectionHandler = (id: string) => {
setSections(prev => prev.filter(sec => sec.Id !== id));
setIngredients(prev => prev.filter(ing => ing.SectionId !== id));
}
// EFFECTS // EFFECTS
useEffect(() => { useEffect(() => {
// Execute validation every time inputs change // Execute validation every time inputs change
validate(); validate();
console.log("@inputs", inputs); }, [inputs, instructions, ingredients]);
}, [inputs, instructions]);
// useEffect(() => {
// console.log("@validation", validation);
// }, [validation]);
useEffect(() => {
console.log("@instructions", instructions);
}, [instructions]);
useEffect(() => { useEffect(() => {
// The form is only valid when every item has been touched, and every item is valid! // The form is only valid when every item has been touched, and every item is valid!
@ -448,32 +477,49 @@ export default function Create() {
Ingredients Ingredients
<span className="text-red-500">*</span> <span className="text-red-500">*</span>
</label> </label>
<p className="text-xs py-1 text-gray-700">Please provide a list of ingredients and their quantities.</p> <p className="text-xs py-1 text-gray-700">
Please provide a list of ingredients and their quantities. Ingredients can be added into
groups. If only a single group exists, the group will be ignored when the recipe is created
and the ingredients will appear as a single list.
</p>
<Reorder.Group <Reorder.Group
axis="y" axis="y"
values={sections} values={sections}
onReorder={setSections} onReorder={setSections}
className="" className="animate-none"
> >
{sections.map((section, i) => { {sections.map((section, i) => (
const controls = useDragControls(); <IngredientSection
key={section.Id}
section={section}
onChange={sectionChangeHandler}
removeIngredientSectionHandler={removeIngredientSectionHandler}
allowDelete={sections.length > 1}
>
return ( <IngredientList
<Reorder.Item classes={INPUT_CLASSES}
key={section.Id} section={section}
value={section} ingredients={ingredients}
dragListener={false} setSectionIngredients={setSectionIngredients}
dragControls={controls} ingredientChangeHandler={ingredientChangeHandler}
className="select-none" removeIngredientHandler={removeIngredientHandler}
/>
<button
onClick={() => addIngredientHandler(section.Id)}
className="w-fit px-3 py-1.5 text-blue-800 font-semibold text-xs md:text-sm rounded-lg hover:bg-gray-100 duration-300 cursor-pointer"
> >
<IngredientSection key={section.Id} section={section} onChange={sectionChangeHandler} index={i} controls={controls} /> Add ingredient
{ingredients.filter(x => x.SectionId === section.Id).map(ing => </button>
<IngredientItem key={ing.Id} ingredient={ing} onChange={ingredientChangeHandler} /> <button
)} onClick={() => addIngredientSectionHandler(i)}
</Reorder.Item> className="w-fit px-3 py-1.5 text-blue-800 font-semibold text-xs md:text-sm rounded-lg hover:bg-gray-100 duration-300 cursor-pointer"
) >
})} Add group header
</button>
</IngredientSection>
))}
</Reorder.Group> </Reorder.Group>
</div> </div>
@ -492,7 +538,7 @@ export default function Create() {
<button <button
onClick={addInstructionHandler} onClick={addInstructionHandler}
className="text-sm md:text-base text-white bg-blue-500 w-full md:w-fit px-8 py-2.5 rounded-lg cursor-pointer" className="w-fit px-3 py-1.5 text-blue-800 font-semibold text-xs md:text-sm rounded-lg hover:bg-gray-100 duration-300 cursor-pointer"
> >
Add Instruction Step Add Instruction Step
</button> </button>