1
0
Fork 0
mirror of https://github.com/mealie-recipes/mealie.git synced 2025-07-25 08:09:41 +02:00

feat: Recipe Finder (aka Cocktail Builder) (#4542)

This commit is contained in:
Michael Genson 2024-12-03 07:27:41 -06:00 committed by GitHub
parent d26e29d1c5
commit 4e0cf985bc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
28 changed files with 1959 additions and 151 deletions

View file

@ -48,3 +48,11 @@
.v-card__title {
word-break: normal !important;
}
.text-hide-overflow {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}

View file

@ -253,7 +253,7 @@
</v-container>
</v-card-text>
<v-card-actions>
<v-container fluid class="d-flex justify-end pa-0">
<v-container fluid class="d-flex justify-end pa-0 mx-2">
<v-checkbox
v-model="showAdvanced"
hide-details
@ -431,6 +431,7 @@ export default defineComponent({
state.qfValid = !!qf;
context.emit("input", qf || undefined);
context.emit("inputJSON", qf ? buildQueryFilterJSON() : undefined);
},
{
deep: true
@ -543,6 +544,32 @@ export default defineComponent({
initFieldsError(`Error initializing fields: ${(error || "").toString()}`);
}
function buildQueryFilterJSON(): QueryFilterJSON {
const parts = fields.value.map((field) => {
const part: QueryFilterJSONPart = {
attributeName: field.name,
leftParenthesis: field.leftParenthesis,
rightParenthesis: field.rightParenthesis,
logicalOperator: field.logicalOperator?.value,
relationalOperator: field.relationalOperatorValue?.value,
};
if (field.fieldOptions?.length || isOrganizerType(field.type)) {
part.value = field.values.map((value) => value.toString());
} else if (field.type === "boolean") {
part.value = field.value ? "true" : "false";
} else {
part.value = (field.value || "").toString();
}
return part;
});
const qfJSON = { parts } as QueryFilterJSON;
console.debug(`Built query filter JSON: ${JSON.stringify(qfJSON)}`);
return qfJSON;
}
const attrs = computed(() => {
const baseColMaxWidth = 55;

View file

@ -0,0 +1,118 @@
<template>
<v-container class="elevation-3">
<v-row no-gutters>
<v-col cols="12">
<RecipeCardMobile
:name="recipe.name"
:description="recipe.description"
:slug="recipe.slug"
:rating="recipe.rating"
:image="recipe.image"
:recipe-id="recipe.id"
/>
</v-col>
<div v-for="(organizer, idx) in missingOrganizers" :key="idx">
<v-col
v-if="organizer.show"
cols="12"
>
<div class="d-flex flex-row flex-wrap align-center pt-2">
<v-icon class="ma-0 pa-0">{{ organizer.icon }}</v-icon>
<v-card-text class="mr-0 my-0 pl-1 py-0" style="width: min-content;">
{{ $tc("recipe-finder.missing") }}:
</v-card-text>
<v-chip
v-for="item in organizer.items"
:key="item.item.id"
label
color="secondary custom-transparent"
class="mr-2 my-1"
>
<v-checkbox dark :ripple="false" @click="handleCheckbox(item)">
<template #label>
{{ organizer.getLabel(item.item) }}
</template>
</v-checkbox>
</v-chip>
</div>
</v-col>
</div>
</v-row>
</v-container>
</template>
<script lang="ts">
import { computed, defineComponent, reactive, useContext } from "@nuxtjs/composition-api";
import RecipeCardMobile from "./RecipeCardMobile.vue";
import { IngredientFood, RecipeSummary, RecipeTool } from "~/lib/api/types/recipe";
interface Organizer {
type: "food" | "tool";
item: IngredientFood | RecipeTool;
selected: boolean;
}
export default defineComponent({
components: { RecipeCardMobile },
props: {
recipe: {
type: Object as () => RecipeSummary,
required: true,
},
missingFoods: {
type: Array as () => IngredientFood[] | null,
default: null,
},
missingTools: {
type: Array as () => RecipeTool[] | null,
default: null,
},
disableCheckbox: {
type: Boolean,
default: false,
},
},
setup(props, context) {
const { $globals } = useContext();
const missingOrganizers = computed(() => [
{
type: "food",
show: props.missingFoods?.length,
icon: $globals.icons.foods,
items: props.missingFoods ? props.missingFoods.map((food) => {
return reactive({type: "food", item: food, selected: false} as Organizer);
}) : [],
getLabel: (item: IngredientFood) => item.pluralName || item.name,
},
{
type: "tool",
show: props.missingTools?.length,
icon: $globals.icons.tools,
items: props.missingTools ? props.missingTools.map((tool) => {
return reactive({type: "tool", item: tool, selected: false} as Organizer);
}) : [],
getLabel: (item: RecipeTool) => item.name,
}
])
function handleCheckbox(organizer: Organizer) {
if (props.disableCheckbox) {
return;
}
organizer.selected = !organizer.selected;
if (organizer.selected) {
context.emit(`add-${organizer.type}`, organizer.item);
}
else {
context.emit(`remove-${organizer.type}`, organizer.item);
}
}
return {
missingOrganizers,
handleCheckbox,
};
}
});
</script>

View file

@ -221,7 +221,13 @@ export default defineComponent({
icon: $globals.icons.silverwareForkKnife,
to: `/g/${groupSlug.value}`,
title: i18n.tc("general.recipes"),
restricted: true,
restricted: false,
},
{
icon: $globals.icons.search,
to: `/g/${groupSlug.value}/recipes/finder`,
title: i18n.tc("recipe-finder.recipe-finder"),
restricted: false,
},
{
icon: $globals.icons.calendarMultiselect,

View file

@ -45,11 +45,13 @@
</v-btn>
<v-spacer></v-spacer>
<slot name="custom-card-action"></slot>
<BaseButton v-if="$listeners.delete" delete secondary @click="deleteEvent" />
<BaseButton
v-if="$listeners.confirm"
:color="color"
type="submit"
:disabled="submitDisabled"
@click="
$emit('confirm');
dialog = false;
@ -60,8 +62,12 @@
</template>
{{ $t("general.confirm") }}
</BaseButton>
<slot name="custom-card-action"></slot>
<BaseButton v-if="$listeners.submit" type="submit" :disabled="submitDisabled" @click="submitEvent">
<BaseButton
v-if="$listeners.submit"
type="submit"
:disabled="submitDisabled"
@click="submitEvent"
>
{{ submitText }}
<template v-if="submitIcon" #icon>
{{ submitIcon }}

View file

@ -1,6 +1,7 @@
import { Ref, useContext } from "@nuxtjs/composition-api";
import { useLocalStorage, useSessionStorage } from "@vueuse/core";
import { RegisteredParser, TimelineEventType } from "~/lib/api/types/recipe";
import { QueryFilterJSON } from "~/lib/api/types/response";
export interface UserPrintPreferences {
imagePosition: string;
@ -49,6 +50,17 @@ export interface UserCookbooksPreferences {
hideOtherHouseholds: boolean;
}
export interface UserRecipeFinderPreferences {
foodIds: string[];
toolIds: string[];
queryFilter: string;
queryFilterJSON: QueryFilterJSON;
maxMissingFoods: number;
maxMissingTools: number;
includeFoodsOnHand: boolean;
includeToolsOnHand: boolean;
}
export function useUserMealPlanPreferences(): Ref<UserMealPlanPreferences> {
const fromStorage = useLocalStorage(
"meal-planner-preferences",
@ -171,3 +183,24 @@ export function useCookbookPreferences(): Ref<UserCookbooksPreferences> {
return fromStorage;
}
export function useRecipeFinderPreferences(): Ref<UserRecipeFinderPreferences> {
const fromStorage = useLocalStorage(
"recipe-finder-preferences",
{
foodIds: [],
toolIds: [],
queryFilter: "",
queryFilterJSON: { parts: [] } as QueryFilterJSON,
maxMissingFoods: 20,
maxMissingTools: 20,
includeFoodsOnHand: true,
includeToolsOnHand: true,
},
{ mergeDefaults: true }
// we cast to a Ref because by default it will return an optional type ref
// but since we pass defaults we know all properties are set.
) as unknown as Ref<UserRecipeFinderPreferences>;
return fromStorage;
}

View file

@ -671,6 +671,23 @@
"reset-servings-count": "Reset Servings Count",
"not-linked-ingredients": "Additional Ingredients"
},
"recipe-finder": {
"recipe-finder": "Recipe Finder",
"recipe-finder-description": "Search for recipes based on ingredients you have on hand. You can also filter by tools you have available, and set a maximum number of missing ingredients or tools.",
"selected-ingredients": "Selected Ingredients",
"no-ingredients-selected": "No ingredients selected",
"missing": "Missing",
"no-recipes-found": "No recipes found",
"no-recipes-found-description": "Try adding more ingredients to your search or adjusting your filters",
"include-ingredients-on-hand": "Include Ingredients On Hand",
"include-tools-on-hand": "Include Tools On Hand",
"max-missing-ingredients": "Max Missing Ingredients",
"max-missing-tools": "Max Missing Tools",
"selected-tools": "Selected Tools",
"other-filters": "Other Filters",
"ready-to-make": "Ready to Make",
"almost-ready-to-make": "Almost Ready to Make"
},
"search": {
"advanced-search": "Advanced Search",
"and": "and",

View file

@ -1,6 +1,6 @@
import { BaseCRUDAPIReadOnly } from "~/lib/api/base/base-clients";
import { route } from "../../base";
import { Recipe } from "~/lib/api/types/recipe";
import { Recipe, RecipeSuggestionQuery, RecipeSuggestionResponse } from "~/lib/api/types/recipe";
import { ApiRequestInstance, PaginationData } from "~/lib/api/types/non-generated";
import { RecipeSearchQuery } from "../../user/recipes/recipe";
@ -23,4 +23,10 @@ export class PublicRecipeApi extends BaseCRUDAPIReadOnly<Recipe> {
async search(rsq: RecipeSearchQuery) {
return await this.requests.get<PaginationData<Recipe>>(route(routes.recipesGroupSlug(this.groupSlug), rsq));
}
async getSuggestions(q: RecipeSuggestionQuery, foods: string[] | null = null, tools: string[]| null = null) {
return await this.requests.get<RecipeSuggestionResponse>(
route(`${this.baseRoute}/suggestions`, { ...q, foods, tools })
);
}
}

View file

@ -7,6 +7,8 @@
export type ExportTypes = "json";
export type RegisteredParser = "nlp" | "brute" | "openai";
export type OrderByNullPosition = "first" | "last";
export type OrderDirection = "asc" | "desc";
export type TimelineEventType = "system" | "info" | "comment";
export type TimelineEventImage = "has image" | "does not have image";
@ -380,6 +382,26 @@ export interface RecipeShareTokenSummary {
export interface RecipeSlug {
slug: string;
}
export interface RecipeSuggestionQuery {
orderBy?: string | null;
orderByNullPosition?: OrderByNullPosition | null;
orderDirection?: OrderDirection;
queryFilter?: string | null;
paginationSeed?: string | null;
limit?: number;
maxMissingFoods?: number;
maxMissingTools?: number;
includeFoodsOnHand?: boolean;
includeToolsOnHand?: boolean;
}
export interface RecipeSuggestionResponse {
items: RecipeSuggestionResponseItem[];
}
export interface RecipeSuggestionResponseItem {
recipe: RecipeSummary;
missingFoods: IngredientFood[];
missingTools: RecipeTool[];
}
export interface RecipeTagResponse {
name: string;
id: string;
@ -519,3 +541,10 @@ export interface UnitFoodBase {
export interface UpdateImageResponse {
image: string;
}
export interface RequestQuery {
orderBy?: string | null;
orderByNullPosition?: OrderByNullPosition | null;
orderDirection?: OrderDirection;
queryFilter?: string | null;
paginationSeed?: string | null;
}

View file

@ -20,13 +20,13 @@ export interface FileTokenResponse {
fileToken: string;
}
export interface PaginationQuery {
page?: number;
perPage?: number;
orderBy?: string | null;
orderByNullPosition?: OrderByNullPosition | null;
orderDirection?: OrderDirection;
queryFilter?: string | null;
paginationSeed?: string | null;
page?: number;
perPage?: number;
}
export interface QueryFilterJSON {
parts?: QueryFilterJSONPart[];
@ -47,6 +47,13 @@ export interface RecipeSearchQuery {
requireAllFoods?: boolean;
search?: string | null;
}
export interface RequestQuery {
orderBy?: string | null;
orderByNullPosition?: OrderByNullPosition | null;
orderDirection?: OrderDirection;
queryFilter?: string | null;
paginationSeed?: string | null;
}
export interface SuccessResponse {
message: string;
error?: boolean;

View file

@ -11,6 +11,8 @@ import {
UpdateImageResponse,
RecipeZipTokenResponse,
RecipeLastMade,
RecipeSuggestionQuery,
RecipeSuggestionResponse,
RecipeTimelineEventIn,
RecipeTimelineEventOut,
RecipeTimelineEventUpdate,
@ -31,6 +33,7 @@ const prefix = "/api";
const routes = {
recipesCreate: `${prefix}/recipes/create`,
recipesBase: `${prefix}/recipes`,
recipesSuggestions: `${prefix}/recipes/suggestions`,
recipesTestScrapeUrl: `${prefix}/recipes/test-scrape-url`,
recipesCreateUrl: `${prefix}/recipes/create/url`,
recipesCreateUrlBulk: `${prefix}/recipes/create/url/bulk`,
@ -109,6 +112,12 @@ export class RecipeAPI extends BaseCRUDAPI<CreateRecipe, Recipe, Recipe> {
});
}
async getSuggestions(q: RecipeSuggestionQuery, foods: string[] | null = null, tools: string[]| null = null) {
return await this.requests.get<RecipeSuggestionResponse>(
route(routes.recipesSuggestions, { ...q, foods, tools })
);
}
async createAsset(recipeSlug: string, payload: CreateAsset) {
const formData = new FormData();
formData.append("file", payload.file);

View file

@ -0,0 +1,596 @@
<template>
<v-container>
<BasePageTitle divider>
<template #header>
<v-img max-height="100" max-width="100" :src="require('~/static/svgs/manage-cookbooks.svg')"></v-img>
</template>
<template #title> {{ $tc('recipe-finder.recipe-finder') }} </template>
{{ $t('recipe-finder.recipe-finder-description') }}
</BasePageTitle>
<v-container v-if="ready">
<v-row>
<v-col :cols="useMobile ? 12 : 3">
<v-container class="ma-0 pa-0">
<v-row no-gutters>
<v-col cols="12" no-gutters :class="attrs.searchFilter.colClass">
<SearchFilter v-if="foods" v-model="selectedFoods" :items="foods" :class="attrs.searchFilter.filterClass">
<v-icon left>
{{ $globals.icons.foods }}
</v-icon>
{{ $t("general.foods") }}
</SearchFilter>
<SearchFilter v-if="tools" v-model="selectedTools" :items="tools" :class="attrs.searchFilter.filterClass">
<v-icon left>
{{ $globals.icons.potSteam }}
</v-icon>
{{ $t("tool.tools") }}
</SearchFilter>
<div :class="attrs.searchFilter.filterClass">
<v-badge
:value="queryFilterJSON.parts && queryFilterJSON.parts.length"
small
overlap
color="primary"
:content="(queryFilterJSON.parts || []).length"
>
<v-btn
small
color="accent"
dark
@click="queryFilterMenu = !queryFilterMenu"
>
<v-icon left>
{{ $globals.icons.filter }}
</v-icon>
{{ $tc("recipe-finder.other-filters") }}
<BaseDialog
v-model="queryFilterMenu"
:title="$tc('recipe-finder.other-filters')"
:icon="$globals.icons.filter"
width="100%"
max-width="1100px"
:submit-disabled="!queryFilterEditorValue"
@confirm="saveQueryFilter"
>
<QueryFilterBuilder
:key="queryFilterMenuKey"
:initial-query-filter="queryFilterJSON"
:field-defs="queryFilterBuilderFields"
@input="(value) => queryFilterEditorValue = value"
@inputJSON="(value) => queryFilterEditorValueJSON = value"
/>
<template #custom-card-action>
<BaseButton color="error" type="submit" @click="clearQueryFilter">
<template #icon>
{{ $globals.icons.close }}
</template>
{{ $t("search.clear-selection") }}
</BaseButton>
</template>
</BaseDialog>
</v-btn>
</v-badge>
</div>
</v-col>
</v-row>
<!-- Settings Menu -->
<v-row no-gutters class="mb-2">
<v-col cols="12" :class="attrs.settings.colClass">
<v-menu
v-model="settingsMenu"
offset-y
nudge-bottom="3"
:close-on-content-click="false"
>
<template #activator="{ on, attrs: activatorAttrs}">
<v-btn small color="primary" dark v-bind="activatorAttrs" v-on="on">
<v-icon left>
{{ $globals.icons.cog }}
</v-icon>
{{ $t("general.settings") }}
</v-btn>
</template>
<v-card>
<v-card-text>
<div>
<v-text-field
v-model="settings.maxMissingFoods"
type="number"
hide-details
hide-spin-buttons
:label="$tc('recipe-finder.max-missing-ingredients')"
/>
<v-text-field
v-model="settings.maxMissingTools"
type="number"
hide-details
hide-spin-buttons
:label="$tc('recipe-finder.max-missing-tools')"
class="mt-4"
/>
</div>
<div class="mt-1">
<v-checkbox
v-if="isOwnGroup"
v-model="settings.includeFoodsOnHand"
dense
small
hide-details
class="my-auto"
:label="$tc('recipe-finder.include-ingredients-on-hand')"
/>
<v-checkbox
v-if="isOwnGroup"
v-model="settings.includeToolsOnHand"
dense
small
hide-details
class="my-auto"
:label="$tc('recipe-finder.include-tools-on-hand')"
/>
</div>
</v-card-text>
</v-card>
</v-menu>
</v-col>
</v-row>
<v-row no-gutters class="my-2">
<v-col cols="12">
<v-divider />
</v-col>
</v-row>
<v-row no-gutters class="mt-5">
<v-card-title class="ma-0 pa-0">
{{ $tc("recipe-finder.selected-ingredients") }}
</v-card-title>
<v-container class="ma-0 pa-0" style="max-height: 60vh; overflow-y: auto;">
<v-card-text v-if="!selectedFoods.length" class="ma-0 pa-0">
{{ $tc("recipe-finder.no-ingredients-selected") }}
</v-card-text>
<div v-if="useMobile">
<v-row no-gutters>
<v-col cols="12" class="d-flex flex-wrap justify-end">
<v-chip
v-for="food in selectedFoods"
:key="food.id"
label
class="ma-1"
color="accent custom-transparent"
close
@click:close="removeFood(food)"
>
<span class="text-hide-overflow">{{ food.pluralName || food.name }}</span>
</v-chip>
</v-col>
</v-row>
</div>
<div v-else>
<v-row v-for="food in selectedFoods" :key="food.id" no-gutters class="mb-1">
<v-col cols="12">
<v-chip
label
color="accent custom-transparent"
close
@click:close="removeFood(food)"
>
<span class="text-hide-overflow">{{ food.pluralName || food.name }}</span>
</v-chip>
</v-col>
</v-row>
</div>
</v-container>
</v-row>
<v-row v-if="selectedTools.length" no-gutters class="mt-5">
<v-card-title class="ma-0 pa-0">
{{ $tc("recipe-finder.selected-tools") }}
</v-card-title>
<v-container class="ma-0 pa-0">
<div v-if="useMobile">
<v-row no-gutters>
<v-col cols="12" class="d-flex flex-wrap justify-end">
<v-chip
v-for="tool in selectedTools"
:key="tool.id"
label
class="ma-1"
color="accent custom-transparent"
close
@click:close="removeTool(tool)"
>
<span class="text-hide-overflow">{{ tool.name }}</span>
</v-chip>
</v-col>
</v-row>
</div>
<div v-else>
<v-row v-for="tool in selectedTools" :key="tool.id" no-gutters class="mb-1">
<v-col cols="12">
<v-chip
label
color="accent custom-transparent"
close
@click:close="removeTool(tool)"
>
<span class="text-hide-overflow">{{ tool.name }}</span>
</v-chip>
</v-col>
</v-row>
</div>
</v-container>
</v-row>
</v-container>
</v-col>
<v-col :cols="useMobile ? 12 : 9">
<v-container
v-if="recipeSuggestions.readyToMake.length || recipeSuggestions.missingItems.length"
class="ma-0 pa-0"
>
<v-row v-if="recipeSuggestions.readyToMake.length" dense>
<v-col cols="12">
<v-card-title :class="attrs.title.class.readyToMake">
{{ $tc("recipe-finder.ready-to-make") }}
</v-card-title>
</v-col>
<v-col
v-for="(item, idx) in recipeSuggestions.readyToMake"
:key="`${idx}-ready`"
cols="12"
>
<v-lazy>
<RecipeSuggestion
:recipe="item.recipe"
:missing-foods="item.missingFoods"
:missing-tools="item.missingTools"
:disable-checkbox="loading"
@add-food="addFood"
@remove-food="removeFood"
@add-tool="addTool"
@remove-tool="removeTool"
/>
</v-lazy>
</v-col>
</v-row>
<v-row v-if="recipeSuggestions.missingItems.length" dense>
<v-col cols="12">
<v-card-title :class="attrs.title.class.missingItems">
{{ $tc("recipe-finder.almost-ready-to-make") }}
</v-card-title>
</v-col>
<v-col
v-for="(item, idx) in recipeSuggestions.missingItems"
:key="`${idx}-missing`"
cols="12"
>
<v-lazy>
<RecipeSuggestion
:recipe="item.recipe"
:missing-foods="item.missingFoods"
:missing-tools="item.missingTools"
:disable-checkbox="loading"
@add-food="addFood"
@remove-food="removeFood"
@add-tool="addTool"
@remove-tool="removeTool"
/>
</v-lazy>
</v-col>
</v-row>
</v-container>
<v-container v-else-if="!recipesReady">
<v-row>
<v-col cols="12" class="d-flex justify-center">
<div class="text-center">
<AppLoader waiting-text="" />
</div>
</v-col>
</v-row>
</v-container>
<v-container v-else>
<v-row>
<v-col cols="12" class="d-flex flex-row flex-wrap justify-center">
<v-card-title class="ma-0 pa-0">{{ $tc("recipe-finder.no-recipes-found") }}</v-card-title>
<v-card-text class="ma-0 pa-0 text-center">
{{ $tc("recipe-finder.no-recipes-found-description") }}
</v-card-text>
</v-col>
</v-row>
</v-container>
</v-col>
</v-row>
</v-container>
<v-container v-else>
<v-row>
<v-col cols="12" class="d-flex justify-center">
<div class="text-center">
<AppLoader waiting-text="" />
</div>
</v-col>
</v-row>
</v-container>
</v-container>
</template>
<script lang="ts">
import {
computed,
defineComponent,
onMounted,
reactive,
ref,
toRefs,
useContext,
useRoute,
watch
} from "@nuxtjs/composition-api";
import { watchDebounced } from "@vueuse/core";
import { useUserApi } from "~/composables/api";
import { usePublicExploreApi } from "~/composables/api/api-client";
import { useLoggedInState } from "~/composables/use-logged-in-state";
import { useFoodStore, usePublicFoodStore, useToolStore, usePublicToolStore } from "~/composables/store";
import { IngredientFood, RecipeSuggestionQuery, RecipeSuggestionResponseItem, RecipeTool } from "~/lib/api/types/recipe";
import { Organizer } from "~/lib/api/types/non-generated";
import QueryFilterBuilder from "~/components/Domain/QueryFilterBuilder.vue";
import RecipeSuggestion from "~/components/Domain/Recipe/RecipeSuggestion.vue";
import SearchFilter from "~/components/Domain/SearchFilter.vue";
import { QueryFilterJSON } from "~/lib/api/types/response";
import { FieldDefinition } from "~/composables/use-query-filter-builder";
import { useRecipeFinderPreferences } from "~/composables/use-users/preferences";
interface RecipeSuggestions {
readyToMake: RecipeSuggestionResponseItem[];
missingItems: RecipeSuggestionResponseItem[];
}
export default defineComponent({
components: { QueryFilterBuilder, RecipeSuggestion, SearchFilter },
setup() {
const { $auth, $vuetify, i18n } = useContext();
const route = useRoute();
const useMobile = computed(() => $vuetify.breakpoint.smAndDown);
const groupSlug = computed(() => route.value.params.groupSlug || $auth.user?.groupSlug || "");
const { isOwnGroup } = useLoggedInState();
const api = isOwnGroup.value ? useUserApi() : usePublicExploreApi(groupSlug.value).explore;
const preferences = useRecipeFinderPreferences();
const state = reactive({
ready: false,
loading: false,
recipesReady: false,
settingsMenu: false,
queryFilterMenu: false,
queryFilterMenuKey: 0,
queryFilterEditorValue: "",
queryFilterEditorValueJSON: {},
queryFilterJSON: preferences.value.queryFilterJSON,
settings: {
maxMissingFoods: preferences.value.maxMissingFoods,
maxMissingTools: preferences.value.maxMissingTools,
includeFoodsOnHand: preferences.value.includeFoodsOnHand,
includeToolsOnHand: preferences.value.includeToolsOnHand,
queryFilter: preferences.value.queryFilter,
limit: 10,
},
});
onMounted(() => {
if (!isOwnGroup.value) {
state.settings.includeFoodsOnHand = false;
state.settings.includeToolsOnHand = false;
}
});
watch(
() => state,
(newState) => {
preferences.value.queryFilter = newState.settings.queryFilter;
preferences.value.queryFilterJSON = newState.queryFilterJSON;
preferences.value.maxMissingFoods = newState.settings.maxMissingFoods;
preferences.value.maxMissingTools = newState.settings.maxMissingTools;
preferences.value.includeFoodsOnHand = newState.settings.includeFoodsOnHand;
preferences.value.includeToolsOnHand = newState.settings.includeToolsOnHand;
},
{
deep: true,
},
);
const attrs = computed(() => {
return {
title: {
class: {
readyToMake: "ma-0 pa-0",
missingItems: recipeSuggestions.value.readyToMake.length ? "ma-0 pa-0 mt-5" : "ma-0 pa-0",
},
},
searchFilter: {
colClass: useMobile.value ? "d-flex flex-wrap justify-end" : "d-flex flex-wrap justify-start",
filterClass: useMobile.value ? "ml-4 mb-2" : "mr-4 mb-2",
},
settings: {
colClass: useMobile.value ? "d-flex flex-wrap justify-end" : "d-flex flex-wrap justify-start",
},
};
})
const foodStore = isOwnGroup.value ? useFoodStore() : usePublicFoodStore(groupSlug.value);
const selectedFoods = ref<IngredientFood[]>([]);
function addFood(food: IngredientFood) {
selectedFoods.value.push(food);
}
function removeFood(food: IngredientFood) {
selectedFoods.value = selectedFoods.value.filter((f) => f.id !== food.id);
}
watch(
() => selectedFoods.value,
() => {
selectedFoods.value.sort((a, b) => (a.pluralName || a.name).localeCompare(b.pluralName || b.name));
preferences.value.foodIds = selectedFoods.value.map((food) => food.id);
}
)
const toolStore = isOwnGroup.value ? useToolStore() : usePublicToolStore(groupSlug.value);
const selectedTools = ref<RecipeTool[]>([]);
function addTool(tool: RecipeTool) {
selectedTools.value.push(tool);
}
function removeTool(tool: RecipeTool) {
selectedTools.value = selectedTools.value.filter((t) => t.id !== tool.id);
}
watch(
() => selectedTools.value,
() => {
selectedTools.value.sort((a, b) => a.name.localeCompare(b.name));
preferences.value.toolIds = selectedTools.value.map((tool) => tool.id);
}
)
async function hydrateFoods() {
if (!preferences.value.foodIds.length) {
return;
}
if (!foodStore.store.value.length) {
await foodStore.actions.refresh();
}
const foods = preferences.value.foodIds
.map((foodId) => foodStore.store.value.find((food) => food.id === foodId))
.filter((food) => !!food);
selectedFoods.value = foods;
}
async function hydrateTools() {
if (!preferences.value.toolIds.length) {
return;
}
if (!toolStore.store.value.length) {
await toolStore.actions.refresh();
}
const tools = preferences.value.toolIds
.map((toolId) => toolStore.store.value.find((tool) => tool.id === toolId))
.filter((tool) => !!tool);
selectedTools.value = tools;
}
onMounted(async () => {
await Promise.all([hydrateFoods(), hydrateTools()]);
state.ready = true;
if (!selectedFoods.value.length) {
state.recipesReady = true;
};
});
const recipeResponseItems = ref<RecipeSuggestionResponseItem[]>([]);
const recipeSuggestions = computed<RecipeSuggestions>(() => {
const readyToMake: RecipeSuggestionResponseItem[] = [];
const missingItems: RecipeSuggestionResponseItem[] = [];
recipeResponseItems.value.forEach((responseItem) => {
if (responseItem.missingFoods.length === 0 && responseItem.missingTools.length === 0) {
readyToMake.push(responseItem);
} else {
missingItems.push(responseItem);
};
});
return {
readyToMake,
missingItems,
};
})
watchDebounced(
[selectedFoods, selectedTools, state.settings], async () => {
// don't search for suggestions if no foods are selected
if(!selectedFoods.value.length) {
recipeResponseItems.value = [];
state.recipesReady = true;
return;
}
state.loading = true;
const { data } = await api.recipes.getSuggestions(
{
limit: state.settings.limit,
queryFilter: state.settings.queryFilter,
maxMissingFoods: state.settings.maxMissingFoods,
maxMissingTools: state.settings.maxMissingTools,
includeFoodsOnHand: state.settings.includeFoodsOnHand,
includeToolsOnHand: state.settings.includeToolsOnHand,
} as RecipeSuggestionQuery,
selectedFoods.value.map((food) => food.id),
selectedTools.value.map((tool) => tool.id),
);
state.loading = false;
if (!data) {
return;
}
recipeResponseItems.value = data.items;
state.recipesReady = true;
},
{
debounce: 500,
},
);
const queryFilterBuilderFields: FieldDefinition[] = [
{
name: "recipe_category.id",
label: i18n.tc("category.categories"),
type: Organizer.Category,
},
{
name: "tags.id",
label: i18n.tc("tag.tags"),
type: Organizer.Tag,
},
{
name: "household_id",
label: i18n.tc("household.households"),
type: Organizer.Household,
},
];
function clearQueryFilter() {
state.queryFilterEditorValue = "";
state.queryFilterEditorValueJSON = { parts: [] } as QueryFilterJSON;
state.settings.queryFilter = "";
state.queryFilterJSON = { parts: [] } as QueryFilterJSON;
state.queryFilterMenu = false;
state.queryFilterMenuKey += 1;
}
function saveQueryFilter() {
state.settings.queryFilter = state.queryFilterEditorValue || "";
state.queryFilterJSON = state.queryFilterEditorValueJSON || { parts: [] } as QueryFilterJSON;
state.queryFilterMenu = false;
}
return {
...toRefs(state),
useMobile,
attrs,
isOwnGroup,
foods: foodStore.store,
selectedFoods,
addFood,
removeFood,
tools: toolStore.store,
selectedTools,
addTool,
removeTool,
recipeSuggestions,
queryFilterBuilderFields,
clearQueryFilter,
saveQueryFilter,
};
},
head() {
return {
title: this.$tc("recipe-finder.recipe-finder"),
};
},
});
</script>