Files
mealie/frontend/app/components/Domain/Recipe/RecipeContextMenu/RecipeContextMenuContent.vue
T

476 lines
13 KiB
Vue

<template>
<RecipeDialogShare v-model="shareDialog" :recipe-id="recipeId" :name="name" />
<RecipeDialogPrintPreferences v-model="printPreferencesDialog" :recipe="recipeRef" />
<BaseDialog
v-model="recipeDeleteDialog"
bottom-sheet
:title="$t('recipe.delete-recipe')"
color="error"
:icon="$globals.icons.alertCircle"
can-confirm
@confirm="deleteRecipe()"
>
<v-card-text>
<template v-if="isAdminAndNotOwner">
{{ $t("recipe.admin-delete-confirmation") }}
</template>
<template v-else>
{{ $t("recipe.delete-confirmation") }}
</template>
</v-card-text>
</BaseDialog>
<BaseDialog
v-model="recipeDuplicateDialog"
bottom-sheet
:title="$t('recipe.duplicate')"
color="primary"
:icon="$globals.icons.duplicate"
can-confirm
@confirm="duplicateRecipe()"
>
<v-card-text>
<v-text-field
v-model="recipeName"
density="compact"
:label="$t('recipe.recipe-name')"
autofocus
/>
</v-card-text>
</BaseDialog>
<MealPlanAddRecipeDialog v-model="mealplannerDialog" :recipe-id="recipeId" :recipe-scale="recipeScale" />
<RecipeDialogAddToShoppingList
v-if="shoppingLists && recipeRefWithScale"
v-model="shoppingListDialog"
:recipes="[recipeRefWithScale]"
:shopping-lists="shoppingLists"
@list-created="addShoppingList"
/>
<v-list density="compact">
<v-list-item v-for="(item, index) in menuItems" :key="index" @click="contextMenuEventHandler(item.event)">
<template #prepend>
<v-icon :color="item.color">
{{ item.icon }}
</v-icon>
</template>
<v-list-item-title>{{ item.title }}</v-list-item-title>
</v-list-item>
<div v-if="useItems.recipeActions && recipeActions && recipeActions.length">
<v-divider />
<v-list-item
v-for="(action, index) in recipeActions"
:key="index"
@click="executeRecipeAction(action)"
>
<template #prepend>
<v-icon color="undefined">
{{ $globals.icons.linkVariantPlus }}
</v-icon>
</template>
<v-list-item-title>
{{ action.title }}
</v-list-item-title>
</v-list-item>
</div>
</v-list>
</template>
<script setup lang="ts">
import { useClipboard, useShare } from "@vueuse/core";
import RecipeDialogAddToShoppingList from "~/components/Domain/Recipe/RecipeDialogAddToShoppingList.vue";
import RecipeDialogPrintPreferences from "~/components/Domain/Recipe/RecipeDialogPrintPreferences.vue";
import RecipeDialogShare from "~/components/Domain/Recipe/RecipeDialogShare.vue";
import { useUserApi } from "~/composables/api";
import { useDownloader } from "~/composables/api/use-downloader";
import { useAddToShoppingListDialog } from "~/composables/shopping-list-page/use-add-to-shopping-list-dialog";
import { useGroupRecipeActions } from "~/composables/use-group-recipe-actions";
import { useGroupSelf } from "~/composables/use-groups";
import { useHouseholdSelf } from "~/composables/use-households";
import { useLoggedInState } from "~/composables/use-logged-in-state";
import { alert, loader } from "~/composables/use-toast";
import type { GroupRecipeActionOut, HouseholdSummary } from "~/lib/api/types/household";
import type { RecipeOut } from "~/lib/api/types/recipe";
import { isRecipeFullyPublic } from "~/lib/recipe/recipe-visibility";
export interface ContextMenuIncludes {
delete: boolean;
edit: boolean;
download: boolean;
downloadPdf: boolean;
duplicate: boolean;
mealplanner: boolean;
shoppingList: boolean;
print: boolean;
printPreferences: boolean;
share: boolean;
recipeActions: boolean;
}
export interface ContextMenuItem {
title: string;
icon: string;
color: string | undefined;
event: string;
isPublic: boolean;
}
interface Props {
useItems?: ContextMenuIncludes;
appendItems?: ContextMenuItem[];
leadingItems?: ContextMenuItem[];
menuTop?: boolean;
fab?: boolean;
color?: string;
slug: string;
menuIcon?: string | null;
name: string;
recipe?: RecipeOut;
recipeId: string;
recipeScale?: number;
}
const props = withDefaults(defineProps<Props>(), {
useItems: () => ({
delete: true,
edit: true,
download: true,
downloadPdf: true,
duplicate: false,
mealplanner: true,
shoppingList: true,
print: true,
printPreferences: true,
share: true,
recipeActions: true,
}),
appendItems: () => [],
leadingItems: () => [],
menuTop: true,
fab: false,
color: "primary",
menuIcon: null,
recipe: undefined,
recipeScale: 1,
});
const emit = defineEmits<{
[key: string]: any;
deleted: [slug: string];
print: [];
mealplanEdit: [];
mealplanRemove: [];
}>();
const api = useUserApi();
const { open: shoppingListDialog, shoppingLists, getShoppingLists, addShoppingList } = useAddToShoppingListDialog();
const printPreferencesDialog = ref(false);
const shareDialog = ref(false);
const recipeDeleteDialog = ref(false);
const mealplannerDialog = ref(false);
const recipeDuplicateDialog = ref(false);
const recipeName = ref(props.name);
const loading = ref(false);
const menuItems = ref<ContextMenuItem[]>([]);
const i18n = useI18n();
const auth = useMealieAuth();
const { $globals } = useNuxtApp();
const { group, actions: groupActions } = useGroupSelf();
const { household } = useHouseholdSelf();
const { isOwnGroup } = useLoggedInState();
const route = useRoute();
const groupSlug = computed(() => route.params.groupSlug as string || auth.user.value?.groupSlug || "");
const { share, isSupported: shareIsSupported } = useShare();
const { copy, copied, isSupported: clipboardIsSupported } = useClipboard({ legacy: true });
function getPlainRecipeLink() {
return `${window.location.origin}/g/${groupSlug.value}/r/${props.slug}`;
}
async function sharePlainLink() {
if (shareIsSupported.value) {
await share({
title: props.name,
url: getPlainRecipeLink(),
});
return;
}
if (!clipboardIsSupported.value) {
alert.error(i18n.t("general.clipboard-not-supported") as string);
return;
}
await copy(getPlainRecipeLink());
alert[copied.value ? "success" : "error"](
i18n.t(copied.value ? "recipe-share.recipe-link-copied-message" : "general.clipboard-copy-failure") as string,
);
}
// ===========================================================================
// Context Menu Setup
const defaultItems: { [key: string]: ContextMenuItem } = {
edit: {
title: i18n.t("general.edit"),
icon: $globals.icons.edit,
color: undefined,
event: "edit",
isPublic: false,
},
delete: {
title: i18n.t("general.delete"),
icon: $globals.icons.delete,
color: undefined,
event: "delete",
isPublic: false,
},
download: {
title: i18n.t("general.download"),
icon: $globals.icons.download,
color: undefined,
event: "download",
isPublic: false,
},
downloadPdf: {
title: i18n.t("recipe.download-pdf"),
icon: $globals.icons.filePDF,
color: undefined,
event: "downloadPdf",
isPublic: false,
},
duplicate: {
title: i18n.t("general.duplicate"),
icon: $globals.icons.duplicate,
color: undefined,
event: "duplicate",
isPublic: false,
},
mealplanner: {
title: i18n.t("recipe.add-to-plan"),
icon: $globals.icons.calendar,
color: undefined,
event: "mealplanner",
isPublic: false,
},
shoppingList: {
title: i18n.t("recipe.add-to-list"),
icon: $globals.icons.cartCheck,
color: undefined,
event: "shoppingList",
isPublic: false,
},
print: {
title: i18n.t("general.print"),
icon: $globals.icons.printer,
color: undefined,
event: "print",
isPublic: true,
},
printPreferences: {
title: i18n.t("general.print-preferences"),
icon: $globals.icons.printerSettings,
color: undefined,
event: "printPreferences",
isPublic: true,
},
share: {
title: i18n.t("general.share"),
icon: $globals.icons.shareVariant,
color: undefined,
event: "share",
isPublic: false,
},
};
// Add leading and Appending Items
menuItems.value = [...menuItems.value, ...props.leadingItems, ...props.appendItems];
// ===========================================================================
// Context Menu Event Handler
const recipeRef = ref<RecipeOut | undefined>(props.recipe);
const recipeRefWithScale = computed(() =>
recipeRef.value ? { scale: props.recipeScale, ...recipeRef.value } : undefined,
);
// the recipe may belong to another household in our group, so we can't reuse the current user's
const recipeHousehold = ref<HouseholdSummary | undefined>();
async function refreshRecipeHousehold() {
const householdId = recipeRef.value?.householdId;
if (!householdId || !isOwnGroup.value) {
recipeHousehold.value = undefined;
return;
}
if (householdId === recipeHousehold.value?.id) {
return;
}
if (householdId === household.value?.id) {
recipeHousehold.value = household.value;
return;
}
const { data } = await api.households.getOne(householdId);
recipeHousehold.value = data || undefined;
}
watch(() => recipeRef.value?.householdId, refreshRecipeHousehold, { immediate: true });
const isFullyPublic = computed(() =>
isRecipeFullyPublic(recipeRef.value, group.value, recipeHousehold.value),
);
const isAdminAndNotOwner = computed(() => {
return (
auth.user.value?.admin
&& auth.user.value?.id !== recipeRef.value?.userId
);
});
const canDelete = computed(() => {
const user = auth.user.value;
const recipe = recipeRef.value;
return user && recipe && (user.admin || user.id === recipe.userId);
});
// Get Default Menu Items Specified in Props
for (const [key, value] of Object.entries(props.useItems)) {
if (!value) continue;
// Skip delete if not allowed
if (key === "delete" && !canDelete.value) continue;
const item = defaultItems[key];
if (item && (item.isPublic || isOwnGroup.value)) {
menuItems.value.push(item);
}
}
async function refreshRecipe() {
const { data } = await api.recipes.getOne(props.slug);
if (data) {
recipeRef.value = data;
}
}
const router = useRouter();
const groupRecipeActionsStore = useGroupRecipeActions();
async function executeRecipeAction(action: GroupRecipeActionOut) {
if (!props.recipe) return;
const response = await groupRecipeActionsStore.execute(action, props.recipe, props.recipeScale);
if (action.actionType === "post") {
if (!response?.error) {
alert.success(i18n.t("events.message-sent"));
}
else {
alert.error(i18n.t("events.something-went-wrong"));
}
}
}
async function deleteRecipe() {
const { data } = await api.recipes.deleteOne(props.slug);
if (data?.slug) {
router.push(`/g/${groupSlug.value}`);
}
emit("deleted", props.slug);
}
const download = useDownloader();
async function handleDownloadEvent() {
const { data: shareToken } = await api.recipes.share.createOne({ recipeId: props.recipeId });
if (!shareToken) {
console.error("No share token received");
alert.error(i18n.t("events.something-went-wrong"));
return;
}
download(api.recipes.share.getZipRedirectUrl(shareToken.id), `${props.slug}.zip`);
}
async function handleDownloadPdfEvent() {
// The menu closes on click, so a toast is the only place left to show that a PDF is coming.
loader.info(i18n.t("recipe.preparing-pdf"));
try {
await download(api.recipes.getPdfUrl(props.slug), `${props.slug}.pdf`);
}
finally {
loader.close();
}
}
async function duplicateRecipe() {
const { data } = await api.recipes.duplicateOne(props.slug, recipeName.value);
if (data && data.slug) {
router.push(`/g/${groupSlug.value}/r/${data.slug}`);
}
}
// Note: Print is handled as an event in the parent component
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type
const eventHandlers: { [key: string]: () => void | Promise<any> } = {
delete: () => {
recipeDeleteDialog.value = true;
},
edit: () => router.push(`/g/${groupSlug.value}/r/${props.slug}` + "?edit=true"),
download: handleDownloadEvent,
downloadPdf: handleDownloadPdfEvent,
duplicate: () => {
recipeDuplicateDialog.value = true;
},
mealplanner: () => {
mealplannerDialog.value = true;
},
printPreferences: async () => {
if (!recipeRef.value) {
await refreshRecipe();
}
printPreferencesDialog.value = true;
},
shoppingList: () => {
const promises: Promise<void>[] = [getShoppingLists()];
if (!recipeRef.value) {
promises.push(refreshRecipe());
}
Promise.allSettled(promises).then(() => {
shoppingListDialog.value = true;
});
},
share: async () => {
// resolve everything the visibility check needs, so we don't fall back to a
// share token just because the recipe/group/household hadn't loaded yet
if (!recipeRef.value) {
await refreshRecipe();
}
if (!group.value) {
await groupActions.refresh();
}
await refreshRecipeHousehold();
if (isFullyPublic.value) {
await sharePlainLink();
}
else {
shareDialog.value = true;
}
},
};
function contextMenuEventHandler(eventKey: string) {
const handler = eventHandlers[eventKey];
if (handler && typeof handler === "function") {
handler();
loading.value = false;
return;
}
emit(eventKey);
loading.value = false;
}
const recipeActions = groupRecipeActionsStore.recipeActions;
</script>