Use exportet js functions

This commit is contained in:
Francesco Lorenzo D'Amico
2025-06-02 12:35:04 +02:00
parent 258ffb782f
commit 006ffc5ba3
3 changed files with 80 additions and 304 deletions
@@ -19,11 +19,11 @@
<input type="file" name="InstructionViewModel.Instructions[@i].MediaFile" class="instruction-file" />
<textarea name="InstructionViewModel.Instructions[@i].Description" placeholder="Beschreibung" class="form-control">@Model.Instructions[i].Description</textarea>
<button type="button" class="btn-delete" onclick="removeInstruction('@Model.Instructions[i].Id', '@Model.RecipeId',)">🗑️</button>
<button type="button" class="btn-delete" onclick="Francesco.removeInstruction('@Model.Instructions[i].Id', '@Model.RecipeId')">🗑️</button>
</div>
<div class="instruction-actions">
<button type="button" class="btn-move-up" onclick="moveInstructionUp('@Model.Instructions[i].Id', '@Model.RecipeId')">⬆️</button>
<button type="button" class="btn-move-down" onclick="moveInstructionDown('@Model.Instructions[i].Id', '@Model.RecipeId')">⬇️</button>
<button type="button" class="btn-move-up" onclick="Francesco.moveInstructionUp('@Model.Instructions[i].Id', '@Model.RecipeId')">⬆️</button>
<button type="button" class="btn-move-down" onclick="Francesco.moveInstructionDown('@Model.Instructions[i].Id', '@Model.RecipeId')">⬇️</button>
</div>
</div>
}
@@ -32,7 +32,7 @@
<button type="button" class="btn-add" onclick="addInstruction()">Schritte hinzufügen</button>
<button type="button" class="btn-add" onclick="Francesco.addInstruction()">Schritte hinzufügen</button>
@@ -20,12 +20,14 @@
}
}
</select>
<button type="button" class="btn-delete" onclick="removeIngredient('@Model.Ingredients[i].Id')">🗑️</button>
<button type="button" class="btn-delete" onclick="Francesco.removeIngredient('@Model.Ingredients[i].Id')">🗑️</button>
</div>
</div>
}
</div>
<button type="button" class="btn-add" onclick="addIngredient()">Zutat hinzufügen</button>
<button type="button" class="btn-add" onclick="Francesco.addIngredient()">Zutat hinzufügen</button>
@@ -49,7 +49,7 @@
<div class="position-relative">
<div class="position-absolute top-0 end-0 p-2">
<button class="btn btn-sm btn-link text-dark" title="Rezept entfernen"
onclick="removeRecipe('@recipe.Id');">
onclick="Francesco.removeRecipe('@recipe.Id');">
<i class="bi bi-trash" style="font-size: 1.2rem;"></i>
</button>
</div>
@@ -87,7 +87,7 @@
<div class="card-body">
<ul id="ingredientList" class="list-group"></ul>
<div class="text-center mt-3">
<button id="removeSelectedButton" class="btn" onclick="removeSelectedIngredients()">
<button id="removeSelectedButton" class="btn" onclick="Francesco.removeSelectedIngredients()">
ENTFERNE MARKIERTE
</button>
</div>
@@ -96,237 +96,11 @@
</div>
</div>
@section Scripts {
@Html.AntiForgeryToken()
<script>
const selectedIngredients = new Set();
const recipeIngredients = @Html.Raw(recipeIngredientsJson);
let activeRecipeId = Object.keys(recipeIngredients)[0];
async function updateRecipeCount() {
try {
const response = await fetch('/ShoppingList/RecipeCount');
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
document.getElementById('recipeCount').textContent = data.count;
} catch (err) {
console.error("Fehler beim Aktualisieren der Rezeptanzahl:", err);
}
}
const countUpdateInterval = setInterval(updateRecipeCount, 5000);
document.addEventListener('shopping-list-changed', function() {
updateRecipeCount();
});
window.addEventListener('beforeunload', function() {
clearInterval(countUpdateInterval);
});
document.getElementById('carouselLeft').onclick = function() {
document.getElementById('recipeCarousel').scrollBy({ left: -200, behavior: 'smooth' });
};
document.getElementById('carouselRight').onclick = function() {
document.getElementById('recipeCarousel').scrollBy({ left: 200, behavior: 'smooth' });
};
function renderIngredientList(recipeId) {
const list = document.getElementById('ingredientList');
list.innerHTML = '';
const ingredients = recipeIngredients[recipeId] || [];
if (ingredients.length === 0) {
list.innerHTML = '<li class="list-group-item text-muted">Keine Zutaten vorhanden.</li>';
return;
}
ingredients.forEach(ingredient => {
const isSelected = selectedIngredients.has(ingredient.id);
const li = document.createElement('li');
li.className = 'list-group-item d-flex justify-content-between align-items-center';
if (isSelected) {
li.classList.add('selected-ingredient');
}
li.innerHTML = `
<span>
<strong>${ingredient.name}</strong>
<span class="text-secondary ms-2">${ingredient.amount} ${ingredient.unit}</span>
</span>
<button class="btn btn-sm btn-outline-danger" title="Zutat entfernen" onclick="toggleIngredientSelection('${ingredient.id}', this); event.stopPropagation();" ${isSelected ? '' : ''}>
<i class="bi bi-dash"></i>
</button>
`;
list.appendChild(li);
});
updateRemoveSelectedButton();
}
function setActiveCard(recipeId) {
document.querySelectorAll('.recipe-card').forEach(card => {
card.classList.toggle('active-recipe-card', card.dataset.recipeId === recipeId);
});
activeRecipeId = recipeId;
renderIngredientList(recipeId);
}
function toggleIngredientSelection(ingredientId, button) {
const listItem = button.closest('li');
if (selectedIngredients.has(ingredientId)) {
selectedIngredients.delete(ingredientId);
listItem.classList.remove('selected-ingredient');
} else {
selectedIngredients.add(ingredientId);
listItem.classList.add('selected-ingredient');
}
updateRemoveSelectedButton();
}
function updateRemoveSelectedButton() {
document.getElementById('removeSelectedButton').style.display =
selectedIngredients.size > 0 ? 'inline-block' : 'none';
}
async function removeSelectedIngredients() {
if (selectedIngredients.size === 0) return;
const shoppingListIds = [];
selectedIngredients.forEach(ingredientId => {
for (const recipeId in recipeIngredients) {
const ingredients = recipeIngredients[recipeId];
const ingredient = ingredients.find(ing => ing.id === ingredientId);
if (ingredient && ingredient.shoppingListId &&
ingredient.shoppingListId !== "00000000-0000-0000-0000-000000000000") {
shoppingListIds.push(ingredient.shoppingListId);
}
}
});
if (shoppingListIds.length === 0) {
console.warn("Keine gültigen Shopping List IDs gefunden");
return;
}
try {
const response = await fetch('/ShoppingList/RemoveIngredients', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'RequestVerificationToken': document.querySelector('input[name="__RequestVerificationToken"]').value,
'Cache-Control': 'no-cache',
'Pragma': 'no-cache'
},
body: JSON.stringify(shoppingListIds)
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
window.location.reload();
} else {
console.error("Fehler beim Entfernen der Zutaten:", result.error);
alert("Beim Entfernen der Zutaten ist ein Fehler aufgetreten.");
}
} catch (err) {
console.error("Fehler beim Entfernen der Zutaten:", err);
alert("Beim Entfernen der Zutaten ist ein Fehler aufgetreten. Bitte versuchen Sie es später erneut.");
}
}
document.addEventListener('DOMContentLoaded', function() {
if (activeRecipeId) {
setActiveCard(activeRecipeId);
}
document.querySelectorAll('.recipe-card').forEach(card => {
card.addEventListener('click', function() {
setActiveCard(this.dataset.recipeId);
});
});
});
async function removeRecipe(recipeId) {
let confirmed = false;
if (window.Swal) {
const result = await Swal.fire({
title: 'Rezept entfernen?',
text: 'Möchten Sie dieses Rezept wirklich aus der Einkaufsliste entfernen?',
icon: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja, entfernen',
cancelButtonText: 'Abbrechen',
confirmButtonColor: '#d33',
cancelButtonColor: '#3085d6'
});
confirmed = result.isConfirmed;
} else {
confirmed = confirm('Möchten Sie dieses Rezept wirklich aus der Einkaufsliste entfernen?');
}
if (!confirmed) return;
try {
const tokenElement = document.querySelector('input[name="__RequestVerificationToken"]');
if (!tokenElement) {
console.error('Anti-forgery token not found');
alert('Fehler: Anti-Forgery Token nicht gefunden');
return;
}
const response = await fetch(`/ShoppingList/RemoveRecipeFromList/${recipeId}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'RequestVerificationToken': tokenElement.value
}
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result = await response.json();
if (result.success) {
if (window.Swal) {
await Swal.fire({
title: 'Erfolgreich!',
text: 'Das Rezept wurde entfernt.',
icon: 'success',
timer: 1500,
showConfirmButton: false
});
} else {
alert('Das Rezept wurde erfolgreich entfernt.');
}
window.location.reload();
} else {
const errorMsg = result.error || 'Unbekannter Fehler';
console.error('Fehler beim Entfernen:', errorMsg);
if (window.Swal) {
await Swal.fire({
title: 'Fehler',
text: errorMsg,
icon: 'error'
});
} else {
alert('Fehler: ' + errorMsg);
}
}
} catch (err) {
console.error('Fehler beim Entfernen des Rezepts:', err);
if (window.Swal) {
await Swal.fire({
title: 'Fehler',
text: 'Beim Löschen ist ein Fehler aufgetreten.',
icon: 'error'
});
} else {
alert('Beim Löschen ist ein Fehler aufgetreten.');
}
}
}
window.recipeIngredients = @Html.Raw(recipeIngredientsJson);
</script>
<script src="~/js/site.js"></script>
}