chore: migrate remaining pages to script setup (#7310)

This commit is contained in:
Kuchenpirat
2026-03-24 16:07:08 +01:00
committed by GitHub
parent 27cb585c80
commit 18b3c4beab
57 changed files with 4160 additions and 4971 deletions

View File

@@ -2,10 +2,6 @@
<CookbookPage />
</template>
<script lang="ts">
<script setup lang="ts">
import CookbookPage from "@/components/Domain/Cookbook/CookbookPage.vue";
export default defineNuxtComponent({
components: { CookbookPage },
});
</script>

View File

@@ -135,7 +135,7 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import { VueDraggable } from "vue-draggable-plus";
import { useCookbookStore } from "~/composables/store/use-cookbook-store";
import { useHouseholdSelf } from "@/composables/use-households";
@@ -143,121 +143,99 @@ import CookbookEditor from "~/components/Domain/Cookbook/CookbookEditor.vue";
import type { CreateCookBook, ReadCookBook } from "~/lib/api/types/cookbook";
import { useCookbookPreferences } from "~/composables/use-users/preferences";
export default defineNuxtComponent({
components: { CookbookEditor, VueDraggable },
definePageMeta({
middleware: ["group-only"],
setup() {
const dialogStates = reactive({
create: false,
delete: false,
});
});
const i18n = useI18n();
const dialogStates = reactive({
create: false,
delete: false,
});
// Set page title
useSeoMeta({
title: i18n.t("cookbook.cookbooks"),
});
const i18n = useI18n();
const auth = useMealieAuth();
const { store: allCookbooks, actions, updateAll } = useCookbookStore();
// Set page title
useSeoMeta({
title: i18n.t("cookbook.cookbooks"),
});
// Make a local reactive copy of myCookbooks
const myCookbooks = ref<ReadCookBook[]>([]);
watch(
allCookbooks,
(cookbooks) => {
myCookbooks.value
= cookbooks?.filter(
cookbook => cookbook.householdId === auth.user.value?.householdId,
).sort((a, b) => a.position > b.position) ?? [];
},
{ immediate: true },
);
const auth = useMealieAuth();
const { store: allCookbooks, actions, updateAll } = useCookbookStore();
const { household } = useHouseholdSelf();
const cookbookPreferences = useCookbookPreferences();
// create
const createTargetKey = ref(0);
const createTarget = ref<ReadCookBook | null>(null);
async function createCookbook() {
const name = i18n.t("cookbook.household-cookbook-name", [
household.value?.name || "",
String((myCookbooks.value?.length ?? 0) + 1),
]) as string;
const data = { name } as CreateCookBook;
await actions.createOne(data).then((cookbook) => {
if (!cookbook) {
return;
}
myCookbooks.value.push(cookbook);
createTarget.value = cookbook as ReadCookBook;
createTargetKey.value++;
});
dialogStates.create = true;
}
// delete
const deleteTarget = ref<ReadCookBook | null>(null);
function deleteEventHandler(item: ReadCookBook) {
deleteTarget.value = item;
dialogStates.delete = true;
}
async function deleteCookbook() {
if (!deleteTarget.value) {
return;
}
await actions.deleteOne(deleteTarget.value.id);
myCookbooks.value = myCookbooks.value.filter(c => c.id !== deleteTarget.value?.id);
dialogStates.delete = false;
deleteTarget.value = null;
}
async function deleteCreateTarget() {
if (!createTarget.value?.id) {
return;
}
await actions.deleteOne(createTarget.value.id);
myCookbooks.value = myCookbooks.value.filter(c => c.id !== createTarget.value?.id);
dialogStates.create = false;
createTarget.value = null;
}
function handleUnmount() {
if (!createTarget.value?.id || createTarget.value.queryFilterString) {
return;
}
deleteCreateTarget();
}
onMounted(() => {
window.addEventListener("beforeunload", handleUnmount);
});
onBeforeUnmount(() => {
handleUnmount();
window.removeEventListener("beforeunload", handleUnmount);
});
return {
myCookbooks,
cookbookPreferences,
actions,
dialogStates,
// create
createTargetKey,
createTarget,
createCookbook,
// update
updateAll,
// delete
deleteTarget,
deleteEventHandler,
deleteCookbook,
deleteCreateTarget,
};
// Make a local reactive copy of myCookbooks
const myCookbooks = ref<ReadCookBook[]>([]);
watch(
allCookbooks,
(cookbooks) => {
myCookbooks.value
= cookbooks?.filter(
cookbook => cookbook.householdId === auth.user.value?.householdId,
).sort((a, b) => a.position > b.position) ?? [];
},
{ immediate: true },
);
const { household } = useHouseholdSelf();
const cookbookPreferences = useCookbookPreferences();
// create
const createTargetKey = ref(0);
const createTarget = ref<ReadCookBook | null>(null);
async function createCookbook() {
const name = i18n.t("cookbook.household-cookbook-name", [
household.value?.name || "",
String((myCookbooks.value?.length ?? 0) + 1),
]) as string;
const data = { name } as CreateCookBook;
await actions.createOne(data).then((cookbook) => {
if (!cookbook) {
return;
}
myCookbooks.value.push(cookbook);
createTarget.value = cookbook as ReadCookBook;
createTargetKey.value++;
});
dialogStates.create = true;
}
// delete
const deleteTarget = ref<ReadCookBook | null>(null);
function deleteEventHandler(item: ReadCookBook) {
deleteTarget.value = item;
dialogStates.delete = true;
}
async function deleteCookbook() {
if (!deleteTarget.value) {
return;
}
await actions.deleteOne(deleteTarget.value.id);
myCookbooks.value = myCookbooks.value.filter(c => c.id !== deleteTarget.value?.id);
dialogStates.delete = false;
deleteTarget.value = null;
}
async function deleteCreateTarget() {
if (!createTarget.value?.id) {
return;
}
await actions.deleteOne(createTarget.value.id);
myCookbooks.value = myCookbooks.value.filter(c => c.id !== createTarget.value?.id);
dialogStates.create = false;
createTarget.value = null;
}
function handleUnmount() {
if (!createTarget.value?.id || createTarget.value.queryFilterString) {
return;
}
deleteCreateTarget();
}
onMounted(() => {
window.addEventListener("beforeunload", handleUnmount);
});
onBeforeUnmount(() => {
handleUnmount();
window.removeEventListener("beforeunload", handleUnmount);
});
</script>

View File

@@ -4,10 +4,6 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import RecipeExplorerPage from "~/components/Domain/Recipe/RecipeExplorerPage/RecipeExplorerPage.vue";
export default defineNuxtComponent({
components: { RecipeExplorerPage },
});
</script>

View File

@@ -42,79 +42,71 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import type { MenuItem } from "~/components/global/BaseOverflowButton.vue";
import AdvancedOnly from "~/components/global/AdvancedOnly.vue";
export default defineNuxtComponent({
components: { AdvancedOnly },
definePageMeta({
middleware: ["group-only"],
setup() {
const i18n = useI18n();
const auth = useMealieAuth();
const { $appInfo, $globals } = useNuxtApp();
});
useSeoMeta({
title: i18n.t("general.create"),
});
const i18n = useI18n();
const auth = useMealieAuth();
const { $appInfo, $globals } = useNuxtApp();
const subpages = computed<MenuItem[]>(() => [
{
icon: $globals.icons.link,
text: i18n.t("recipe.import-with-url"),
value: "url",
},
{
icon: $globals.icons.link,
text: i18n.t("recipe.bulk-url-import"),
value: "bulk",
},
{
icon: $globals.icons.codeTags,
text: i18n.t("recipe.import-from-html-or-json"),
value: "html",
},
{
icon: $globals.icons.fileImage,
text: i18n.t("recipe.create-from-images"),
value: "image",
hide: !$appInfo.enableOpenaiImageServices,
},
{
icon: $globals.icons.edit,
text: i18n.t("recipe.create-recipe"),
value: "new",
},
{
icon: $globals.icons.zip,
text: i18n.t("recipe.import-with-zip"),
value: "zip",
},
{
icon: $globals.icons.robot,
text: i18n.t("recipe.debug-scraper"),
value: "debug",
},
]);
useSeoMeta({
title: i18n.t("general.create"),
});
const route = useRoute();
const router = useRouter();
const groupSlug = computed(() => route.params.groupSlug || auth.user.value?.groupSlug || "");
const subpages = computed<MenuItem[]>(() => [
{
icon: $globals.icons.link,
text: i18n.t("recipe.import-with-url"),
value: "url",
},
{
icon: $globals.icons.link,
text: i18n.t("recipe.bulk-url-import"),
value: "bulk",
},
{
icon: $globals.icons.codeTags,
text: i18n.t("recipe.import-from-html-or-json"),
value: "html",
},
{
icon: $globals.icons.fileImage,
text: i18n.t("recipe.create-from-images"),
value: "image",
hide: !$appInfo.enableOpenaiImageServices,
},
{
icon: $globals.icons.edit,
text: i18n.t("recipe.create-recipe"),
value: "new",
},
{
icon: $globals.icons.zip,
text: i18n.t("recipe.import-with-zip"),
value: "zip",
},
{
icon: $globals.icons.robot,
text: i18n.t("recipe.debug-scraper"),
value: "debug",
},
]);
const subpage = computed({
set(subpage: string) {
router.push({ path: `/g/${groupSlug.value}/r/create/${subpage}`, query: route.query });
},
get() {
return route.path.split("/").pop() ?? "url";
},
});
const route = useRoute();
const router = useRouter();
const groupSlug = computed(() => route.params.groupSlug || auth.user.value?.groupSlug || "");
return {
groupSlug,
subpages,
subpage,
};
const subpage = computed({
set(subpage: string) {
router.push({ path: `/g/${groupSlug.value}/r/create/${subpage}`, query: route.query });
},
get() {
return route.path.split("/").pop() ?? "url";
},
});
</script>

View File

@@ -49,7 +49,7 @@
</template>
</v-text-field>
</v-col>
<template v-if="showCatTags">
<template v-if="state.showCatTags">
<v-col
cols="12"
xs="12"
@@ -115,14 +115,14 @@
{{ $t('general.new') }}
</BaseButton>
<RecipeDialogBulkAdd
v-model="bulkDialog"
v-model="state.bulkDialog"
class="mr-1 mr-sm-0 mb-1"
@bulk-data="assignUrls"
/>
</v-card-actions>
<div class="px-0">
<v-checkbox
v-model="showCatTags"
v-model="state.showCatTags"
hide-details
:label="$t('recipe.set-categories-and-tags')"
/>
@@ -154,7 +154,7 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import { whenever } from "@vueuse/shared";
import { useUserApi } from "~/composables/api";
import { alert } from "~/composables/use-toast";
@@ -162,84 +162,67 @@ import RecipeOrganizerSelector from "~/components/Domain/Recipe/RecipeOrganizerS
import type { ReportSummary } from "~/lib/api/types/reports";
import RecipeDialogBulkAdd from "~/components/Domain/Recipe/RecipeDialogBulkAdd.vue";
export default defineNuxtComponent({
components: { RecipeOrganizerSelector, RecipeDialogBulkAdd },
setup() {
const state = reactive({
error: false,
loading: false,
showCatTags: false,
bulkDialog: false,
});
whenever(
() => !state.showCatTags,
() => {
console.log("showCatTags changed");
},
);
const api = useUserApi();
const i18n = useI18n();
const bulkUrls = ref([{ url: "", categories: [], tags: [] }]);
const lockBulkImport = ref(false);
async function bulkCreate() {
if (bulkUrls.value.length === 0) {
return;
}
const { response } = await api.recipes.createManyByUrl({ imports: bulkUrls.value });
if (response?.status === 202) {
alert.success(i18n.t("recipe.bulk-import-process-has-started"));
lockBulkImport.value = true;
}
else {
alert.error(i18n.t("recipe.bulk-import-process-has-failed"));
}
fetchReports();
}
// =========================================================
// Reports
const reports = ref<ReportSummary[]>([]);
async function fetchReports() {
const { data } = await api.groupReports.getAll("bulk_import");
reports.value = data ?? [];
}
async function deleteReport(id: string) {
console.log(id);
const { response } = await api.groupReports.deleteOne(id);
if (response?.status === 200) {
fetchReports();
}
else {
alert.error(i18n.t("recipe.report-deletion-failed"));
}
}
fetchReports();
function assignUrls(urls: string[]) {
bulkUrls.value = urls.map(url => ({ url, categories: [], tags: [] }));
}
return {
assignUrls,
reports,
deleteReport,
bulkCreate,
bulkUrls,
lockBulkImport,
...toRefs(state),
};
},
const state = reactive({
showCatTags: false,
bulkDialog: false,
});
whenever(
() => !state.showCatTags,
() => {
console.log("showCatTags changed");
},
);
const api = useUserApi();
const i18n = useI18n();
const bulkUrls = ref([{ url: "", categories: [], tags: [] }]);
const lockBulkImport = ref(false);
async function bulkCreate() {
if (bulkUrls.value.length === 0) {
return;
}
const { response } = await api.recipes.createManyByUrl({ imports: bulkUrls.value });
if (response?.status === 202) {
alert.success(i18n.t("recipe.bulk-import-process-has-started"));
lockBulkImport.value = true;
}
else {
alert.error(i18n.t("recipe.bulk-import-process-has-failed"));
}
fetchReports();
}
// =========================================================
// Reports
const reports = ref<ReportSummary[]>([]);
async function fetchReports() {
const { data } = await api.groupReports.getAll("bulk_import");
reports.value = data ?? [];
}
async function deleteReport(id: string) {
console.log(id);
const { response } = await api.groupReports.deleteOne(id);
if (response?.status === 200) {
fetchReports();
}
else {
alert.error(i18n.t("recipe.report-deletion-failed"));
}
}
fetchReports();
function assignUrls(urls: string[]) {
bulkUrls.value = urls.map(url => ({ url, categories: [], tags: [] }));
}
</script>

View File

@@ -28,7 +28,7 @@
<v-card-text v-if="$appInfo.enableOpenai">
{{ $t('recipe.recipe-debugger-use-openai-description') }}
<v-checkbox
v-model="useOpenAI"
v-model="state.useOpenAI"
:label="$t('recipe.use-openai')"
/>
</v-card-text>
@@ -40,7 +40,7 @@
block
type="submit"
color="info"
:loading="loading"
:loading="state.loading"
>
<template #icon>
{{ $globals.icons.robot }}
@@ -67,60 +67,46 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import { useUserApi } from "~/composables/api";
import { validators } from "~/composables/use-validators";
import type { Recipe } from "~/lib/api/types/recipe";
export default defineNuxtComponent({
setup() {
const state = reactive({
error: false,
loading: false,
useOpenAI: false,
});
const state = reactive({
loading: false,
useOpenAI: false,
});
const api = useUserApi();
const route = useRoute();
const router = useRouter();
const api = useUserApi();
const route = useRoute();
const router = useRouter();
const recipeUrl = computed({
set(recipe_import_url: string | null) {
if (recipe_import_url !== null) {
recipe_import_url = recipe_import_url.trim();
router.replace({ query: { ...route.query, recipe_import_url } });
}
},
get() {
return route.query.recipe_import_url as string | null;
},
});
const debugTreeView = ref(false);
const debugData = ref<Recipe | null>(null);
async function debugUrl(url: string | null) {
if (url === null) {
return;
}
state.loading = true;
const { data } = await api.recipes.testCreateOneUrl(url, state.useOpenAI);
state.loading = false;
debugData.value = data;
const recipeUrl = computed({
set(recipe_import_url: string | null) {
if (recipe_import_url !== null) {
recipe_import_url = recipe_import_url.trim();
router.replace({ query: { ...route.query, recipe_import_url } });
}
return {
recipeUrl,
debugTreeView,
debugUrl,
debugData,
...toRefs(state),
validators,
};
},
get() {
return route.query.recipe_import_url as string | null;
},
});
const debugTreeView = ref(false);
const debugData = ref<Recipe | null>(null);
async function debugUrl(url: string | null) {
if (url === null) {
return;
}
state.loading = true;
const { data } = await api.recipes.testCreateOneUrl(url, state.useOpenAI);
state.loading = false;
debugData.value = data;
}
</script>

View File

@@ -90,7 +90,7 @@
rounded
block
type="submit"
:loading="loading"
:loading="state.loading"
/>
</div>
<v-card-text class="py-2">
@@ -103,7 +103,7 @@
</v-form>
</template>
<script lang="ts">
<script setup lang="ts">
import type { AxiosResponse } from "axios";
import { useTagStore } from "~/composables/store/use-tag-store";
import { useUserApi } from "~/composables/api";
@@ -111,113 +111,94 @@ import { useNewRecipeOptions } from "~/composables/use-new-recipe-options";
import { validators } from "~/composables/use-validators";
import type { VForm } from "~/types/auto-forms";
export default defineNuxtComponent({
setup() {
const state = reactive({
error: false,
loading: false,
isEditJSON: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const domUrlForm = ref<VForm | null>(null);
const api = useUserApi();
const tags = useTagStore();
const {
importKeywordsAsTags,
importCategories,
stayInEditMode,
parseRecipe,
navigateToRecipe,
} = useNewRecipeOptions();
function handleResponse(response: AxiosResponse<string> | null, refreshTags = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
if (refreshTags) {
tags.actions.refresh();
}
navigateToRecipe(response.data, groupSlug.value, `/g/${groupSlug.value}/r/create/html`);
}
const newRecipeData = ref<string | object | null>(null);
const newRecipeUrl = ref<string | null>(null);
function handleIsEditJson() {
if (state.isEditJSON) {
if (newRecipeData.value) {
try {
newRecipeData.value = JSON.parse(newRecipeData.value as string);
}
catch {
newRecipeData.value = { data: newRecipeData.value };
}
}
else {
newRecipeData.value = {};
}
}
else if (newRecipeData.value && Object.keys(newRecipeData.value).length > 0) {
newRecipeData.value = JSON.stringify(newRecipeData.value);
}
else {
newRecipeData.value = null;
}
}
handleIsEditJson();
const createStatus = ref<string | null>(null);
async function createFromHtmlOrJson(htmlOrJsonData: string | object | null, importKeywordsAsTags: boolean, importCategories: boolean, url: string | null = null) {
if (!htmlOrJsonData) {
return;
}
const isValid = await domUrlForm.value?.validate();
if (!isValid?.valid) {
return;
}
let dataString;
if (typeof htmlOrJsonData === "string") {
dataString = htmlOrJsonData;
}
else {
dataString = JSON.stringify(htmlOrJsonData);
}
state.loading = true;
const { response } = await api.recipes.createOneByHtmlOrJson(
dataString,
importKeywordsAsTags,
importCategories,
url,
(message: string) => createStatus.value = message,
);
createStatus.value = null;
handleResponse(response, importKeywordsAsTags);
}
return {
domUrlForm,
importKeywordsAsTags,
stayInEditMode,
parseRecipe,
importCategories,
newRecipeData,
newRecipeUrl,
handleIsEditJson,
createStatus,
createFromHtmlOrJson,
...toRefs(state),
validators,
};
},
const state = reactive({
error: false,
loading: false,
isEditJSON: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const domUrlForm = ref<VForm | null>(null);
const api = useUserApi();
const tags = useTagStore();
const {
importKeywordsAsTags,
importCategories,
stayInEditMode,
parseRecipe,
navigateToRecipe,
} = useNewRecipeOptions();
function handleResponse(response: AxiosResponse<string> | null, refreshTags = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
if (refreshTags) {
tags.actions.refresh();
}
navigateToRecipe(response.data, groupSlug.value, `/g/${groupSlug.value}/r/create/html`);
}
const newRecipeData = ref<string | object | null>(null);
const newRecipeUrl = ref<string | null>(null);
function handleIsEditJson() {
if (state.isEditJSON) {
if (newRecipeData.value) {
try {
newRecipeData.value = JSON.parse(newRecipeData.value as string);
}
catch {
newRecipeData.value = { data: newRecipeData.value };
}
}
else {
newRecipeData.value = {};
}
}
else if (newRecipeData.value && Object.keys(newRecipeData.value).length > 0) {
newRecipeData.value = JSON.stringify(newRecipeData.value);
}
else {
newRecipeData.value = null;
}
}
handleIsEditJson();
const createStatus = ref<string | null>(null);
async function createFromHtmlOrJson(htmlOrJsonData: string | object | null, importKeywordsAsTags: boolean, importCategories: boolean, url: string | null = null) {
if (!htmlOrJsonData) {
return;
}
const isValid = await domUrlForm.value?.validate();
if (!isValid?.valid) {
return;
}
let dataString;
if (typeof htmlOrJsonData === "string") {
dataString = htmlOrJsonData;
}
else {
dataString = JSON.stringify(htmlOrJsonData);
}
state.loading = true;
const { response } = await api.recipes.createOneByHtmlOrJson(
dataString,
importKeywordsAsTags,
importCategories,
url,
(message: string) => createStatus.value = message,
);
createStatus.value = null;
handleResponse(response, importKeywordsAsTags);
}
</script>

View File

@@ -37,7 +37,7 @@
:img="imageUrl"
cropper-height="100%"
cropper-width="100%"
:submitted="loading"
:submitted="state.loading"
class="mt-4 mb-2"
@save="(croppedImage) => updateUploadedImage(index, croppedImage)"
@delete="clearImage(index)"
@@ -45,7 +45,7 @@
<v-btn
v-if="uploadedImages.length > 1"
:disabled="loading || index === 0"
:disabled="state.loading || index === 0"
color="primary"
@click="() => setCoverImage(index)"
>
@@ -66,7 +66,7 @@
color="primary"
hide-details
:label="$t('recipe.should-translate-description')"
:disabled="loading"
:disabled="state.loading"
/>
<v-checkbox
v-if="uploadedImages.length"
@@ -74,15 +74,15 @@
color="primary"
hide-details
:label="$t('recipe.parse-recipe-ingredients-after-import')"
:disabled="loading"
:disabled="state.loading"
/>
</v-card-text>
<v-card-actions v-if="uploadedImages.length">
<div class="w-100 d-flex flex-column align-center">
<p style="width: 250px">
<BaseButton rounded block type="submit" :loading="loading" />
<BaseButton rounded block type="submit" :loading="state.loading" />
</p>
<p v-if="loading" class="mb-0">
<p v-if="state.loading" class="mb-0">
{{
uploadedImages.length > 1
? $t("recipe.please-wait-images-processing")
@@ -96,111 +96,93 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import { useUserApi } from "~/composables/api";
import { alert } from "~/composables/use-toast";
import { useNewRecipeOptions } from "~/composables/use-new-recipe-options";
import type { VForm } from "~/types/auto-forms";
export default defineNuxtComponent({
setup() {
const state = reactive({
loading: false,
});
const i18n = useI18n();
const api = useUserApi();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug || "");
const domUrlForm = ref<VForm | null>(null);
const uploadedImages = ref<(Blob | File)[]>([]);
const uploadedImageNames = ref<string[]>([]);
const uploadedImagesPreviewUrls = ref<string[]>([]);
const shouldTranslate = ref(true);
const { parseRecipe, navigateToRecipe } = useNewRecipeOptions();
function uploadImages(files: File[]) {
uploadedImages.value = [...uploadedImages.value, ...files];
uploadedImageNames.value = [...uploadedImageNames.value, ...files.map(file => file.name)];
uploadedImagesPreviewUrls.value = [
...uploadedImagesPreviewUrls.value,
...files.map(file => URL.createObjectURL(file)),
];
}
function clearImage(index: number) {
// Revoke _before_ splicing
URL.revokeObjectURL(uploadedImagesPreviewUrls.value[index]);
uploadedImages.value.splice(index, 1);
uploadedImageNames.value.splice(index, 1);
uploadedImagesPreviewUrls.value.splice(index, 1);
}
async function createRecipe() {
if (uploadedImages.value.length === 0) {
return;
}
state.loading = true;
const translateLanguage = shouldTranslate.value ? i18n.locale : undefined;
const { data, error } = await api.recipes.createOneFromImages(uploadedImages.value, translateLanguage?.value);
if (error || !data) {
alert.error(i18n.t("events.something-went-wrong"));
state.loading = false;
}
else {
navigateToRecipe(data, groupSlug.value, `/g/${groupSlug.value}/r/create/image`);
}
}
function updateUploadedImage(index: number, croppedImage: Blob) {
uploadedImages.value[index] = croppedImage;
uploadedImagesPreviewUrls.value[index] = URL.createObjectURL(croppedImage);
}
function swapItem(array: any[], i: number, j: number) {
if (i < 0 || j < 0 || i >= array.length || j >= array.length) {
return;
}
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function swapImages(i: number, j: number) {
swapItem(uploadedImages.value, i, j);
swapItem(uploadedImageNames.value, i, j);
swapItem(uploadedImagesPreviewUrls.value, i, j);
}
// Put the intended cover image at the start of the array
// The backend currently sets the first image as the cover image
function setCoverImage(index: number) {
if (index < 0 || index >= uploadedImages.value.length || index === 0) {
return;
}
swapImages(0, index);
}
return {
...toRefs(state),
domUrlForm,
uploadedImages,
uploadedImagesPreviewUrls,
shouldTranslate,
parseRecipe,
uploadImages,
clearImage,
createRecipe,
updateUploadedImage,
setCoverImage,
};
},
const state = reactive({
loading: false,
});
const i18n = useI18n();
const api = useUserApi();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug || "");
const domUrlForm = ref<VForm | null>(null);
const uploadedImages = ref<(Blob | File)[]>([]);
const uploadedImageNames = ref<string[]>([]);
const uploadedImagesPreviewUrls = ref<string[]>([]);
const shouldTranslate = ref(true);
const { parseRecipe, navigateToRecipe } = useNewRecipeOptions();
function uploadImages(files: File[]) {
uploadedImages.value = [...uploadedImages.value, ...files];
uploadedImageNames.value = [...uploadedImageNames.value, ...files.map(file => file.name)];
uploadedImagesPreviewUrls.value = [
...uploadedImagesPreviewUrls.value,
...files.map(file => URL.createObjectURL(file)),
];
}
function clearImage(index: number) {
// Revoke _before_ splicing
URL.revokeObjectURL(uploadedImagesPreviewUrls.value[index]);
uploadedImages.value.splice(index, 1);
uploadedImageNames.value.splice(index, 1);
uploadedImagesPreviewUrls.value.splice(index, 1);
}
async function createRecipe() {
if (uploadedImages.value.length === 0) {
return;
}
state.loading = true;
const translateLanguage = shouldTranslate.value ? i18n.locale : undefined;
const { data, error } = await api.recipes.createOneFromImages(uploadedImages.value, translateLanguage?.value);
if (error || !data) {
alert.error(i18n.t("events.something-went-wrong"));
state.loading = false;
}
else {
navigateToRecipe(data, groupSlug.value, `/g/${groupSlug.value}/r/create/image`);
}
}
function updateUploadedImage(index: number, croppedImage: Blob) {
uploadedImages.value[index] = croppedImage;
uploadedImagesPreviewUrls.value[index] = URL.createObjectURL(croppedImage);
}
function swapItem(array: any[], i: number, j: number) {
if (i < 0 || j < 0 || i >= array.length || j >= array.length) {
return;
}
const temp = array[i];
array[i] = array[j];
array[j] = temp;
}
function swapImages(i: number, j: number) {
swapItem(uploadedImages.value, i, j);
swapItem(uploadedImageNames.value, i, j);
swapItem(uploadedImagesPreviewUrls.value, i, j);
}
// Put the intended cover image at the start of the array
// The backend currently sets the first image as the cover image
function setCoverImage(index: number) {
if (index < 0 || index >= uploadedImages.value.length || index === 0) {
return;
}
swapImages(0, index);
}
</script>

View File

@@ -2,15 +2,10 @@
<div />
</template>
<script lang="ts">
export default defineNuxtComponent({
setup() {
const router = useRouter();
onMounted(() => {
// Force redirect to first valid page
router.replace("/r/create/url");
});
return {};
},
<script setup lang="ts">
const router = useRouter();
onMounted(() => {
// Force redirect to first valid page
router.replace("/r/create/url");
});
</script>

View File

@@ -33,7 +33,7 @@
:disabled="newRecipeName.trim() === ''"
rounded
block
:loading="loading"
:loading="state.loading"
@click="createByName(newRecipeName)"
/>
</div>
@@ -41,51 +41,40 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import type { AxiosResponse } from "axios";
import { useUserApi } from "~/composables/api";
import { validators } from "~/composables/use-validators";
import type { VForm } from "~/types/auto-forms";
export default defineNuxtComponent({
setup() {
const state = reactive({
error: false,
loading: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const api = useUserApi();
const router = useRouter();
function handleResponse(response: AxiosResponse<string> | null, edit = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
router.push(`/g/${groupSlug.value}/r/${response.data}?edit=${edit.toString()}`);
}
const newRecipeName = ref("");
const domCreateByName = ref<VForm | null>(null);
async function createByName(name: string) {
if (!domCreateByName.value?.validate() || name === "") {
return;
}
const { response } = await api.recipes.createOne({ name });
handleResponse(response as any, true);
}
return {
domCreateByName,
newRecipeName,
createByName,
...toRefs(state),
validators,
};
},
const state = reactive({
error: false,
loading: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const api = useUserApi();
const router = useRouter();
function handleResponse(response: AxiosResponse<string> | null, edit = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
router.push(`/g/${groupSlug.value}/r/${response.data}?edit=${edit.toString()}`);
}
const newRecipeName = ref("");
const domCreateByName = ref<VForm | null>(null);
async function createByName(name: string) {
if (!domCreateByName.value?.validate() || name === "") {
return;
}
const { response } = await api.recipes.createOne({ name });
handleResponse(response as any, true);
}
</script>

View File

@@ -72,7 +72,7 @@
rounded
block
type="submit"
:loading="loading"
:loading="state.loading"
/>
</div>
<v-card-text class="py-2">
@@ -85,7 +85,7 @@
</v-form>
<v-expand-transition>
<v-alert
v-if="error"
v-if="state.error"
color="error"
class="mt-6 white--text"
>
@@ -140,7 +140,7 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import type { AxiosResponse } from "axios";
import { useUserApi } from "~/composables/api";
import { useTagStore } from "~/composables/store/use-tag-store";
@@ -148,135 +148,116 @@ import { useNewRecipeOptions } from "~/composables/use-new-recipe-options";
import { validators } from "~/composables/use-validators";
import type { VForm } from "~/types/auto-forms";
export default defineNuxtComponent({
setup() {
definePageMeta({
key: route => route.path,
});
const state = reactive({
error: false,
loading: false,
});
definePageMeta({
key: route => route.path,
});
const state = reactive({
error: false,
loading: false,
});
const auth = useMealieAuth();
const api = useUserApi();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const auth = useMealieAuth();
const api = useUserApi();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const router = useRouter();
const tags = useTagStore();
const router = useRouter();
const tags = useTagStore();
const {
importKeywordsAsTags,
importCategories,
stayInEditMode,
parseRecipe,
navigateToRecipe,
} = useNewRecipeOptions();
const {
importKeywordsAsTags,
importCategories,
stayInEditMode,
parseRecipe,
navigateToRecipe,
} = useNewRecipeOptions();
const bulkImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/bulk`);
const htmlOrJsonImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/html`);
const bulkImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/bulk`);
const htmlOrJsonImporterTarget = computed(() => `/g/${groupSlug.value}/r/create/html`);
function handleResponse(response: AxiosResponse<string> | null, refreshTags = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
if (refreshTags) {
tags.actions.refresh();
}
function handleResponse(response: AxiosResponse<string> | null, refreshTags = false) {
if (response?.status !== 201) {
state.error = true;
state.loading = false;
return;
}
if (refreshTags) {
tags.actions.refresh();
}
navigateToRecipe(response.data, groupSlug.value, `/g/${groupSlug.value}/r/create/url`);
navigateToRecipe(response.data, groupSlug.value, `/g/${groupSlug.value}/r/create/url`);
}
const recipeUrl = computed({
set(recipe_import_url: string | null) {
if (recipe_import_url !== null) {
recipe_import_url = recipe_import_url.trim();
router.replace({ query: { ...route.query, recipe_import_url } });
}
const recipeUrl = computed({
set(recipe_import_url: string | null) {
if (recipe_import_url !== null) {
recipe_import_url = recipe_import_url.trim();
router.replace({ query: { ...route.query, recipe_import_url } });
}
},
get() {
return route.query.recipe_import_url as string | null;
},
});
onMounted(() => {
if (recipeUrl.value && recipeUrl.value.includes("https")) {
// Check if we have a query params for using keywords as tags or staying in edit mode.
// We don't use these in the app anymore, but older automations such as Bookmarklet might still use them,
// and they're easy enough to support.
const importKeywordsAsTagsParam = route.query.use_keywords;
if (importKeywordsAsTagsParam === "1") {
importKeywordsAsTags.value = true;
}
else if (importKeywordsAsTagsParam === "0") {
importKeywordsAsTags.value = false;
}
const stayInEditModeParam = route.query.edit;
if (stayInEditModeParam === "1") {
stayInEditMode.value = true;
}
else if (stayInEditModeParam === "0") {
stayInEditMode.value = false;
}
createByUrl(recipeUrl.value, importKeywordsAsTags.value, false);
return;
}
});
const domUrlForm = ref<VForm | null>(null);
// Remove import URL from query params when leaving the page
const isLeaving = ref(false);
onBeforeRouteLeave((to) => {
if (isLeaving.value) {
return;
}
isLeaving.value = true;
router.replace({ query: undefined }).then(() => router.push(to));
});
const createStatus = ref<string | null>(null);
async function createByUrl(url: string | null, importKeywordsAsTags: boolean, importCategories: boolean) {
if (url === null) {
return;
}
if (!domUrlForm.value?.validate() || url === "") {
console.log("Invalid URL", url);
return;
}
state.loading = true;
const { response } = await api.recipes.createOneByUrl(
url,
importKeywordsAsTags,
importCategories,
(message: string) => createStatus.value = message,
);
createStatus.value = null;
handleResponse(response, importKeywordsAsTags);
}
return {
bulkImporterTarget,
htmlOrJsonImporterTarget,
recipeUrl,
importKeywordsAsTags,
importCategories: importCategories,
stayInEditMode,
parseRecipe,
domUrlForm,
createStatus,
createByUrl,
...toRefs(state),
validators,
};
},
get() {
return route.query.recipe_import_url as string | null;
},
});
onMounted(() => {
if (recipeUrl.value && recipeUrl.value.includes("https")) {
// Check if we have a query params for using keywords as tags or staying in edit mode.
// We don't use these in the app anymore, but older automations such as Bookmarklet might still use them,
// and they're easy enough to support.
const importKeywordsAsTagsParam = route.query.use_keywords;
if (importKeywordsAsTagsParam === "1") {
importKeywordsAsTags.value = true;
}
else if (importKeywordsAsTagsParam === "0") {
importKeywordsAsTags.value = false;
}
const stayInEditModeParam = route.query.edit;
if (stayInEditModeParam === "1") {
stayInEditMode.value = true;
}
else if (stayInEditModeParam === "0") {
stayInEditMode.value = false;
}
createByUrl(recipeUrl.value, importKeywordsAsTags.value, false);
return;
}
});
const domUrlForm = ref<VForm | null>(null);
// Remove import URL from query params when leaving the page
const isLeaving = ref(false);
onBeforeRouteLeave((to) => {
if (isLeaving.value) {
return;
}
isLeaving.value = true;
router.replace({ query: undefined }).then(() => router.push(to));
});
const createStatus = ref<string | null>(null);
async function createByUrl(url: string | null, importKeywordsAsTags: boolean, importCategories: boolean) {
if (url === null) {
return;
}
if (!domUrlForm.value?.validate() || url === "") {
console.log("Invalid URL", url);
return;
}
state.loading = true;
const { response } = await api.recipes.createOneByUrl(
url,
importKeywordsAsTags,
importCategories,
(message: string) => createStatus.value = message,
);
createStatus.value = null;
handleResponse(response, importKeywordsAsTags);
}
</script>
<style scoped>

View File

@@ -27,7 +27,7 @@
:disabled="newRecipeZip === null"
rounded
block
:loading="loading"
:loading="state.loading"
@click="createByZip"
/>
</div>
@@ -36,57 +36,45 @@
</v-form>
</template>
<script lang="ts">
<script setup lang="ts">
import { useUserApi } from "~/composables/api";
import { useGlobalI18n } from "~/composables/use-global-i18n";
import { alert } from "~/composables/use-toast";
import { validators } from "~/composables/use-validators";
export default defineNuxtComponent({
setup() {
const state = reactive({
loading: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const api = useUserApi();
const router = useRouter();
const newRecipeZip = ref<File | null>(null);
const newRecipeZipFileName = "archive";
async function createByZip() {
if (!newRecipeZip.value) {
return;
}
const formData = new FormData();
formData.append(newRecipeZipFileName, newRecipeZip.value);
try {
const response = await api.upload.file("/api/recipes/create/zip", formData);
if (response?.status !== 201) {
throw new Error("Failed to upload zip");
}
router.push(`/g/${groupSlug.value}/r/${response.data}`);
}
catch (error) {
console.error(error);
const i18n = useGlobalI18n();
alert.error(i18n.t("events.something-went-wrong"));
}
finally {
state.loading = false;
}
}
return {
newRecipeZip,
createByZip,
...toRefs(state),
validators,
};
},
const state = reactive({
loading: false,
});
const auth = useMealieAuth();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const api = useUserApi();
const router = useRouter();
const newRecipeZip = ref<File | null>(null);
const newRecipeZipFileName = "archive";
async function createByZip() {
if (!newRecipeZip.value) {
return;
}
const formData = new FormData();
formData.append(newRecipeZipFileName, newRecipeZip.value);
try {
const response = await api.upload.file("/api/recipes/create/zip", formData);
if (response?.status !== 201) {
throw new Error("Failed to upload zip");
}
router.push(`/g/${groupSlug.value}/r/${response.data}`);
}
catch (error) {
console.error(error);
const i18n = useGlobalI18n();
alert.error(i18n.t("events.something-went-wrong"));
}
finally {
state.loading = false;
}
}
</script>

View File

@@ -15,27 +15,18 @@
</v-container>
</template>
<script lang="ts">
<script setup lang="ts">
import RecipeOrganizerPage from "~/components/Domain/Recipe/RecipeOrganizerPage.vue";
import { useCategoryStore } from "~/composables/store";
export default defineNuxtComponent({
components: {
RecipeOrganizerPage,
},
definePageMeta({
middleware: ["group-only"],
setup() {
const { store, actions } = useCategoryStore();
const i18n = useI18n();
});
useSeoMeta({
title: i18n.t("category.categories"),
});
const { store, actions } = useCategoryStore();
const i18n = useI18n();
return {
store,
actions,
};
},
useSeoMeta({
title: i18n.t("category.categories"),
});
</script>

View File

@@ -17,7 +17,7 @@
{{ $t('recipe-finder.recipe-finder-description') }}
</template>
</BasePageTitle>
<v-container v-if="ready">
<v-container v-if="state.ready">
<v-row>
<v-col :cols="useMobile ? 12 : 3">
<v-container class="ma-0 pa-0">
@@ -51,38 +51,38 @@
</SearchFilter>
<div :class="attrs.searchFilter.filterClass">
<v-badge
:model-value="!!queryFilterJSON.parts && queryFilterJSON.parts.length > 0"
:model-value="!!state.queryFilterJSON.parts && state.queryFilterJSON.parts.length > 0"
size="small"
color="primary"
:content="(queryFilterJSON.parts || []).length"
:content="(state.queryFilterJSON.parts || []).length"
>
<v-btn
size="small"
color="accent"
dark
@click="queryFilterMenu = !queryFilterMenu"
@click="state.queryFilterMenu = !state.queryFilterMenu"
>
<v-icon start>
{{ $globals.icons.filter }}
</v-icon>
{{ $t("recipe-finder.other-filters") }}
<BaseDialog
v-model="queryFilterMenu"
v-model="state.queryFilterMenu"
:title="$t('recipe-finder.other-filters')"
:icon="$globals.icons.filter"
width="100%"
max-width="1100px"
:submit-disabled="!queryFilterEditorValue"
:submit-disabled="!state.queryFilterEditorValue"
can-confirm
@confirm="saveQueryFilter"
>
<v-card-text>
<QueryFilterBuilder
:key="queryFilterMenuKey"
:initial-query-filter="queryFilterJSON"
:key="state.queryFilterMenuKey"
:initial-query-filter="state.queryFilterJSON"
:field-defs="queryFilterBuilderFields"
@input="(value) => queryFilterEditorValue = value"
@input-j-s-o-n="(value) => queryFilterEditorValueJSON = value"
@input="(value) => state.queryFilterEditorValue = value"
@input-j-s-o-n="(value) => state.queryFilterEditorValueJSON = value"
/>
</v-card-text>
<template #custom-card-action>
@@ -113,7 +113,7 @@
:class="attrs.settings.colClass"
>
<v-menu
v-model="settingsMenu"
v-model="state.settingsMenu"
offset-y
nudge-bottom="3"
:close-on-content-click="false"
@@ -135,7 +135,7 @@
<v-card-text>
<div>
<v-number-input
v-model="settings.maxMissingFoods"
v-model="state.settings.maxMissingFoods"
:precision="null"
:min="0"
control-variant="stacked"
@@ -144,7 +144,7 @@
:label="$t('recipe-finder.max-missing-ingredients')"
/>
<v-number-input
v-model="settings.maxMissingTools"
v-model="state.settings.maxMissingTools"
:precision="null"
:min="0"
control-variant="stacked"
@@ -157,7 +157,7 @@
<div class="mt-1">
<v-checkbox
v-if="isOwnGroup"
v-model="settings.includeFoodsOnHand"
v-model="state.settings.includeFoodsOnHand"
density="compact"
size="small"
hide-details
@@ -166,7 +166,7 @@
/>
<v-checkbox
v-if="isOwnGroup"
v-model="settings.includeToolsOnHand"
v-model="state.settings.includeToolsOnHand"
density="compact"
size="small"
hide-details
@@ -328,7 +328,7 @@
:recipe="item.recipe"
:missing-foods="item.missingFoods"
:missing-tools="item.missingTools"
:disable-checkbox="loading"
:disable-checkbox="state.loading"
@add-food="addFood"
@remove-food="removeFood"
@add-tool="addTool"
@@ -356,7 +356,7 @@
:recipe="item.recipe"
:missing-foods="item.missingFoods"
:missing-tools="item.missingTools"
:disable-checkbox="loading"
:disable-checkbox="state.loading"
@add-food="addFood"
@remove-food="removeFood"
@add-tool="addTool"
@@ -366,7 +366,7 @@
</v-col>
</v-row>
</v-container>
<v-container v-else-if="!recipesReady">
<v-container v-else-if="!state.recipesReady">
<v-row>
<v-col
cols="12"
@@ -411,7 +411,7 @@
</v-container>
</template>
<script lang="ts">
<script setup lang="ts">
import { watchDebounced } from "@vueuse/core";
import { useUserApi } from "~/composables/api";
import { usePublicExploreApi } from "~/composables/api/api-client";
@@ -431,279 +431,257 @@ interface RecipeSuggestions {
missingItems: RecipeSuggestionResponseItem[];
}
export default defineNuxtComponent({
components: { QueryFilterBuilder, RecipeSuggestion, SearchFilter },
setup() {
const display = useDisplay();
const i18n = useI18n();
const auth = useMealieAuth();
const route = useRoute();
const display = useDisplay();
const i18n = useI18n();
const auth = useMealieAuth();
const route = useRoute();
useSeoMeta({
title: i18n.t("recipe-finder.recipe-finder"),
});
useSeoMeta({
title: i18n.t("recipe-finder.recipe-finder"),
});
const useMobile = computed(() => display.smAndDown.value);
const useMobile = computed(() => display.smAndDown.value);
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const { isOwnGroup } = useLoggedInState();
const api = isOwnGroup.value ? useUserApi() : usePublicExploreApi(groupSlug.value).explore;
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.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: 20,
},
});
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 = [...selectedFoods.value, food];
handleFoodUpdates();
}
function removeFood(food: IngredientFood) {
selectedFoods.value = selectedFoods.value.filter(f => f.id !== food.id);
handleFoodUpdates();
}
function handleFoodUpdates() {
selectedFoods.value.sort((a, b) => (a.pluralName || a.name).localeCompare(b.pluralName || b.name));
preferences.value.foodIds = selectedFoods.value.map(food => food.id);
}
watch(
() => selectedFoods.value,
() => {
handleFoodUpdates();
},
);
const toolStore = isOwnGroup.value ? useToolStore() : usePublicToolStore(groupSlug.value);
const selectedTools = ref<RecipeTool[]>([]);
function addTool(tool: RecipeTool) {
selectedTools.value = [...selectedTools.value, tool];
handleToolUpdates();
}
function removeTool(tool: RecipeTool) {
selectedTools.value = selectedTools.value.filter(t => t.id !== tool.id);
handleToolUpdates();
}
function handleToolUpdates() {
selectedTools.value.sort((a, b) => a.name.localeCompare(b.name));
preferences.value.toolIds = selectedTools.value.map(tool => tool.id);
}
watch(
() => selectedTools.value,
() => {
handleToolUpdates();
},
);
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.t("category.categories"),
type: Organizer.Category,
},
{
name: "tags.id",
label: i18n.t("tag.tags"),
type: Organizer.Tag,
},
{
name: "household_id",
label: i18n.t("household.households"),
type: Organizer.Household,
},
{
name: "user_id",
label: i18n.t("user.users"),
type: Organizer.User,
},
{
name: "last_made",
label: i18n.t("general.last-made"),
type: "relativeDate",
},
];
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,
};
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: 20,
},
});
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 foods = foodStore.store.value;
const selectedFoods = ref<IngredientFood[]>([]);
function addFood(food: IngredientFood) {
selectedFoods.value = [...selectedFoods.value, food];
handleFoodUpdates();
}
function removeFood(food: IngredientFood) {
selectedFoods.value = selectedFoods.value.filter(f => f.id !== food.id);
handleFoodUpdates();
}
function handleFoodUpdates() {
selectedFoods.value.sort((a, b) => (a.pluralName || a.name).localeCompare(b.pluralName || b.name));
preferences.value.foodIds = selectedFoods.value.map(food => food.id);
}
watch(
() => selectedFoods.value,
() => {
handleFoodUpdates();
},
);
const toolStore = isOwnGroup.value ? useToolStore() : usePublicToolStore(groupSlug.value);
const tools = toolStore.store.value;
const selectedTools = ref<RecipeTool[]>([]);
function addTool(tool: RecipeTool) {
selectedTools.value = [...selectedTools.value, tool];
handleToolUpdates();
}
function removeTool(tool: RecipeTool) {
selectedTools.value = selectedTools.value.filter(t => t.id !== tool.id);
handleToolUpdates();
}
function handleToolUpdates() {
selectedTools.value.sort((a, b) => a.name.localeCompare(b.name));
preferences.value.toolIds = selectedTools.value.map(tool => tool.id);
}
watch(
() => selectedTools.value,
() => {
handleToolUpdates();
},
);
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.t("category.categories"),
type: Organizer.Category,
},
{
name: "tags.id",
label: i18n.t("tag.tags"),
type: Organizer.Tag,
},
{
name: "household_id",
label: i18n.t("household.households"),
type: Organizer.Household,
},
{
name: "user_id",
label: i18n.t("user.users"),
type: Organizer.User,
},
{
name: "last_made",
label: i18n.t("general.last-made"),
type: "relativeDate",
},
];
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;
}
</script>

View File

@@ -15,27 +15,18 @@
</v-container>
</template>
<script lang="ts">
<script setup lang="ts">
import RecipeOrganizerPage from "~/components/Domain/Recipe/RecipeOrganizerPage.vue";
import { useTagStore } from "~/composables/store";
export default defineNuxtComponent({
components: {
RecipeOrganizerPage,
},
definePageMeta({
middleware: ["group-only"],
setup() {
const { store, actions } = useTagStore();
const i18n = useI18n();
});
useSeoMeta({
title: i18n.t("tag.tags"),
});
const { store, actions } = useTagStore();
const i18n = useI18n();
return {
store,
actions,
};
},
useSeoMeta({
title: i18n.t("tag.tags"),
});
</script>

View File

@@ -30,41 +30,33 @@
</div>
</template>
<script lang="ts">
<script setup lang="ts">
import { useUserApi } from "~/composables/api";
import RecipeTimeline from "~/components/Domain/Recipe/RecipeTimeline.vue";
export default defineNuxtComponent({
components: { RecipeTimeline },
definePageMeta({
middleware: ["group-only"],
setup() {
const i18n = useI18n();
const api = useUserApi();
const ready = ref<boolean>(false);
useSeoMeta({
title: i18n.t("recipe.timeline"),
});
const groupName = ref<string>("");
const queryFilter = ref<string>("");
async function fetchHousehold() {
const { data } = await api.households.getCurrentUserHousehold();
if (data) {
queryFilter.value = `recipe.group_id="${data.groupId}"`;
groupName.value = data.group;
}
ready.value = true;
}
useAsyncData("house-hold", fetchHousehold);
return {
groupName,
queryFilter,
ready,
};
},
});
const i18n = useI18n();
const api = useUserApi();
const ready = ref<boolean>(false);
useSeoMeta({
title: i18n.t("recipe.timeline"),
});
const groupName = ref<string>("");
const queryFilter = ref<string>("");
async function fetchHousehold() {
const { data } = await api.households.getCurrentUserHousehold();
if (data) {
queryFilter.value = `recipe.group_id="${data.groupId}"`;
groupName.value = data.group;
}
ready.value = true;
}
useAsyncData("house-hold", fetchHousehold);
</script>

View File

@@ -15,7 +15,7 @@
</v-container>
</template>
<script lang="ts">
<script setup lang="ts">
import RecipeOrganizerPage from "~/components/Domain/Recipe/RecipeOrganizerPage.vue";
import { useToolStore } from "~/composables/store";
import type { RecipeTool } from "~/lib/api/types/recipe";
@@ -24,56 +24,44 @@ interface RecipeToolWithOnHand extends RecipeTool {
onHand: boolean;
}
export default defineNuxtComponent({
components: {
RecipeOrganizerPage,
},
definePageMeta({
middleware: ["group-only"],
setup() {
const auth = useMealieAuth();
const toolStore = useToolStore();
const dialog = ref(false);
const i18n = useI18n();
useSeoMeta({
title: i18n.t("tool.tools"),
});
const userHousehold = computed(() => auth.user.value?.householdSlug || "");
const tools = computed(() => toolStore.store.value.map(tool => (
{
...tool,
onHand: tool.householdsWithTool?.includes(userHousehold.value) || false,
} as RecipeToolWithOnHand
)));
async function deleteOne(id: string | number) {
await toolStore.actions.deleteOne(id);
}
async function updateOne(tool: RecipeToolWithOnHand) {
if (userHousehold.value) {
if (tool.onHand && !tool.householdsWithTool?.includes(userHousehold.value)) {
if (!tool.householdsWithTool) {
tool.householdsWithTool = [userHousehold.value];
}
else {
tool.householdsWithTool.push(userHousehold.value);
}
}
else if (!tool.onHand && tool.householdsWithTool?.includes(userHousehold.value)) {
tool.householdsWithTool = tool.householdsWithTool.filter(household => household !== userHousehold.value);
}
}
await toolStore.actions.updateOne(tool);
}
return {
dialog,
tools,
deleteOne,
updateOne,
};
},
});
const auth = useMealieAuth();
const toolStore = useToolStore();
const i18n = useI18n();
useSeoMeta({
title: i18n.t("tool.tools"),
});
const userHousehold = computed(() => auth.user.value?.householdSlug || "");
const tools = computed(() => toolStore.store.value.map(tool => (
{
...tool,
onHand: tool.householdsWithTool?.includes(userHousehold.value) || false,
} as RecipeToolWithOnHand
)));
async function deleteOne(id: string | number) {
await toolStore.actions.deleteOne(id);
}
async function updateOne(tool: RecipeToolWithOnHand) {
if (userHousehold.value) {
if (tool.onHand && !tool.householdsWithTool?.includes(userHousehold.value)) {
if (!tool.householdsWithTool) {
tool.householdsWithTool = [userHousehold.value];
}
else {
tool.householdsWithTool.push(userHousehold.value);
}
}
else if (!tool.onHand && tool.householdsWithTool?.includes(userHousehold.value)) {
tool.householdsWithTool = tool.householdsWithTool.filter(household => household !== userHousehold.value);
}
}
await toolStore.actions.updateOne(tool);
}
</script>