feat(recipe): add step quantities and appliance settings
Release Drafter / auto_label (push) Skipped
Release Drafter / draft_release (push) Canceled after 0s
CodeQL / Analyze (javascript-typescript) (push) Canceled after 0s
CodeQL / Analyze (python) (push) Canceled after 0s
Backend Lint and Test / tests (sqlite) (push) Canceled after 0s
Backend Lint and Test / tests (postgres) (push) Canceled after 0s
Docker Nightly Production / Backend Server Tests (push) Canceled after 0s
Frontend Lint and Test / lint (push) Canceled after 0s
Docker Nightly Production / Frontend Tests (push) Canceled after 0s
Build Package / Build frontend and wheel (push) Canceled after 0s
Docker Nightly Production / Build Package (push) Canceled after 0s
Docker Nightly Production / Build E2E Image Cache (push) Canceled after 0s
Docker Nightly Production / Build Tagged Release (push) Canceled after 0s
Docker Nightly Production / Notify Discord (push) Canceled after 0s

This commit is contained in:
jfmcarreira committed 2026-12-01 13:05:50 +00:00
1 parent 1dd63a070b
commit 8dad430650
51 files changed
+2775 -77

No files matched your search

@@ -17,14 +17,15 @@ import { useIngredientTextParser } from "~/composables/recipes";
interface Props {
ingredient?: RecipeIngredient;
scale?: number;
showZero?: boolean;
}
const { ingredient, scale = 1 } = defineProps<Props>();
const { ingredient, scale = 1, showZero = false } = defineProps<Props>();
const { useParsedIngredientText } = useIngredientTextParser();
const baseText = computed(() => {
if (!ingredient) return "";
const parsed = useParsedIngredientText(ingredient, scale);
const parsed = useParsedIngredientText(ingredient, scale, true, undefined, showZero);
return [parsed.quantity, parsed.unit, parsed.name].filter(Boolean).join(" ").trim();
});
</script>
@@ -45,10 +45,12 @@ interface Props {
// off by default: the shopping list and the add-to-list dialog reuse this row, and a menu
// button is noise in both. the recipe renderer opts in
showSubstitutions?: boolean;
showZero?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
scale: 1,
showSubstitutions: false,
showZero: false,
});
const route = useRoute();
const auth = useMealieAuth();
@@ -56,7 +58,7 @@ const groupSlug = computed(() => route.params.groupSlug || auth.user?.value?.gro
const { useParsedIngredientText } = useIngredientTextParser();
const parsedIng = computed(() => {
return useParsedIngredientText(props.ingredient, props.scale, true, groupSlug.value.toString());
return useParsedIngredientText(props.ingredient, props.scale, true, groupSlug.value.toString(), props.showZero);
});
</script>
@@ -98,4 +98,17 @@ describe("RecipeIngredients", () => {
const labels = wrapper.findAll("input[type='checkbox']").map(input => input.attributes("aria-label"));
expect(labels).toEqual(["2 cups flour", "salt to taste"]);
});
test("tracks separate portions independently while keeping legacy references shared", async () => {
const first = mountIngredients([ingredients.curryPaste]);
await first.setProps({ portionKey: "step-a", portionReferenceIds: [ingredients.curryPaste.referenceId] });
await first.find(".checkbox").trigger("click");
const second = mountIngredients([ingredients.curryPaste]);
await second.setProps({ portionKey: "step-b", portionReferenceIds: [ingredients.curryPaste.referenceId] });
expect(second.find(".checkbox").attributes("aria-pressed")).toBe("false");
first.unmount();
const restored = mountIngredients([ingredients.curryPaste]);
await restored.setProps({ portionKey: "step-a", portionReferenceIds: [ingredients.curryPaste.referenceId] });
expect(restored.find(".checkbox").attributes("aria-pressed")).toBe("true");
});
});
@@ -32,7 +32,7 @@
<template #prepend>
<v-checkbox
:model-value="isChecked(index)"
:aria-label="parseIngredientText(ingredient, scale, false)"
:aria-label="parseIngredientText(ingredient, scale, false, isExplicitZero(ingredient))"
hide-details
class="pt-0 mt-0"
color="secondary"
@@ -45,6 +45,7 @@
<RecipeIngredientListItem
:ingredient="ingredient"
:scale="scale"
:show-zero="isExplicitZero(ingredient)"
show-substitutions
/>
</v-list-item-title>
@@ -65,16 +66,28 @@ interface Props {
scale?: number;
isCookMode?: boolean;
storageKey?: string;
portionKey?: string;
portionReferenceIds?: string[];
portionAllocationIds?: (string | null)[];
zeroPortionReferenceIds?: string[];
}
const props = withDefaults(defineProps<Props>(), {
value: () => [],
scale: 1,
isCookMode: false,
storageKey: undefined,
portionKey: undefined,
portionReferenceIds: () => [],
portionAllocationIds: () => [],
zeroPortionReferenceIds: () => [],
});
const { parseIngredientText } = useIngredientTextParser();
function isExplicitZero(ingredient: RecipeIngredient) {
return !!ingredient.referenceId && props.zeroPortionReferenceIds.includes(ingredient.referenceId);
}
function validateTitle(title?: string | null) {
return !(title === undefined || title === "" || title === null);
}
@@ -111,8 +124,13 @@ function checkedState() {
}
function checkedKey(index: number) {
const allocationId = props.portionAllocationIds[index];
if (props.portionKey && allocationId) return `allocation:${allocationId}`;
const referenceId = props.value[index]?.referenceId;
return referenceId ? `ref:${referenceId}` : `idx:${index}`;
const key = referenceId ? `ref:${referenceId}` : `idx:${index}`;
return props.portionKey && referenceId && props.portionReferenceIds.includes(referenceId)
? `step:${props.portionKey}:${key}`
: key;
}
function isChecked(index: number) {
@@ -95,7 +95,7 @@
<RecipePageInstructions
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -121,7 +121,7 @@
v-model="recipe"
class="px-1 my-4 d-print-none"
/>
<RecipePrintContainer :recipe="displayedRecipe" :scale="scale" />
<RecipePrintContainer :recipe="displayedRecipe" :source-ingredients="recipe.recipeIngredient" :scale="scale" />
</v-container>
<!-- Floating save button when toolbar scrolls out of view -->
<v-fab
@@ -176,7 +176,7 @@
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
class="overflow-y-hidden px-4"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -191,7 +191,7 @@
v-model="recipe.recipeInstructions"
v-model:assets="recipe.assets"
class="overflow-y-hidden mt-n5 px-2 px-md-4"
:recipe="displayedRecipe"
:recipe="recipe"
:scale="scale"
:ingredient-storage-key="ingredientStorageKey"
/>
@@ -18,7 +18,7 @@ function editor(value: number | null = null) {
describe("instruction duration in minutes with seconds storage", () => {
it("always shows a blank optional input without emitting a duration", () => {
const wrapper = editor();
expect(wrapper.findAll("input")).toHaveLength(1);
expect(wrapper.findAll("input")).toHaveLength(2);
expect(wrapper.find("input").element.value).toBe("");
expect(wrapper.find("input").attributes("placeholder")).toBe("Minutes");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
@@ -60,7 +60,13 @@ describe("instruction duration in minutes with seconds storage", () => {
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([120]);
wrapper.unmount();
});
it.each([[3661, "1h 1m 1s"], [90, "1m 30s"], [60, "1m"], [30, "30s"], [null, ""]] as const)("displays %s with units", async (value, text) => {
it("allows an exact fractional-second duration", async () => {
const wrapper = editor();
await wrapper.findAll("input")[1]!.setValue("0.5");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([0.5]);
wrapper.unmount();
});
it.each([[3661, "1h 1m 1s"], [90, "1m 30s"], [61.001, "1m 1.001s"], [0.5, "0.5s"], [60, "1m"], [30, "30s"], [null, ""]] as const)("displays %s with units", async (value, text) => {
const wrapper = editor(value);
await wrapper.setProps({ isEditMode: false });
expect(wrapper.text()).toBe(text);
@@ -14,7 +14,24 @@
inset
hide-details="auto"
@update:model-value="updateDuration"
@keypress="e => e.key === '-' && e.preventDefault()"
@keypress="(e: KeyboardEvent) => e.key === '-' && e.preventDefault()"
@click.stop
/>
<v-number-input
v-if="isEditMode"
:model-value="modelValue ?? null"
class="step-duration"
:min="0"
:max="2147483647"
:step="0.001"
:precision="3"
:label="$t('recipe.step-duration-seconds')"
density="compact"
inset
clearable
hide-details="auto"
@update:model-value="emit('update:modelValue', $event || null)"
@keypress="(e: KeyboardEvent) => e.key === '-' && e.preventDefault()"
@click.stop
/>
<span v-else-if="modelValue" class="text-body-2">
@@ -60,7 +77,7 @@ const formattedDuration = computed(() => {
const seconds = props.modelValue ?? 0;
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainder = seconds % 60;
const remainder = (Math.round(seconds * 1000) % 60000) / 1000;
return [
hours ? t("recipe.step-duration-value-hours", { hours }) : "",
minutes ? t("recipe.step-duration-value-minutes", { minutes }) : "",
@@ -0,0 +1,68 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test, vi } from "vitest";
import { ref } from "vue";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipePageInstructions from "./RecipePageInstructions.vue";
import { makeRecipe } from "~/tests/factories";
vi.mock("vue-draggable-plus", () => ({
VueDraggable: { template: "<div><slot /></div>" },
}));
vi.mock("~/composables/api", () => ({
useUserApi: () => ({}),
useStaticRoutes: () => ({ recipeAssetPath: () => "" }),
}));
vi.mock("~/composables/recipe-page/shared-state", () => ({
usePageState: () => ({ isCookMode: ref(false), isEditForm: ref(true), toggleCookMode: () => {} }),
}));
vi.mock("~/composables/recipe-page/use-extract-ingredient-references", () => ({
useExtractIngredientReferences: () => ({ extractIngredientReferences: () => [] }),
}));
vi.mock("~/composables/use-locales", () => ({
useLocales: () => ({ locales: [{ value: "en-US" }], locale: { value: "en-US" } }),
}));
describe("RecipePageInstructions", () => {
test("edits fractional ingredient portions without rounding on blur", async () => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "ingredient", quantity: 2, food: { name: "flour" } }],
recipeInstructions: [{ id: "step", text: "Mix", ingredientReferences: [{ referenceId: "ingredient", quantity: 0.5 }] }],
});
const wrapper = mount(RecipePageInstructions, {
props: { recipe, modelValue: recipe.recipeInstructions, assets: [] },
global: {
plugins: [createVuetify({ components, directives })],
mocks: { $globals: { icons: {} } },
stubs: {
BaseDialog: true,
BaseButton: true,
BaseButtonGroup: true,
DropZone: { template: "<div><slot /></div>" },
MarkdownEditor: true,
RecipeStepCooking: true,
},
},
});
const field = wrapper.findComponent(components.VNumberInput);
expect(field.props("precision")).toBeNull();
const input = field.find("input");
expect(input.element.value).toBe("0.5");
await input.trigger("focus");
await input.setValue("1.");
input.element.setSelectionRange(2, 2);
const decimalDigit = new InputEvent("beforeinput", {
bubbles: true,
cancelable: true,
inputType: "insertText",
data: "2",
});
expect(input.element.dispatchEvent(decimalDigit)).toBe(true);
await input.setValue("1.25");
await input.trigger("blur");
expect(recipe.recipeInstructions[0].ingredientReferences?.[0].quantity).toBe(1.25);
expect(input.element.value).toBe("1.25");
});
});
@@ -415,7 +415,7 @@
>
<div
v-for="(linkRef, i) in step.ingredientReferences"
:key="linkRef.referenceId ?? i"
:key="linkRef.allocationId ?? linkRef.referenceId ?? i"
class="mb-1"
>
<RecipeIngredientHtml
@@ -423,6 +423,13 @@
:ingredient="ingredientLookup[linkRef.referenceId]"
:scale="scale"
/>
<RecipeStepAllocationEditor :model-value="linkRef" @update:model-value="Object.assign(linkRef, $event)" />
<div v-if="linkRef.referenceId && overallocatedIds.has(linkRef.referenceId)" class="text-warning text-body-2">
{{ $t('recipe.step-quantity-exceeds') }}
</div>
<div v-if="linkRef.quantityKind === 'remaining' && linkRef.referenceId && unresolvedRemainingIds.has(linkRef.referenceId)" class="text-warning text-body-2">
{{ $t('recipe.step-remaining-unknown') }}
</div>
</div>
</div>
<div
@@ -445,6 +452,7 @@
:is-edit-mode="isEditForm"
@update:model-value="step.durationSeconds = $event"
/>
<RecipeStepCooking v-model="step.cooking" :ingredients="recipe.recipeIngredient" edit @link-ingredient="linkReviewIngredient(step, $event)" />
</v-card-text>
</DropZone>
@@ -465,13 +473,14 @@
class="ml-n4"
>
<RecipeIngredients
:value="recipe.recipeIngredient.filter((ing) => {
if (!step.ingredientReferences) return false
return step.ingredientReferences.map((ref) => ref.referenceId).includes(ing.referenceId || '')
})"
:value="displayStepIngredients(step)"
:scale="scale"
:is-cook-mode="isCookMode"
:storage-key="ingredientStorageKey"
:portion-key="step.id ?? undefined"
:portion-reference-ids="portionReferenceIds"
:portion-allocation-ids="stepAllocationIds(step)"
:zero-portion-reference-ids="zeroPortionIds(step)"
/>
</div>
<v-divider
@@ -503,6 +512,17 @@
class="markdown"
:source="step.text"
/>
<div v-if="!isCookMode && hasLinkedIngredients(step)" class="mt-2">
<RecipeIngredientHtml
v-for="(ingredient, i) in displayStepIngredients(step)"
:key="ingredient.referenceId ?? i"
:ingredient="ingredient"
:scale="scale"
:show-zero="!!ingredient.referenceId && zeroPortionIds(step).includes(ingredient.referenceId)"
/>
</div>
<RecipeStepCooking :model-value="step.cooking" />
<RecipeStepAllocationSummary :references="step.ingredientReferences" :ingredients="recipe.recipeIngredient" :scale="scale" />
</v-col>
</v-row>
</v-card-text>
@@ -532,6 +552,12 @@ import DropZone from "~/components/global/DropZone.vue";
import { alert } from "~/composables/use-toast";
import RecipeIngredients from "~/components/Domain/Recipe/RecipeIngredients.vue";
import RecipeIngredientHtml from "~/components/Domain/Recipe/RecipeIngredientHtml.vue";
import RecipeStepCooking from "~/components/Domain/Recipe/RecipeStepCooking.vue";
import RecipeStepAllocationEditor from "~/components/Domain/Recipe/RecipeStepAllocationEditor.vue";
import RecipeStepAllocationSummary from "~/components/Domain/Recipe/RecipeStepAllocationSummary.vue";
import { overallocatedIngredientIds, stepIngredients, unresolvedRemainingIngredientIds } from "~/lib/recipe/step-ingredients";
import { useUnitConversion } from "~/composables/recipes/use-unit-conversion";
import { useUnitSystem } from "~/composables/recipes/use-unit-system";
import { mergeSteps, undoStepMerge, type StepMerge } from "~/lib/recipe/instruction-merge";
import CookTime from "./CookTime.vue";
@@ -556,8 +582,33 @@ const props = defineProps({
const emit = defineEmits(["click-instruction-field", "update:assets"]);
const i18n = useI18n();
function linkReviewIngredient(step: RecipeStep, referenceId: string) {
step.ingredientReferences ??= [];
if (!step.ingredientReferences.some(ref => ref.referenceId === referenceId)) {
step.ingredientReferences.push({ allocationId: uuid4(), referenceId, quantityKind: "unknown", quantity: 0 });
}
}
const { isCookMode, toggleCookMode, isEditForm } = usePageState(props.recipe.slug);
const { extractIngredientReferences } = useExtractIngredientReferences();
const { convertIngredient } = useUnitConversion();
const { unitSystem } = useUnitSystem();
function displayStepIngredients(step: RecipeStep) {
const ingredients = stepIngredients(step, props.recipe.recipeIngredient, instructionList.value);
return unitSystem.value ? ingredients.map(ingredient => convertIngredient(ingredient, unitSystem.value!, props.scale)) : ingredients;
}
function zeroPortionIds(step: RecipeStep): string[] {
return (step.ingredientReferences ?? [])
.filter(ref => ref.quantity === 0 && (!ref.quantityKind || ref.quantityKind === "partial") && ref.referenceId)
.map(ref => ref.referenceId!);
}
function stepAllocationIds(step: RecipeStep): (string | null)[] {
return (step.ingredientReferences ?? [])
.filter(ref => ref.referenceId && props.recipe.recipeIngredient.some(ingredient => ingredient.referenceId === ref.referenceId))
.map(ref => ref.quantityKind || ref.quantity != null ? ref.allocationId ?? null : null);
}
const dialog = ref(false);
const disabledSteps = ref<number[]>([]);
@@ -678,6 +729,11 @@ const activeNoteReferenceIds = ref<string[]>([]);
const activeText = ref("");
const linkedNotesSheetOpen = ref(false);
const activeStepLinkedNotes = ref<RecipeNote[]>([]);
const overallocatedIds = computed(() => overallocatedIngredientIds(instructionList.value, props.recipe.recipeIngredient));
const unresolvedRemainingIds = computed(() => unresolvedRemainingIngredientIds(instructionList.value, props.recipe.recipeIngredient));
const portionReferenceIds = computed(() => [...new Set(instructionList.value.flatMap(step =>
(step.ingredientReferences ?? []).filter(ref => (ref.quantityKind || ref.quantity != null) && ref.referenceId).map(ref => ref.referenceId!),
))]);
const availableDialogNextStep = computed(() => activeLinkerIndex.value < instructionList.value.length - 1);
const activeDialogStepText = computed(() => activeText.value);
@@ -722,7 +778,7 @@ function saveDialogLinks() {
}
step.ingredientReferences = activeRefs.value.map((referenceId) => {
return { referenceId };
return step.ingredientReferences?.find(ref => ref.referenceId === referenceId) ?? { referenceId };
});
step.noteReferences = activeNoteReferenceIds.value.map((referenceId) => {
@@ -891,6 +947,9 @@ function mergeAbove(target: number, source: number) {
if (merge) {
mergeHistory.value.push(merge);
}
else if (target >= 0) {
alert.error(i18n.t("recipe.step-merge-conflict"));
}
}
function undoMerge(event: KeyboardEvent) {
@@ -2,6 +2,7 @@
<div class="print-container">
<RecipePrintView
:recipe="recipe"
:source-ingredients="sourceIngredients"
:scale="scale"
:density="'compact'"
/>
@@ -10,11 +11,12 @@
<script setup lang="ts">
import RecipePrintView from "~/components/Domain/Recipe/RecipePrintView.vue";
import type { RecipeOut } from "~/lib/api/types/recipe";
import type { RecipeIngredient, RecipeOut } from "~/lib/api/types/recipe";
interface Props {
recipe: RecipeOut;
scale?: number;
sourceIngredients?: RecipeIngredient[];
}
withDefaults(defineProps<Props>(), {
@@ -0,0 +1,76 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test, vi } from "vitest";
import RecipePrintView from "./RecipePrintView.vue";
import { makeRecipe } from "~/tests/factories";
vi.mock("~/composables/api", () => ({
useStaticRoutes: () => ({ recipeImage: () => "" }),
}));
vi.mock("~/composables/use-locales", () => ({
useLocales: () => ({ locales: [{ value: "en-US" }], locale: { value: "en-US" } }),
}));
describe("RecipePrintView", () => {
test.each([true, false])("renders settings with their step and only labels reverse rotation: %s", (reverse) => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "ingredient", quantity: 100, food: { name: "flour" } }],
recipeInstructions: [
{ text: "Mix", durationSeconds: 180, cooking: { temperatureCelsius: 120, speed: "spoon", reverse } },
{ text: "Rest" },
],
});
const wrapper = mount(RecipePrintView, {
props: { recipe },
global: {
mocks: { $globals: { icons: { primary: "", potSteam: "" } } },
stubs: {
SafeMarkdown: { props: ["source"], template: "<div>{{ source }}</div>" },
SafeInlineHtml: { props: ["html"], template: "<span>{{ html }}</span>" },
RecipeTimeCard: true,
},
},
});
expect(wrapper.find(".ingredient-cell").text()).toContain("flour");
expect(wrapper.find(".ingredient-cell").text()).not.toContain("120");
const steps = wrapper.findAll(".recipe-step-body");
expect(steps).toHaveLength(2);
expect(steps[0].element.parentElement?.textContent).toContain("120 °C");
expect(steps[0].element.parentElement?.textContent?.includes("Reverse rotation")).toBe(reverse);
expect(wrapper.text()).not.toContain("Forward rotation");
expect(steps[0].element.parentElement?.textContent).toContain("3m");
expect(steps[1].element.parentElement?.textContent).not.toContain("120 °C");
expect(steps[1].element.parentElement?.textContent).not.toContain("Reverse rotation");
});
test("prints fractional pulses, ranges, accessories and allocation intent without scaling operation settings", () => {
const recipe = makeRecipe({
recipeIngredient: [{ referenceId: "flour", quantity: 100, food: { name: "flour" } }],
recipeInstructions: [{
text: "Check consistency", durationSeconds: 0.5,
ingredientReferences: [{ referenceId: "flour", quantityKind: "unknown", quantity: 0, weighing: "manual", destination: "bowl" }],
cooking: {
durationRangeSeconds: { minimum: 0.5, maximum: 2 },
speedProgression: [1, 3, 5], accessories: [{ name: "lid", state: "open" }],
optional: true, condition: "If too coarse", repetitions: 3,
modeParameters: [{ name: "thickness", kind: "text", value: "coarse" }],
},
}],
});
const wrapper = mount(RecipePrintView, {
props: { recipe, scale: 2 },
global: {
mocks: { $globals: { icons: { primary: "", potSteam: "" } } },
stubs: { SafeMarkdown: true, SafeInlineHtml: true, RecipeTimeCard: true },
},
});
expect(wrapper.text()).toContain("0.5s");
expect(wrapper.text()).toContain("0.5–2 s");
expect(wrapper.text()).toContain("1 → 3 → 5");
expect(wrapper.text()).toContain("lid: Open");
expect(wrapper.text()).toContain("Unknown amount");
expect(wrapper.text()).toContain("If too coarse");
expect(recipe.recipeIngredient[0]!.quantity).toBe(100);
expect(recipe.recipeInstructions[0]!.ingredientReferences![0]!.quantity).toBe(0);
});
});
@@ -136,6 +136,9 @@
:source="step.text"
class="recipe-step-body"
/>
<CookTime :model-value="step.durationSeconds" :is-edit-mode="false" />
<RecipeStepCooking :model-value="step.cooking" />
<RecipeStepAllocationSummary :references="step.ingredientReferences" :ingredients="sourceIngredients ?? recipe.recipeIngredient" :scale="scale" />
<!-- Step Ingredients -->
<div
v-if="preferences.showLinkedIngredients && step.ingredientReferences && step.ingredientReferences.length > 0"
@@ -155,7 +158,7 @@
:key="`ingredient-${ingredientIndex}`"
>
<p class="ingredient-body">
<SafeInlineHtml :html="parseText(ingredient)" />
<SafeInlineHtml :html="parseText(ingredient, step.ingredientReferences?.some(ref => ref.referenceId === ingredient.referenceId && ref.quantity === 0 && (!ref.quantityKind || ref.quantityKind === 'partial')))" />
</p>
</template>
</div>
@@ -224,6 +227,12 @@ import { ImagePosition, useUserPrintPreferences } from "~/composables/use-users/
import { ingredientSubstitutionSummary, useFoodPlurality, useIngredientTextParser, useNutritionLabels } from "~/composables/recipes";
import { usePageState } from "~/composables/recipe-page/shared-state";
import { useScaledAmount } from "~/composables/recipes/use-scaled-amount";
import CookTime from "~/components/Domain/Recipe/RecipePage/RecipePageParts/CookTime.vue";
import RecipeStepCooking from "~/components/Domain/Recipe/RecipeStepCooking.vue";
import RecipeStepAllocationSummary from "~/components/Domain/Recipe/RecipeStepAllocationSummary.vue";
import { stepIngredients } from "~/lib/recipe/step-ingredients";
import { useUnitConversion } from "~/composables/recipes/use-unit-conversion";
import { useUnitSystem } from "~/composables/recipes/use-unit-system";
type IngredientSection = {
sectionName: string;
@@ -240,6 +249,7 @@ interface Props {
recipe: RecipeOut;
scale?: number;
dense?: boolean;
sourceIngredients?: RecipeIngredient[];
}
const props = withDefaults(defineProps<Props>(), {
scale: 1,
@@ -251,6 +261,8 @@ const preferences = useUserPrintPreferences();
const { recipeImage } = useStaticRoutes();
const { imageKey } = usePageState(props.recipe.slug);
const { labels } = useNutritionLabels();
const { convertIngredient } = useUnitConversion();
const { unitSystem } = useUnitSystem();
const servingsDisplay = computed(() => {
const { scaledAmountDisplay } = useScaledAmount(props.recipe.recipeYieldQuantity, props.scale);
@@ -395,11 +407,10 @@ const stepLinkedIngredients = computed(() => {
return;
}
const referenceIds = new Set(step.ingredientReferences.map(ref => ref.referenceId));
map.set(
`${sectionIndex}-${stepIndex}`,
props.recipe.recipeIngredient.filter(ing => ing.referenceId && referenceIds.has(ing.referenceId)),
);
const ingredients = stepIngredients(step, props.sourceIngredients ?? props.recipe.recipeIngredient, props.recipe.recipeInstructions);
map.set(`${sectionIndex}-${stepIndex}`, props.sourceIngredients && unitSystem.value
? ingredients.map(ingredient => convertIngredient(ingredient, unitSystem.value!, props.scale))
: ingredients);
});
});
@@ -408,8 +419,8 @@ const stepLinkedIngredients = computed(() => {
const { parseIngredientText } = useIngredientTextParser();
function parseText(ingredient: RecipeIngredient) {
return parseIngredientText(ingredient, props.scale);
function parseText(ingredient: RecipeIngredient, showZero = false) {
return parseIngredientText(ingredient, props.scale, true, showZero);
}
const { shouldPluralizeFood } = useFoodPlurality();
@@ -0,0 +1,49 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test } from "vitest";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipeStepAllocationEditor from "./RecipeStepAllocationEditor.vue";
describe("allocation intent editor", () => {
test("does not change legacy quantities on mount and never infers scale activation", () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { referenceId: "flour", quantity: null } },
global: { plugins: [createVuetify({ components, directives })] },
});
expect(wrapper.findComponent(components.VSelect).props("modelValue")).toBe("full");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
});
test("selects unknown safely and retains the association identity", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { allocationId: "allocation", referenceId: "flour", quantity: 20, weighing: "weigh" } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VSelect).vm.$emit("update:modelValue", "unknown");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{
allocationId: "allocation", referenceId: "flour", quantity: 0, quantityKind: "unknown", weighing: "unspecified",
}]);
});
test("edits partial portions and weighing independently", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { allocationId: "allocation", referenceId: "flour", quantityKind: "partial", quantity: 0 } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VNumberInput).vm.$emit("update:modelValue", 0.5);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantity: 0.5, quantityKind: "partial" });
const weighing = wrapper.findAllComponents(components.VSelect)[1]!;
await weighing.vm.$emit("update:modelValue", "manual");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantity: 0, weighing: "manual" });
});
test("requires a portion to be entered when an unknown amount is changed to partial", async () => {
const wrapper = mount(RecipeStepAllocationEditor, {
props: { modelValue: { referenceId: "flour", quantityKind: "unknown", quantity: 0 } },
global: { plugins: [createVuetify({ components, directives })] },
});
await wrapper.findComponent(components.VSelect).vm.$emit("update:modelValue", "partial");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ quantityKind: "partial", quantity: null });
});
});
@@ -0,0 +1,72 @@
<template>
<div @click.stop>
<v-select :model-value="kind" :items="allocationOptions" :label="$t('recipe.allocation-kind')" density="compact" @update:model-value="setKind" />
<v-number-input
v-if="kind === 'partial'"
:model-value="modelValue.quantity"
:label="$t('recipe.step-quantity')"
:min="0"
:precision="null"
density="compact"
clearable
@update:model-value="update('quantity', $event)"
/>
<v-select :model-value="modelValue.weighing ?? 'unspecified'" :items="weighingOptions" :label="$t('recipe.weighing-intent')" density="compact" @update:model-value="update('weighing', $event)" />
<v-text-field :model-value="modelValue.role" :label="$t('recipe.allocation-role')" clearable density="compact" @update:model-value="update('role', $event || null)" />
<v-text-field :model-value="modelValue.destination" :label="$t('recipe.allocation-destination')" clearable density="compact" @update:model-value="update('destination', $event || null)" />
<v-number-input
:model-value="modelValue.quantityMinimum"
:label="$t('recipe.allocation-minimum')"
:min="0"
:precision="null"
clearable
density="compact"
@update:model-value="update('quantityMinimum', $event)"
/>
<v-number-input
:model-value="modelValue.quantityMaximum"
:label="$t('recipe.allocation-maximum')"
:min="0"
:precision="null"
clearable
density="compact"
@update:model-value="update('quantityMaximum', $event)"
/>
<v-number-input
:model-value="modelValue.containerCount"
:label="$t('recipe.allocation-containers')"
:min="1"
:precision="0"
clearable
density="compact"
@update:model-value="update('containerCount', $event)"
/>
<v-checkbox :model-value="modelValue.approximate ?? false" :label="$t('recipe.allocation-approximate')" density="compact" @update:model-value="update('approximate', $event)" />
<v-text-field :model-value="modelValue.sourceText" :label="$t('recipe.allocation-source')" clearable density="compact" @update:model-value="update('sourceText', $event || null)" />
</div>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { useI18n } from "vue-i18n";
import type { IngredientReferences } from "~/lib/api/types/recipe";
const props = defineProps<{ modelValue: IngredientReferences }>();
const emit = defineEmits<{ "update:modelValue": [value: IngredientReferences] }>();
const { t } = useI18n();
const kind = computed(() => props.modelValue.quantityKind ?? (props.modelValue.quantity == null ? "full" : "partial"));
const kinds = ["full", "partial", "remaining", "unknown", "prepared", "asNeeded", "referenceOnly"] as const;
const allocationOptions = computed(() => kinds.map(value => ({ title: t(`recipe.allocation-${value}`), value })));
const weighingOptions = computed(() => ["unspecified", "manual", ...(kind.value === "full" || kind.value === "partial" ? ["weigh"] : [])].map(value => ({ title: t(`recipe.weighing-${value}`), value })));
function update<K extends keyof IngredientReferences>(key: K, value: IngredientReferences[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function setKind(value: NonNullable<IngredientReferences["quantityKind"]>) {
emit("update:modelValue", {
...props.modelValue,
quantityKind: value,
quantity: value === "full" ? null : value === "partial" ? (kind.value === "partial" ? props.modelValue.quantity : null) : 0,
weighing: value === "full" || value === "partial" ? props.modelValue.weighing : "unspecified",
});
}
</script>
@@ -0,0 +1,40 @@
<template>
<div v-for="(reference, index) in references ?? []" :key="reference.allocationId ?? index" class="text-body-2">
<template v-if="reference.quantityKind || reference.weighing || reference.destination || reference.role || reference.sourceText || reference.approximate || reference.containerCount != null || reference.quantityMinimum != null || reference.quantityMaximum != null">
{{ ingredientName(reference.referenceId) }}:
{{ $t(`recipe.allocation-${allocationKind(reference)}`) }}
<template v-if="reference.weighing && reference.weighing !== 'unspecified'">
· {{ $t(`recipe.weighing-${reference.weighing}`) }}
</template>
<template v-if="reference.role">
· {{ reference.role }}
</template>
<template v-if="reference.destination">
· {{ reference.destination }}
</template>
<template v-if="reference.approximate">
· {{ $t("recipe.allocation-approximate") }}
</template>
<template v-if="reference.quantityMinimum != null || reference.quantityMaximum != null">
· {{ reference.quantityMinimum == null ? "?" : reference.quantityMinimum * scale }}–{{ reference.quantityMaximum == null ? "?" : reference.quantityMaximum * scale }}
</template>
<template v-if="reference.containerCount != null">
· ×{{ reference.containerCount }}
</template>
<template v-if="reference.sourceText">
· {{ reference.sourceText }}
</template>
</template>
</div>
</template>
<script setup lang="ts">
import type { IngredientReferences, RecipeIngredient } from "~/lib/api/types/recipe";
import { allocationKind } from "~/lib/recipe/step-ingredients";
const props = withDefaults(defineProps<{ references?: IngredientReferences[]; ingredients: RecipeIngredient[]; scale?: number }>(), { scale: 1 });
function ingredientName(referenceId?: string | null) {
const ingredient = props.ingredients.find(item => item.referenceId === referenceId);
return ingredient?.food?.name || ingredient?.note || "";
}
</script>
@@ -0,0 +1,59 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test } from "vitest";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipeStepCooking from "./RecipeStepCooking.vue";
describe("RecipeStepCooking", () => {
test("displays numeric and named settings", () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { appliance: "thermomix", temperatureCelsius: 120, speed: "spoon", mode: "steaming" } },
});
expect(wrapper.text()).toContain("120 °C");
expect(wrapper.text()).toContain("Speed: spoon");
expect(wrapper.text()).toContain("steaming");
});
test("edits whole degrees without replacing an imported fraction on focus and blur", async () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { temperatureCelsius: 37.5 }, edit: true },
global: { plugins: [createVuetify({ components, directives })] },
});
const field = wrapper.findComponent(components.VNumberInput);
const input = field.find("input");
expect(field.props("precision")).toBe(0);
expect(field.props("step")).toBe(1);
expect(input.element.value).toBe("38");
expect(wrapper.text()).toContain("37.5 °C");
await input.trigger("focus");
await input.trigger("blur");
expect(wrapper.emitted("update:modelValue")).toBeUndefined();
await input.setValue("39");
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ temperatureCelsius: 39 }]);
});
test.each([true, false, null, undefined])("only displays reverse rotation: %s", (reverse) => {
const wrapper = mount(RecipeStepCooking, { props: { modelValue: { speed: 2, reverse } } });
expect(wrapper.text().includes("Reverse rotation")).toBe(reverse === true);
expect(wrapper.text()).not.toContain("Forward rotation");
expect(wrapper.text()).toContain("Speed: 2");
});
test("does not render a settings row for forward rotation alone", () => {
const wrapper = mount(RecipeStepCooking, { props: { modelValue: { reverse: false } } });
expect(wrapper.find(".text-body-2").exists()).toBe(false);
});
test("edits and clears direction while preserving other cooking settings", async () => {
const wrapper = mount(RecipeStepCooking, {
props: { modelValue: { speed: 2, reverse: true }, edit: true },
global: { plugins: [createVuetify({ components, directives })] },
});
const field = wrapper.findComponent(components.VSelect);
await field.vm.$emit("update:modelValue", false);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ speed: 2, reverse: false }]);
await field.vm.$emit("update:modelValue", null);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{ speed: 2, reverse: null }]);
});
});
@@ -0,0 +1,114 @@
<template>
<div v-if="edit" class="mt-3" @click.stop>
<div class="text-subtitle-2">
{{ $t("recipe.step-cooking") }}
</div>
<v-text-field :model-value="modelValue?.appliance" :label="$t('recipe.step-appliance')" clearable density="compact" @update:model-value="update('appliance', $event || null)" />
<v-number-input
:model-value="inputTemperature"
:label="$t('recipe.step-temperature')"
:precision="0"
:step="1"
:hint="fractionalTemperature ? $t('recipe.step-temperature-saved', { temperature: modelValue?.temperatureCelsius }) : undefined"
persistent-hint
hide-details="auto"
density="compact"
control-variant="hidden"
clearable
@update:model-value="updateTemperature"
/>
<v-text-field
:model-value="modelValue?.speed"
:label="$t('recipe.step-speed')"
clearable
density="compact"
@change="updateSpeed(($event.target as HTMLInputElement).value)"
@click:clear="updateSpeed(null)"
/>
<v-select
:model-value="modelValue?.reverse"
:items="directionOptions"
:label="$t('recipe.step-direction')"
clearable
density="compact"
@update:model-value="update('reverse', $event)"
/>
<v-text-field :model-value="modelValue?.mode" :label="$t('recipe.step-mode')" clearable density="compact" @update:model-value="update('mode', $event || null)" />
<RecipeStepOperationDetails :model-value="modelValue" :ingredients="ingredients" @update:model-value="emit('update:modelValue', $event)" @link-ingredient="emit('linkIngredient', $event)" />
<v-btn v-if="modelValue" variant="text" size="small" @click="emit('update:modelValue', null)">
{{ $t("recipe.step-cooking-clear") }}
</v-btn>
</div>
<div v-else-if="modelValue && parts.length" class="text-body-2 mt-2">
{{ parts.join(" · ") }}
</div>
<div v-if="!edit && modelValue?.reviews?.length" class="text-body-2 mt-2">
<div v-for="(review, index) in modelValue.reviews" :key="index">
{{ $t(`recipe.review-category-${review.category}`) }} — {{ $t(`recipe.review-status-${review.status ?? 'unresolved'}`) }}:
{{ review.source }} {{ review.reason }} {{ review.resolution }}
</div>
</div>
</template>
<script setup lang="ts">
import type { RecipeIngredient, StepCooking } from "~/lib/api/types/recipe";
import RecipeStepOperationDetails from "./RecipeStepOperationDetails.vue";
const props = defineProps<{ modelValue?: StepCooking | null; edit?: boolean; ingredients?: RecipeIngredient[] }>();
const emit = defineEmits<{ "update:modelValue": [value: StepCooking | null]; "linkIngredient": [referenceId: string] }>();
const { t } = useI18n();
const directionOptions = computed(() => [
{ title: t("recipe.step-forward"), value: false },
{ title: t("recipe.step-reverse"), value: true },
]);
// Keep imported fractional temperatures until the user changes the displayed value.
const inputTemperature = computed(() => props.modelValue?.temperatureCelsius == null
? null
: Math.round(props.modelValue.temperatureCelsius));
const fractionalTemperature = computed(() => props.modelValue?.temperatureCelsius != null
&& !Number.isInteger(props.modelValue.temperatureCelsius));
function updateTemperature(value: number | null) {
if (value !== inputTemperature.value) {
update("temperatureCelsius", value);
}
}
function update<K extends keyof StepCooking>(key: K, value: StepCooking[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function updateSpeed(value: string | null) {
const text = String(value ?? "").trim();
const numeric = Number(text);
update("speed", !text ? null : Number.isFinite(numeric) ? numeric : text);
}
const parts = computed(() => {
const cooking = props.modelValue;
if (!cooking) return [];
return [
cooking.appliance,
cooking.temperatureCelsius != null ? `${cooking.temperatureCelsius} °C` : null,
cooking.speed != null ? t("recipe.step-speed-value", { speed: cooking.speed }) : null,
cooking.reverse === true ? t("recipe.step-reverse") : null,
cooking.mode,
cooking.actionType ? t(`recipe.action-${cooking.actionType}`) : null,
cooking.applianceInstance,
cooking.timerType ? t(`recipe.timer-${cooking.timerType}`) : null,
cooking.durationKind ? t(`recipe.setting-${cooking.durationKind}`) : null,
...(cooking.accessories ?? []).map(accessory => `${accessory.name}: ${t(`recipe.accessory-${accessory.state}`)}`),
cooking.durationRangeSeconds ? `${t("recipe.operation-duration-range")}: ${cooking.durationRangeSeconds.minimum ?? "?"}–${cooking.durationRangeSeconds.maximum ?? "?"} s` : null,
cooking.durationCondition,
cooking.speedRange ? `${t("recipe.operation-speed-range")}: ${cooking.speedRange.minimum ?? "?"}–${cooking.speedRange.maximum ?? "?"}` : null,
cooking.speedProgression?.length ? `${t("recipe.operation-speed-progression")}: ${cooking.speedProgression.join(" → ")}` : null,
...(cooking.modeParameters ?? []).map(parameter => `${parameter.name}: ${parameter.value ?? [parameter.minimum, parameter.maximum].filter(v => v != null).join("–")} ${parameter.unit ?? ""}`),
cooking.optional ? t("recipe.operation-is-optional") : null,
cooking.condition,
cooking.requiresConfirmation ? t("recipe.operation-confirmation") : null,
cooking.repetitions != null ? `${t("recipe.operation-repetitions")}: ${cooking.repetitions}` : null,
cooking.repetitionRange ? `${t("recipe.operation-repetition-range")}: ${cooking.repetitionRange.minimum ?? "?"}–${cooking.repetitionRange.maximum ?? "?"}` : null,
].filter(Boolean);
});
</script>
@@ -0,0 +1,91 @@
import { mount } from "@vue/test-utils";
import { describe, expect, test } from "vitest";
import { createVuetify } from "vuetify";
import * as components from "vuetify/components";
import * as directives from "vuetify/directives";
import RecipeStepOperationDetails from "./RecipeStepOperationDetails.vue";
import type { StepCooking } from "~/lib/api/types/recipe";
function editor(modelValue: StepCooking = {}) {
return mount(RecipeStepOperationDetails, {
props: { modelValue },
global: { plugins: [createVuetify({ components, directives })] },
});
}
describe("generic operation editor", () => {
test("edits fractional duration bounds without inventing a fixed setting", async () => {
const wrapper = editor({ speed: 2, durationKind: "range" });
const inputs = wrapper.findAllComponents(components.VNumberInput);
await inputs.find(input => input.props("label") === "Minimum duration (seconds)")!.vm.$emit("update:modelValue", 0.5);
expect(wrapper.emitted("update:modelValue")?.at(-1)).toEqual([{
speed: 2, durationKind: "range", durationRangeSeconds: { minimum: 0.5 },
}]);
});
test("preserves progressive speeds and rejects an invalid progression visibly", async () => {
const wrapper = editor({ speed: 1, speedKind: "progression", speedProgression: [1, 3, 5] });
const input = wrapper.findAllComponents(components.VTextField).find(field => field.props("label") === "Speed progression (comma-separated)")!.find("input");
await input.setValue("1, 2.5, 6");
await input.trigger("change");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({ speed: 1, speedProgression: [1, 2.5, 6] });
const count = wrapper.emitted("update:modelValue")!.length;
await input.setValue("1, invalid");
await input.trigger("change");
expect(wrapper.emitted("update:modelValue")).toHaveLength(count);
expect(wrapper.text()).toContain("Enter a comma-separated list of numbers.");
});
test("edits accessory state and typed mode parameters without changing other settings", async () => {
const settings: StepCooking = {
appliance: "mixer",
accessories: [{ name: "basket", state: "unknown" }],
modeParameters: [{ name: "pulses", kind: "number", value: 3 }],
};
const wrapper = editor(settings);
const accessory = wrapper.findAllComponents(components.VSelect).find(field => field.props("label") === "State")!;
await accessory.vm.$emit("update:modelValue", "removed");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
accessories: [{ name: "basket", state: "removed" }], modeParameters: settings.modeParameters,
});
const parameter = wrapper.findAllComponents(components.VNumberInput).find(field => field.props("label") === "Value")!;
await parameter.vm.$emit("update:modelValue", 4);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
modeParameters: [{ name: "pulses", kind: "number", value: 4 }], appliance: "mixer",
});
});
test("edits conditions and repeats independently", async () => {
const wrapper = editor({ optional: true, condition: "If too coarse", requiresConfirmation: true });
const repeats = wrapper.findAllComponents(components.VNumberInput).find(field => field.props("label") === "Repetitions")!;
await repeats.vm.$emit("update:modelValue", 3);
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
optional: true, condition: "If too coarse", requiresConfirmation: true, repetitions: 3,
});
});
test("explicit parameter type changes clear incompatible values with a visible hint", async () => {
const wrapper = editor({ modeParameters: [{ name: "pulses", kind: "number", value: 3 }] });
const field = wrapper.findAllComponents(components.VSelect).find(input => input.props("label") === "Parameter type")!;
expect(wrapper.text()).toContain("Changing type clears the previous value and bounds.");
await field.vm.$emit("update:modelValue", "range");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
modeParameters: [{ name: "pulses", kind: "range", value: null, minimum: null, maximum: null }],
});
});
test("exposes review candidates, provenance and an explicit resolution", async () => {
const wrapper = editor({
reviews: [{ id: "review", category: "ingredient", source: "some flour", reason: "Unknown portion", candidateIngredientIds: ["flour"], status: "unresolved" }],
});
await wrapper.setProps({ ingredients: [{ referenceId: "flour", quantity: 100, note: "flour" }] });
const link = wrapper.findAllComponents(components.VSelect).find(field => field.props("label") === "Link a candidate ingredient (unknown amount)")!;
await link.vm.$emit("update:modelValue", "flour");
expect(wrapper.emitted("linkIngredient")).toEqual([["flour"]]);
const resolution = wrapper.findAllComponents(components.VTextField).find(field => field.props("label") === "Resolution")!;
await resolution.vm.$emit("update:modelValue", "Confirmed manual addition");
expect(wrapper.emitted("update:modelValue")?.at(-1)?.[0]).toMatchObject({
reviews: [{ source: "some flour", reason: "Unknown portion", resolution: "Confirmed manual addition", status: "unresolved" }],
});
});
});
@@ -0,0 +1,288 @@
<template>
<div class="mt-2">
<v-select
:model-value="modelValue?.actionType"
:items="actionTypes"
:label="$t('recipe.operation-type')"
clearable
density="compact"
@update:model-value="update('actionType', $event)"
/>
<v-select
:model-value="modelValue?.timerType"
:items="timerTypes"
:label="$t('recipe.operation-timer-type')"
clearable
density="compact"
@update:model-value="update('timerType', $event)"
/>
<v-select
:model-value="modelValue?.durationKind"
:items="durationKinds"
:label="$t('recipe.operation-duration-kind')"
clearable
density="compact"
@update:model-value="update('durationKind', $event)"
/>
<v-select
:model-value="modelValue?.speedKind"
:items="speedKinds"
:label="$t('recipe.operation-speed-kind')"
clearable
density="compact"
@update:model-value="update('speedKind', $event)"
/>
<v-text-field :model-value="modelValue?.applianceInstance" :label="$t('recipe.operation-instance')" clearable density="compact" @update:model-value="update('applianceInstance', $event || null)" />
<div v-for="range in ranges" :key="range.key" class="d-flex ga-2">
<v-number-input
:model-value="modelValue?.[range.key]?.minimum"
:label="$t(range.minimum)"
:precision="range.key === 'repetitionRange' ? 0 : null"
density="compact"
clearable
@update:model-value="setRange(range.key, 'minimum', $event)"
/>
<v-number-input
:model-value="modelValue?.[range.key]?.maximum"
:label="$t(range.maximum)"
:precision="range.key === 'repetitionRange' ? 0 : null"
density="compact"
clearable
@update:model-value="setRange(range.key, 'maximum', $event)"
/>
</div>
<v-text-field :model-value="modelValue?.durationCondition" :label="$t('recipe.operation-duration-condition')" clearable density="compact" @update:model-value="update('durationCondition', $event || null)" />
<v-text-field
:model-value="(modelValue?.speedProgression ?? []).join(', ')"
:label="$t('recipe.operation-speed-progression')"
:error-messages="progressionError ? [$t('recipe.operation-invalid-progression')] : []"
clearable
density="compact"
@change="setProgression(($event.target as HTMLInputElement).value)"
@click:clear="setProgression('')"
/>
<v-select
:model-value="modelValue?.optional"
:items="optionalOptions"
:label="$t('recipe.operation-optional')"
clearable
density="compact"
@update:model-value="update('optional', $event)"
/>
<v-text-field :model-value="modelValue?.condition" :label="$t('recipe.operation-condition')" clearable density="compact" @update:model-value="update('condition', $event || null)" />
<v-checkbox :model-value="modelValue?.requiresConfirmation ?? false" :label="$t('recipe.operation-confirmation')" density="compact" @update:model-value="update('requiresConfirmation', $event)" />
<v-combobox
:model-value="modelValue?.dependsOnStepIds ?? []"
:label="$t('recipe.operation-dependencies')"
multiple
chips
density="compact"
@update:model-value="update('dependsOnStepIds', $event)"
/>
<v-number-input
:model-value="modelValue?.repetitions"
:label="$t('recipe.operation-repetitions')"
:min="1"
:precision="0"
clearable
density="compact"
@update:model-value="update('repetitions', $event)"
/>
<div class="text-subtitle-2">
{{ $t("recipe.operation-accessories") }}
</div>
<div v-for="(accessory, index) in modelValue?.accessories ?? []" :key="index" class="d-flex ga-2">
<v-text-field :model-value="accessory.name" :label="$t('recipe.operation-name')" density="compact" @update:model-value="setAccessory(index, 'name', $event)" />
<v-select :model-value="accessory.state" :items="accessoryStates" :label="$t('recipe.operation-state')" density="compact" @update:model-value="setAccessory(index, 'state', $event)" />
<v-btn variant="text" @click="removeAccessory(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addAccessory">
{{ $t("recipe.operation-add-accessory") }}
</v-btn>
<div class="text-subtitle-2 mt-2">
{{ $t("recipe.operation-parameters") }}
</div>
<div v-for="(parameter, index) in modelValue?.modeParameters ?? []" :key="index">
<v-text-field :model-value="parameter.name" :label="$t('recipe.operation-name')" density="compact" @update:model-value="setParameter(index, 'name', $event)" />
<v-select
:model-value="parameter.kind ?? 'text'"
:items="parameterKinds"
:label="$t('recipe.operation-parameter-kind')"
:hint="$t('recipe.operation-parameter-kind-hint')"
persistent-hint
density="compact"
@update:model-value="setParameterKind(index, $event)"
/>
<v-number-input
v-if="parameter.kind === 'number'"
:model-value="typeof parameter.value === 'number' ? parameter.value : null"
:label="$t('recipe.operation-parameter-value')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'value', $event)"
/>
<v-select
v-else-if="parameter.kind === 'boolean'"
:model-value="parameter.value"
:items="optionalOptions"
:label="$t('recipe.operation-parameter-value')"
clearable
density="compact"
@update:model-value="setParameter(index, 'value', $event)"
/>
<v-text-field v-else-if="parameter.kind !== 'range'" :model-value="parameter.value == null ? '' : String(parameter.value)" :label="$t('recipe.operation-parameter-value')" density="compact" @change="setParameter(index, 'value', ($event.target as HTMLInputElement).value)" />
<v-text-field :model-value="parameter.unit" :label="$t('recipe.operation-parameter-unit')" clearable density="compact" @update:model-value="setParameter(index, 'unit', $event || null)" />
<div v-if="parameter.kind === 'range'" class="d-flex ga-2">
<v-number-input
:model-value="parameter.minimum"
:label="$t('recipe.operation-parameter-minimum')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'minimum', $event)"
/>
<v-number-input
:model-value="parameter.maximum"
:label="$t('recipe.operation-parameter-maximum')"
:precision="null"
clearable
density="compact"
@update:model-value="setParameter(index, 'maximum', $event)"
/>
</div>
<v-btn size="small" variant="text" @click="removeParameter(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addParameter">
{{ $t("recipe.operation-add-parameter") }}
</v-btn>
<div class="text-subtitle-2 mt-2">
{{ $t("recipe.operation-reviews") }}
</div>
<div v-for="(review, index) in modelValue?.reviews ?? []" :key="index" class="mb-3">
<v-select :model-value="review.category" :items="reviewCategories" :label="$t('recipe.operation-review-category')" density="compact" @update:model-value="setReview(index, 'category', $event)" />
<v-text-field :model-value="review.source" :readonly="!!review.history?.length" :label="$t('recipe.operation-review-source')" density="compact" @update:model-value="setReview(index, 'source', $event)" />
<v-text-field :model-value="review.reason" :readonly="!!review.history?.length" :label="$t('recipe.operation-review-reason')" density="compact" @update:model-value="setReview(index, 'reason', $event)" />
<v-select
v-if="review.category === 'ingredient'"
:model-value="review.candidateIngredientIds ?? []"
:items="ingredientOptions"
:label="$t('recipe.operation-review-candidates')"
multiple
chips
:readonly="!!review.history?.length"
density="compact"
@update:model-value="setReview(index, 'candidateIngredientIds', $event)"
/>
<v-select
v-if="review.category === 'ingredient'"
:items="ingredientOptions.filter(item => review.candidateIngredientIds?.includes(item.value))"
:label="$t('recipe.operation-review-link')"
density="compact"
@update:model-value="emit('linkIngredient', $event)"
/>
<v-text-field :model-value="review.resolution" :label="$t('recipe.operation-review-resolution')" clearable density="compact" @update:model-value="setReview(index, 'resolution', $event || null)" />
<v-select :model-value="review.status ?? 'unresolved'" :items="reviewStatuses" :label="$t('recipe.operation-review-status')" density="compact" @update:model-value="setReview(index, 'status', $event)" />
<details v-if="review.history?.length">
<summary>{{ $t("recipe.operation-review-history") }}</summary>
<div v-for="(event, eventIndex) in review.history" :key="eventIndex">
{{ event.at }} — {{ $t(`recipe.review-status-${event.status}`) }} — {{ event.resolution }}
<pre class="review-history">{{ event.content }}</pre>
</div>
</details>
<v-btn v-if="!review.history?.length" size="small" variant="text" @click="removeReview(index)">
{{ $t("general.delete") }}
</v-btn>
</div>
<v-btn size="small" variant="text" @click="addReview">
{{ $t("recipe.operation-add-review") }}
</v-btn>
</div>
</template>
<script setup lang="ts">
import type { RecipeIngredient, StepAccessory, StepCooking, StepParameter, StepRange, StepReview } from "~/lib/api/types/recipe";
const props = defineProps<{ modelValue?: StepCooking | null; ingredients?: RecipeIngredient[] }>();
const emit = defineEmits<{ "update:modelValue": [value: StepCooking]; "linkIngredient": [referenceId: string] }>();
const { t } = useI18n();
const progressionError = ref(false);
const options = (prefix: string, values: string[]) => values.map(value => ({ title: t(`recipe.${prefix}-${value}`), value }));
const actionTypes = computed(() => options("action", ["manual", "machine", "oven", "waiting", "weighing"]));
const timerTypes = computed(() => options("timer", ["machine", "manual", "oven", "resting"]));
const durationKinds = computed(() => options("setting", ["fixed", "range", "userSelected", "condition"]));
const speedKinds = computed(() => options("setting", ["fixed", "range", "progression"]));
const parameterKinds = computed(() => options("parameter-kind", ["text", "number", "boolean", "range"]));
const accessoryStates = computed(() => options("accessory", ["installed", "removed", "unknown", "conditional", "open", "closed"]));
const optionalOptions = computed(() => [{ title: t("general.yes"), value: true }, { title: t("general.no"), value: false }]);
const reviewCategories = computed(() => options("review-category", ["ingredient", "operation", "schema", "unsupported"]));
const reviewStatuses = computed(() => options("review-status", ["unresolved", "resolved"]));
const ingredientOptions = computed(() => (props.ingredients ?? []).filter(i => i.referenceId).map(i => ({ title: i.display || i.note || i.referenceId!, value: i.referenceId! })));
const ranges = [
{ key: "durationRangeSeconds", minimum: "recipe.operation-duration-minimum", maximum: "recipe.operation-duration-maximum" },
{ key: "speedRange", minimum: "recipe.operation-speed-minimum", maximum: "recipe.operation-speed-maximum" },
{ key: "repetitionRange", minimum: "recipe.operation-repeat-minimum", maximum: "recipe.operation-repeat-maximum" },
] as const;
function update<K extends keyof StepCooking>(key: K, value: StepCooking[K]) {
emit("update:modelValue", { ...props.modelValue, [key]: value });
}
function setRange(key: "durationRangeSeconds" | "speedRange" | "repetitionRange", bound: keyof StepRange, value: number | null) {
const range = { ...props.modelValue?.[key], [bound]: value };
update(key, range.minimum == null && range.maximum == null ? null : range);
}
function setProgression(text: string) {
const values = text.trim() ? text.split(",").map(value => value.trim()) : [];
progressionError.value = values.some(value => !value || !Number.isFinite(Number(value)));
if (!progressionError.value) update("speedProgression", values.map(Number));
}
function setAccessory<K extends keyof StepAccessory>(index: number, key: K, value: StepAccessory[K]) {
const items = [...(props.modelValue?.accessories ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("accessories", items);
}
function addAccessory() { update("accessories", [...(props.modelValue?.accessories ?? []), { name: "", state: "unknown" }]); }
function removeAccessory(index: number) { update("accessories", (props.modelValue?.accessories ?? []).filter((_, i) => i !== index)); }
function setParameter<K extends keyof StepParameter>(index: number, key: K, value: StepParameter[K]) {
const items = [...(props.modelValue?.modeParameters ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("modeParameters", items);
}
function setParameterKind(index: number, kind: NonNullable<StepParameter["kind"]>) {
const items = [...(props.modelValue?.modeParameters ?? [])];
const existing = items[index];
if (!existing || (existing.kind ?? "text") === kind) return;
items[index] = { ...existing, kind, value: null, minimum: null, maximum: null };
update("modeParameters", items);
}
function addParameter() { update("modeParameters", [...(props.modelValue?.modeParameters ?? []), { name: "" }]); }
function removeParameter(index: number) { update("modeParameters", (props.modelValue?.modeParameters ?? []).filter((_, i) => i !== index)); }
function setReview<K extends keyof StepReview>(index: number, key: K, value: StepReview[K]) {
const items = [...(props.modelValue?.reviews ?? [])];
const existing = items[index];
if (!existing) return;
items[index] = { ...existing, [key]: value };
update("reviews", items);
}
function addReview() { update("reviews", [...(props.modelValue?.reviews ?? []), { category: "operation", status: "unresolved" }]); }
function removeReview(index: number) { update("reviews", (props.modelValue?.reviews ?? []).filter((_, i) => i !== index)); }
</script>
<style scoped>
.review-history {
white-space: pre-wrap;
overflow-wrap: anywhere;
}
</style>