2023-07-30 19:40:39 +02:00
|
|
|
import { Signal } from "@preact/signals";
|
|
|
|
import type {
|
|
|
|
Ingredient,
|
|
|
|
IngredientGroup,
|
|
|
|
Ingredients,
|
|
|
|
} from "../lib/recipes.ts";
|
|
|
|
import { FunctionalComponent } from "preact";
|
|
|
|
|
2023-08-04 23:36:35 +02:00
|
|
|
function numberToString(num: number) {
|
|
|
|
return (Math.floor(num * 4) / 4).toString();
|
|
|
|
}
|
2023-07-30 19:40:39 +02:00
|
|
|
|
|
|
|
const Ingredient = (
|
|
|
|
{ ingredient, amount, key = "", portion = 1 }: {
|
|
|
|
ingredient: Ingredient;
|
|
|
|
amount: Signal<number>;
|
|
|
|
key?: string | number;
|
|
|
|
portion?: number;
|
|
|
|
},
|
|
|
|
) => {
|
|
|
|
const { type, amount: _amount, unit } = ingredient;
|
|
|
|
|
|
|
|
const finalAmount = (typeof _amount === "number" && amount)
|
|
|
|
? (_amount / portion) * (amount?.value || 1)
|
|
|
|
: "";
|
|
|
|
|
|
|
|
return (
|
|
|
|
<tr key={key}>
|
|
|
|
<td class="pr-4 py-2">
|
2023-08-04 23:36:35 +02:00
|
|
|
{numberToString(finalAmount || 0) +
|
|
|
|
(typeof unit === "string" ? unit : "")}
|
2023-07-30 19:40:39 +02:00
|
|
|
</td>
|
|
|
|
<td class="px-4 py-2">{type}</td>
|
|
|
|
</tr>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export const IngredientsList: FunctionalComponent<
|
|
|
|
{ ingredients: Ingredients; amount: Signal<number>; portion?: number }
|
|
|
|
> = (
|
|
|
|
{ ingredients, amount, portion },
|
|
|
|
) => {
|
|
|
|
return (
|
|
|
|
<table class="w-full border-collapse table-auto">
|
|
|
|
<tbody>
|
|
|
|
{ingredients.map((item, index) => {
|
|
|
|
if ("name" in item) {
|
|
|
|
// Render IngredientGroup
|
|
|
|
const { name, ingredients: groupIngredients } =
|
|
|
|
item as IngredientGroup;
|
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<tr key={index}>
|
|
|
|
<td colSpan={3} class="pr-4 py-2 font-italic">{name}</td>
|
|
|
|
</tr>
|
|
|
|
{groupIngredients.map((item, index) => {
|
|
|
|
// Render Ingredient
|
|
|
|
return (
|
|
|
|
<Ingredient
|
|
|
|
key={index}
|
|
|
|
ingredient={item}
|
|
|
|
amount={amount}
|
|
|
|
portion={portion}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
})}
|
|
|
|
</>
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
return (
|
|
|
|
<Ingredient ingredient={item} amount={amount} portion={portion} />
|
|
|
|
);
|
|
|
|
}
|
|
|
|
})}
|
|
|
|
</tbody>
|
|
|
|
</table>
|
|
|
|
);
|
|
|
|
};
|