Add meal plan editor
Some checks failed
Build and Deploy / build-and-push (push) Failing after 1m19s
Some checks failed
Build and Deploy / build-and-push (push) Failing after 1m19s
This commit is contained in:
@@ -3,6 +3,7 @@ import { getFilterHTML, setupFilter } from './views/Filter.js?v=2';
|
||||
import { getRecipeDetailHTML, setupRecipeDetail } from './views/RecipeDetailV2.js?v=2';
|
||||
import { getMealPlannerHTML, setupMealPlanner } from './views/MealPlanner.js?v=2';
|
||||
import { getPantryHTML, refreshPantry, setupPantry } from './views/Pantry.js?v=2';
|
||||
import { getMealPlanEditorHTML, setupMealPlanEditor } from './ui/mealPlanEditor.js?v=2';
|
||||
|
||||
function getAppToastHTML() {
|
||||
return `
|
||||
@@ -105,6 +106,7 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
${getBottomNavHTML()}
|
||||
${getRecipeDetailHTML()}
|
||||
${getFilterHTML()}
|
||||
${getMealPlanEditorHTML()}
|
||||
${getAppToastHTML()}
|
||||
`;
|
||||
|
||||
@@ -114,5 +116,6 @@ document.addEventListener('DOMContentLoaded', () => {
|
||||
setupMealPlanner();
|
||||
setupPantry();
|
||||
setupFilter();
|
||||
setupMealPlanEditor();
|
||||
setupRecipeDetail();
|
||||
});
|
||||
|
||||
@@ -13,27 +13,79 @@ export function dayHasAnyMeal(plans, d) {
|
||||
});
|
||||
}
|
||||
|
||||
function hasCustomizations(entry) {
|
||||
return (entry.excludedIngredients?.length > 0) ||
|
||||
(entry.amountOverrides && Object.keys(entry.amountOverrides).length > 0) ||
|
||||
(entry.addedIngredients?.length > 0) ||
|
||||
(entry.substitutions && Object.keys(entry.substitutions).length > 0);
|
||||
}
|
||||
|
||||
function nutritionForAmountRaw(ingredientId, amount, unit) {
|
||||
const def = INGREDIENTS[ingredientId];
|
||||
if (!def?.nutritionPer100g) return null;
|
||||
let g = amount;
|
||||
if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) g = amount * def.weightPerPiece;
|
||||
const f = g / 100;
|
||||
return {
|
||||
kcal: def.nutritionPer100g.kcal * f,
|
||||
protein: def.nutritionPer100g.protein * f,
|
||||
fat: def.nutritionPer100g.fat * f,
|
||||
carbs: def.nutritionPer100g.carbs * f,
|
||||
};
|
||||
}
|
||||
|
||||
export function computeEntryNutrition(entry) {
|
||||
if (!entry?.recipeId) return { kcal: 0, protein: 0, fat: 0, carbs: 0 };
|
||||
const r = RECIPES[entry.recipeId];
|
||||
if (!r) return { kcal: 0, protein: 0, fat: 0, carbs: 0 };
|
||||
const s = Math.max(1, Number(entry.servings) || 1);
|
||||
|
||||
if (!hasCustomizations(entry)) {
|
||||
return {
|
||||
kcal: Math.round(r.nutritionPerServing.kcal * s),
|
||||
protein: Math.round(r.nutritionPerServing.protein * s * 10) / 10,
|
||||
fat: Math.round(r.nutritionPerServing.fat * s * 10) / 10,
|
||||
carbs: Math.round(r.nutritionPerServing.carbs * s * 10) / 10,
|
||||
};
|
||||
}
|
||||
|
||||
const excluded = new Set(entry.excludedIngredients || []);
|
||||
const overrides = entry.amountOverrides || {};
|
||||
const subs = entry.substitutions || {};
|
||||
let kcal = 0, protein = 0, fat = 0, carbs = 0;
|
||||
|
||||
for (const ing of r.ingredients) {
|
||||
if (excluded.has(ing.ingredientId)) continue;
|
||||
const eid = subs[ing.ingredientId] || ing.ingredientId;
|
||||
const base = overrides[ing.ingredientId] ?? ing.amount;
|
||||
const n = nutritionForAmountRaw(eid, base * s, ing.unit);
|
||||
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
|
||||
}
|
||||
for (const a of (entry.addedIngredients || [])) {
|
||||
const n = nutritionForAmountRaw(a.ingredientId, a.amount * s, a.unit);
|
||||
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
|
||||
}
|
||||
|
||||
return {
|
||||
kcal: Math.round(kcal),
|
||||
protein: Math.round(protein * 10) / 10,
|
||||
fat: Math.round(fat * 10) / 10,
|
||||
carbs: Math.round(carbs * 10) / 10,
|
||||
};
|
||||
}
|
||||
|
||||
export function sumDayNutrition(dayPlan) {
|
||||
let kcal = 0;
|
||||
let protein = 0;
|
||||
let fat = 0;
|
||||
let carbs = 0;
|
||||
let mealCount = 0;
|
||||
let kcal = 0, protein = 0, fat = 0, carbs = 0, mealCount = 0;
|
||||
const skipped = dayPlan._skipped || {};
|
||||
MEAL_SLOTS.forEach((slot) => {
|
||||
if (skipped[slot.id]) return;
|
||||
const entries = dayPlan[slot.id];
|
||||
if (!Array.isArray(entries)) return;
|
||||
entries.forEach((entry) => {
|
||||
if (!entry || !entry.recipeId) return;
|
||||
const r = RECIPES[entry.recipeId];
|
||||
if (!r) return;
|
||||
const s = Math.max(1, Number(entry.servings) || 1);
|
||||
if (!entry?.recipeId || !RECIPES[entry.recipeId]) return;
|
||||
mealCount += 1;
|
||||
kcal += r.nutritionPerServing.kcal * s;
|
||||
protein += r.nutritionPerServing.protein * s;
|
||||
fat += r.nutritionPerServing.fat * s;
|
||||
carbs += r.nutritionPerServing.carbs * s;
|
||||
const n = computeEntryNutrition(entry);
|
||||
kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs;
|
||||
});
|
||||
});
|
||||
return {
|
||||
@@ -70,10 +122,20 @@ export function flattenDayIngredientLines(dayPlan) {
|
||||
const r = RECIPES[entry.recipeId];
|
||||
if (!r || !Array.isArray(r.ingredients)) return;
|
||||
const serv = Math.max(1, Number(entry.servings) || 1);
|
||||
const excluded = new Set(entry.excludedIngredients || []);
|
||||
const overrides = entry.amountOverrides || {};
|
||||
const subs = entry.substitutions || {};
|
||||
r.ingredients.forEach((ing) => {
|
||||
const scaled = Math.round(ing.amount * serv * 10) / 10;
|
||||
out.push(resolveLine(ing, scaled));
|
||||
if (excluded.has(ing.ingredientId)) return;
|
||||
const effectiveId = subs[ing.ingredientId] || ing.ingredientId;
|
||||
const base = overrides[ing.ingredientId] ?? ing.amount;
|
||||
const scaled = Math.round(base * serv * 10) / 10;
|
||||
out.push(resolveLine({ ingredientId: effectiveId, unit: ing.unit }, scaled));
|
||||
});
|
||||
for (const a of (entry.addedIngredients || [])) {
|
||||
const scaled = Math.round(a.amount * serv * 10) / 10;
|
||||
out.push(resolveLine(a, scaled));
|
||||
}
|
||||
});
|
||||
});
|
||||
return out;
|
||||
@@ -129,16 +191,33 @@ export function aggregateDayIngredientsBySlot(dayPlan) {
|
||||
const r = RECIPES[entry.recipeId];
|
||||
if (!r) return;
|
||||
const s = Math.max(1, Number(entry.servings) || 1);
|
||||
const items = r.ingredients.map((ing) => {
|
||||
const def = INGREDIENTS[ing.ingredientId];
|
||||
return {
|
||||
ingredientId: ing.ingredientId,
|
||||
name: def?.name ?? ing.ingredientId,
|
||||
const excluded = new Set(entry.excludedIngredients || []);
|
||||
const overrides = entry.amountOverrides || {};
|
||||
const subs = entry.substitutions || {};
|
||||
const items = [];
|
||||
r.ingredients.forEach((ing) => {
|
||||
if (excluded.has(ing.ingredientId)) return;
|
||||
const effectiveId = subs[ing.ingredientId] || ing.ingredientId;
|
||||
const base = overrides[ing.ingredientId] ?? ing.amount;
|
||||
const def = INGREDIENTS[effectiveId];
|
||||
items.push({
|
||||
ingredientId: effectiveId,
|
||||
name: def?.name ?? effectiveId,
|
||||
category: def?.category ?? 'inne',
|
||||
amount: Math.round(ing.amount * s * 10) / 10,
|
||||
amount: Math.round(base * s * 10) / 10,
|
||||
unit: ing.unit,
|
||||
};
|
||||
});
|
||||
});
|
||||
for (const a of (entry.addedIngredients || [])) {
|
||||
const def = INGREDIENTS[a.ingredientId];
|
||||
items.push({
|
||||
ingredientId: a.ingredientId,
|
||||
name: def?.name ?? a.ingredientId,
|
||||
category: def?.category ?? 'inne',
|
||||
amount: Math.round(a.amount * s * 10) / 10,
|
||||
unit: a.unit,
|
||||
});
|
||||
}
|
||||
recipes.push({ recipeTitle: r.title, items });
|
||||
});
|
||||
if (recipes.length > 0) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { RECIPES } from '../data/catalog.js';
|
||||
import { INGREDIENTS, RECIPES } from '../data/catalog.js';
|
||||
import { MEAL_SLOTS } from '../planner/mealSlots.js';
|
||||
import { PLANS_STORAGE_KEY } from '../storageKeys.js';
|
||||
import { startOfDay } from './dateUtils.js';
|
||||
@@ -18,7 +18,32 @@ export function newPlanEntryId() {
|
||||
return `e${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
|
||||
}
|
||||
|
||||
/** Jedna pora dnia = tablica wpisów { id, recipeId, servings } */
|
||||
function normalizeEntryExtras(x) {
|
||||
const out = {};
|
||||
if (x.substitutions && typeof x.substitutions === 'object' && !Array.isArray(x.substitutions) && Object.keys(x.substitutions).length > 0) {
|
||||
out.substitutions = { ...x.substitutions };
|
||||
}
|
||||
if (Array.isArray(x.excludedIngredients)) {
|
||||
const arr = x.excludedIngredients.filter((id) => typeof id === 'string');
|
||||
if (arr.length > 0) out.excludedIngredients = arr;
|
||||
}
|
||||
if (x.amountOverrides && typeof x.amountOverrides === 'object' && !Array.isArray(x.amountOverrides)) {
|
||||
const filtered = {};
|
||||
for (const [k, v] of Object.entries(x.amountOverrides)) {
|
||||
if (typeof v === 'number' && v >= 0) filtered[k] = v;
|
||||
}
|
||||
if (Object.keys(filtered).length > 0) out.amountOverrides = filtered;
|
||||
}
|
||||
if (Array.isArray(x.addedIngredients)) {
|
||||
const valid = x.addedIngredients
|
||||
.filter((a) => a && typeof a.ingredientId === 'string' && INGREDIENTS[a.ingredientId] && typeof a.amount === 'number' && a.amount >= 0 && typeof a.unit === 'string')
|
||||
.map((a) => ({ ingredientId: a.ingredientId, amount: a.amount, unit: a.unit }));
|
||||
if (valid.length > 0) out.addedIngredients = valid;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Jedna pora dnia = tablica wpisów { id, recipeId, servings, ...extras } */
|
||||
export function normalizeSlotValue(v) {
|
||||
if (!v) return [];
|
||||
if (Array.isArray(v)) {
|
||||
@@ -28,9 +53,7 @@ export function normalizeSlotValue(v) {
|
||||
id: x.id && String(x.id).length ? String(x.id) : newPlanEntryId(),
|
||||
recipeId: x.recipeId,
|
||||
servings: Math.max(1, Math.min(12, Number(x.servings) || 1)),
|
||||
...(x.substitutions && typeof x.substitutions === 'object' && !Array.isArray(x.substitutions) && Object.keys(x.substitutions).length > 0
|
||||
? { substitutions: { ...x.substitutions } }
|
||||
: {}),
|
||||
...normalizeEntryExtras(x),
|
||||
}));
|
||||
}
|
||||
if (typeof v === 'object' && v.recipeId && RECIPES[v.recipeId]) {
|
||||
@@ -38,9 +61,7 @@ export function normalizeSlotValue(v) {
|
||||
id: newPlanEntryId(),
|
||||
recipeId: v.recipeId,
|
||||
servings: Math.max(1, Math.min(12, Number(v.servings) || 1)),
|
||||
...(v.substitutions && typeof v.substitutions === 'object' && !Array.isArray(v.substitutions) && Object.keys(v.substitutions).length > 0
|
||||
? { substitutions: { ...v.substitutions } }
|
||||
: {}),
|
||||
...normalizeEntryExtras(v),
|
||||
}];
|
||||
}
|
||||
return [];
|
||||
|
||||
644
js/ui/mealPlanEditor.js
Normal file
644
js/ui/mealPlanEditor.js
Normal file
@@ -0,0 +1,644 @@
|
||||
import { INGREDIENTS, RECIPES } from '../data/catalog.js';
|
||||
import { MEAL_SLOTS } from '../planner/mealSlots.js';
|
||||
import {
|
||||
addDays,
|
||||
addMonths,
|
||||
sameDay,
|
||||
sameMonth,
|
||||
startOfDay,
|
||||
startOfMonth,
|
||||
startOfWeekMonday,
|
||||
} from '../services/dateUtils.js';
|
||||
import {
|
||||
dateKey,
|
||||
loadPlans,
|
||||
newPlanEntryId,
|
||||
savePlans,
|
||||
} from '../services/planStore.js';
|
||||
import { showAppToast } from './toast.js';
|
||||
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
}
|
||||
|
||||
const MONTHS_LONG = ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'];
|
||||
const MONTHS_SHORT = ['sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru'];
|
||||
const WEEKDAYS_SHORT = ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'];
|
||||
const WEEKDAYS_LONG = ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'];
|
||||
const slotLabel = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));
|
||||
|
||||
/* ── HTML template ──────────────────────────────────── */
|
||||
|
||||
export function getMealPlanEditorHTML() {
|
||||
return `
|
||||
<div id="mpe-overlay" class="absolute inset-0 z-[55] bg-black/45 hidden flex items-end" style="pointer-events:none">
|
||||
<div id="mpe-sheet" class="w-full bg-white rounded-t-3xl shadow-lg flex flex-col" style="pointer-events:auto; max-height:95vh; transform:translateY(100%); transition:transform 300ms cubic-bezier(0.32,0.72,0,1)">
|
||||
<div class="shrink-0 px-5 pt-3 pb-2.5 border-b border-gray-100">
|
||||
<div class="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-3"></div>
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="min-w-0 flex-1">
|
||||
<h2 id="mpe-title" class="text-[15px] font-bold text-gray-900 leading-tight"></h2>
|
||||
<p id="mpe-subtitle" class="text-[11px] text-gray-500 mt-0.5 truncate"></p>
|
||||
</div>
|
||||
<button id="mpe-close-btn" type="button" class="shrink-0 w-8 h-8 rounded-full border border-gray-200 flex items-center justify-center text-gray-400 hover:text-gray-900 hover:bg-gray-50 transition-colors ml-3">
|
||||
<i class="fas fa-times text-xs"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="mpe-body" class="flex-1 min-h-0 overflow-y-auto no-scrollbar px-5 py-3">
|
||||
<div id="mpe-cal-section" class="hidden mb-4">
|
||||
<div class="flex items-center gap-1 mb-2">
|
||||
<button id="mpe-cal-prev" type="button" class="shrink-0 w-8 h-8 flex items-center justify-center rounded-full border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"><i class="fas fa-chevron-left text-xs"></i></button>
|
||||
<p id="mpe-cal-title" class="flex-1 min-w-0 text-xs font-medium text-gray-900 text-center tabular-nums leading-none px-1 truncate"></p>
|
||||
<button id="mpe-cal-next" type="button" class="shrink-0 w-8 h-8 flex items-center justify-center rounded-full border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"><i class="fas fa-chevron-right text-xs"></i></button>
|
||||
</div>
|
||||
<div class="flex items-center justify-center mb-2">
|
||||
<button id="mpe-cal-today" type="button" class="h-6 shrink-0 inline-flex items-center justify-center gap-1 rounded-md border border-gray-200 bg-white px-2.5 text-[10px] font-semibold text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 transition-colors hidden"><i class="fas fa-calendar-day text-[9px] opacity-70"></i> Dziś</button>
|
||||
</div>
|
||||
<div class="grid grid-cols-7 gap-0.5 text-center text-[9px] font-medium text-gray-400 uppercase tracking-wide mb-0.5 leading-none">${WEEKDAYS_SHORT.map((d) => `<div>${d}</div>`).join('')}</div>
|
||||
<div id="mpe-cal-grid" class="grid grid-cols-7 gap-0.5"></div>
|
||||
<button id="mpe-cal-toggle" type="button" class="w-full flex items-center justify-center py-1 mt-1 text-gray-400 hover:text-gray-600 transition-colors"><i id="mpe-cal-toggle-icon" class="fas fa-chevron-down text-[10px]"></i></button>
|
||||
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mt-3 mb-2">Pora posiłku</p>
|
||||
<div id="mpe-slot-chips" class="flex flex-wrap gap-1.5"></div>
|
||||
</div>
|
||||
<div id="mpe-servings-row" class="flex items-center justify-between mb-4"></div>
|
||||
<div id="mpe-ing-section" class="mb-4">
|
||||
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Składniki</p>
|
||||
<div id="mpe-ing-list" class="space-y-1.5"></div>
|
||||
<div id="mpe-add-area" class="mt-2"></div>
|
||||
</div>
|
||||
<div id="mpe-nutrition-section"></div>
|
||||
</div>
|
||||
<div class="shrink-0 px-5 pb-8 pt-3 border-t border-gray-100">
|
||||
<button id="mpe-confirm-btn" type="button" class="w-full bg-gray-900 hover:bg-black text-white py-3 rounded-xl font-semibold text-[13px] transition-colors flex items-center justify-center gap-2">
|
||||
<i class="fas fa-check text-xs"></i> <span id="mpe-confirm-label">Dodaj do planu</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/* ── Setup ──────────────────────────────────────────── */
|
||||
|
||||
export function setupMealPlanEditor() {
|
||||
const overlay = document.getElementById('mpe-overlay');
|
||||
const sheet = document.getElementById('mpe-sheet');
|
||||
if (!overlay || !sheet) return;
|
||||
|
||||
const S = {
|
||||
mode: null,
|
||||
recipeId: null,
|
||||
date: null,
|
||||
slotId: null,
|
||||
servings: 1,
|
||||
subs: {},
|
||||
excluded: new Set(),
|
||||
overrides: {},
|
||||
added: [],
|
||||
entryId: null,
|
||||
showCal: false,
|
||||
calDate: null,
|
||||
calExpanded: false,
|
||||
altOpen: new Set(),
|
||||
addOpen: false,
|
||||
addQuery: '',
|
||||
};
|
||||
|
||||
/* ── helpers ───────────────────────────────────── */
|
||||
|
||||
function nutFor(ingredientId, amount, unit) {
|
||||
const def = INGREDIENTS[ingredientId];
|
||||
if (!def?.nutritionPer100g) return null;
|
||||
let g = amount;
|
||||
if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) g = amount * def.weightPerPiece;
|
||||
const f = g / 100;
|
||||
return {
|
||||
kcal: Math.round(def.nutritionPer100g.kcal * f),
|
||||
protein: Math.round(def.nutritionPer100g.protein * f * 10) / 10,
|
||||
fat: Math.round(def.nutritionPer100g.fat * f * 10) / 10,
|
||||
carbs: Math.round(def.nutritionPer100g.carbs * f * 10) / 10,
|
||||
};
|
||||
}
|
||||
|
||||
function totalNutrition() {
|
||||
const r = RECIPES[S.recipeId];
|
||||
if (!r) return { kcal: 0, protein: 0, fat: 0, carbs: 0 };
|
||||
let kcal = 0, protein = 0, fat = 0, carbs = 0;
|
||||
for (const ing of r.ingredients) {
|
||||
if (S.excluded.has(ing.ingredientId)) continue;
|
||||
const eid = S.subs[ing.ingredientId] || ing.ingredientId;
|
||||
const base = S.overrides[ing.ingredientId] ?? ing.amount;
|
||||
const n = nutFor(eid, base * S.servings, ing.unit);
|
||||
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
|
||||
}
|
||||
for (const a of S.added) {
|
||||
const n = nutFor(a.ingredientId, a.amount * S.servings, a.unit);
|
||||
if (n) { kcal += n.kcal; protein += n.protein; fat += n.fat; carbs += n.carbs; }
|
||||
}
|
||||
return { kcal: Math.round(kcal), protein: Math.round(protein * 10) / 10, fat: Math.round(fat * 10) / 10, carbs: Math.round(carbs * 10) / 10 };
|
||||
}
|
||||
|
||||
function fmtAmt(n) { return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(1))); }
|
||||
|
||||
/* ── Calendar ──────────────────────────────────── */
|
||||
|
||||
function calCell(d, today, month) {
|
||||
const sel = S.date && sameDay(d, S.date);
|
||||
const past = d.getTime() < today.getTime();
|
||||
const other = d.getMonth() !== month;
|
||||
let cls = 'flex flex-col items-center justify-center rounded-md text-xs font-medium transition-colors w-full min-h-10 py-1 gap-0.5 leading-tight ';
|
||||
if (sel) cls += 'bg-gray-900 text-white ';
|
||||
else if (past || other) cls += 'text-gray-300 ';
|
||||
else cls += 'text-gray-800 hover:bg-gray-100 ';
|
||||
if (!sel && !past && !other && sameDay(d, today)) cls += 'ring-1 ring-inset ring-gray-900 ';
|
||||
const inner = `<span>${d.getDate()}</span><span class="w-1 h-1"></span>`;
|
||||
return (past && !sel) ? `<div class="${cls}">${inner}</div>` : `<button type="button" class="mpe-cal-day ${cls}" data-ts="${d.getTime()}">${inner}</button>`;
|
||||
}
|
||||
|
||||
function renderCal() {
|
||||
const sec = document.getElementById('mpe-cal-section');
|
||||
if (!sec || !S.showCal) { sec?.classList.add('hidden'); return; }
|
||||
sec.classList.remove('hidden');
|
||||
const grid = document.getElementById('mpe-cal-grid');
|
||||
const title = document.getElementById('mpe-cal-title');
|
||||
const todayBtn = document.getElementById('mpe-cal-today');
|
||||
const icon = document.getElementById('mpe-cal-toggle-icon');
|
||||
if (!grid || !title) return;
|
||||
const today = startOfDay(new Date());
|
||||
|
||||
if (S.calExpanded) {
|
||||
const ms = startOfMonth(S.calDate);
|
||||
title.textContent = `${MONTHS_LONG[ms.getMonth()]} ${ms.getFullYear()}`;
|
||||
icon.className = 'fas fa-chevron-up text-[10px]';
|
||||
const first = startOfWeekMonday(ms);
|
||||
const cells = [];
|
||||
let d = new Date(first);
|
||||
for (let i = 0; i < 42; i++) { cells.push(new Date(d)); d = addDays(d, 1); }
|
||||
while (cells.length > 7 && cells.slice(-7).every((c) => c.getMonth() !== ms.getMonth())) cells.splice(-7);
|
||||
grid.innerHTML = cells.map((c) => calCell(c, today, ms.getMonth())).join('');
|
||||
todayBtn?.classList.toggle('hidden', sameMonth(today, S.calDate));
|
||||
} else {
|
||||
const ws = startOfWeekMonday(S.calDate);
|
||||
title.textContent = `${MONTHS_LONG[S.calDate.getMonth()]} ${S.calDate.getFullYear()}`;
|
||||
icon.className = 'fas fa-chevron-down text-[10px]';
|
||||
const cells = [];
|
||||
for (let i = 0; i < 7; i++) cells.push(addDays(ws, i));
|
||||
grid.innerHTML = cells.map((c) => calCell(c, today, S.calDate.getMonth())).join('');
|
||||
todayBtn?.classList.toggle('hidden', sameDay(startOfWeekMonday(today), ws));
|
||||
}
|
||||
|
||||
grid.querySelectorAll('.mpe-cal-day').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
S.date = new Date(Number(btn.dataset.ts));
|
||||
S.calDate = new Date(S.date);
|
||||
renderCal();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderSlots() {
|
||||
const el = document.getElementById('mpe-slot-chips');
|
||||
if (!el || !S.showCal) return;
|
||||
const r = RECIPES[S.recipeId];
|
||||
if (!r) return;
|
||||
el.innerHTML = MEAL_SLOTS.filter((s) => r.allowedSlots.includes(s.id)).map((s) => {
|
||||
const sel = s.id === S.slotId;
|
||||
return `<button type="button" class="mpe-slot-btn px-3 py-1.5 rounded-lg border text-[12px] font-semibold transition-all ${sel ? 'border-gray-900 bg-gray-900 text-white' : 'border-gray-200 bg-gray-50 text-gray-700 hover:border-gray-400'}" data-slot-id="${s.id}">${esc(s.label)}</button>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
/* ── Servings ──────────────────────────────────── */
|
||||
|
||||
function renderServings() {
|
||||
const el = document.getElementById('mpe-servings-row');
|
||||
if (!el) return;
|
||||
el.innerHTML = `
|
||||
<span class="text-[13px] font-semibold text-gray-900">Porcje</span>
|
||||
<div class="flex items-center gap-0.5 bg-gray-100 p-0.5 rounded-lg">
|
||||
<button type="button" id="mpe-serv-minus" class="w-7 h-7 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black hover:bg-gray-50"><i class="fas fa-minus text-[9px]"></i></button>
|
||||
<span id="mpe-serv-count" class="font-bold text-gray-900 text-[13px] w-5 text-center tabular-nums">${S.servings}</span>
|
||||
<button type="button" id="mpe-serv-plus" class="w-7 h-7 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black hover:bg-gray-50"><i class="fas fa-plus text-[9px]"></i></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/* ── Ingredients list ──────────────────────────── */
|
||||
|
||||
function renderIngList() {
|
||||
const list = document.getElementById('mpe-ing-list');
|
||||
if (!list) return;
|
||||
const r = RECIPES[S.recipeId];
|
||||
if (!r) return;
|
||||
let html = '';
|
||||
|
||||
for (const ing of r.ingredients) {
|
||||
const id = ing.ingredientId;
|
||||
const excl = S.excluded.has(id);
|
||||
const eid = S.subs[id] || id;
|
||||
const eDef = INGREDIENTS[eid];
|
||||
const eName = eDef?.name || eid;
|
||||
const hasAlts = ing.alternatives?.length > 0;
|
||||
const swapped = eid !== id;
|
||||
const altOpen = S.altOpen.has(id);
|
||||
const base = S.overrides[id] ?? ing.amount;
|
||||
const disp = base * S.servings;
|
||||
const modified = id in S.overrides;
|
||||
|
||||
const checkCls = excl
|
||||
? 'w-5 h-5 rounded-md border-2 border-gray-300 bg-white'
|
||||
: 'w-5 h-5 rounded-md border-2 border-gray-900 bg-gray-900';
|
||||
const checkIco = excl ? '' : '<i class="fas fa-check text-white text-[8px]"></i>';
|
||||
const rowBorder = excl ? 'border-gray-100' : swapped ? 'border-amber-200' : 'border-gray-200';
|
||||
const rowBg = excl ? 'bg-gray-50/50' : swapped ? 'bg-amber-50/30' : 'bg-white';
|
||||
const rowOp = excl ? 'opacity-50' : '';
|
||||
const nameCls = excl ? 'text-[12px] font-semibold text-gray-400 line-through' : 'text-[12px] font-semibold text-gray-900';
|
||||
const amtCls = excl ? 'text-gray-300' : 'text-gray-900';
|
||||
const unitCls = excl ? 'text-gray-300' : 'text-gray-500';
|
||||
|
||||
const shuffleBtn = hasAlts && !excl
|
||||
? `<button type="button" class="mpe-shuffle shrink-0 w-5 h-5 rounded-full ${swapped ? 'bg-amber-50 text-amber-500' : 'bg-gray-100 text-gray-400 hover:bg-gray-200'} flex items-center justify-center transition-colors" data-orig-id="${esc(id)}"><i class="fas fa-shuffle text-[8px]"></i></button>`
|
||||
: '';
|
||||
const modDot = modified && !excl ? '<span class="w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"></span>' : '';
|
||||
|
||||
html += `<div class="mpe-ing-row rounded-xl border ${rowBorder} ${rowBg} ${rowOp} p-2.5" data-orig-id="${esc(id)}" data-type="recipe">`;
|
||||
html += `<div class="flex items-center gap-2.5">`;
|
||||
html += `<button type="button" class="mpe-toggle ${checkCls} flex items-center justify-center shrink-0" data-orig-id="${esc(id)}">${checkIco}</button>`;
|
||||
html += `<div class="flex-1 min-w-0 flex items-center gap-1.5"><span class="${nameCls} truncate">${esc(eName)}</span>${shuffleBtn}</div>`;
|
||||
html += `<button type="button" class="mpe-edit-amt shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg ${excl ? '' : 'hover:bg-gray-100'} transition-colors" data-orig-id="${esc(id)}" data-type="recipe" ${excl ? 'disabled' : ''}>`;
|
||||
html += `${modDot}<span class="text-[12px] font-semibold ${amtCls} tabular-nums">${fmtAmt(disp)}</span>`;
|
||||
html += `<span class="text-[11px] ${unitCls}">${esc(ing.unit)}</span></button>`;
|
||||
html += `</div>`;
|
||||
|
||||
if (hasAlts && altOpen && !excl) {
|
||||
const opts = [id, ...ing.alternatives];
|
||||
html += '<div class="mt-2 ml-7 space-y-1">';
|
||||
for (const altId of opts) {
|
||||
const def = INGREDIENTS[altId];
|
||||
const name = def?.name || altId;
|
||||
const isSel = eid === altId;
|
||||
const isOrig = altId === id;
|
||||
const cls2 = isSel ? 'border-gray-900 bg-gray-50 ring-1 ring-gray-900' : 'border-gray-200 bg-white hover:border-gray-300';
|
||||
const radio = `<div class="w-3.5 h-3.5 rounded-full border-2 shrink-0 ${isSel ? 'border-gray-900' : 'border-gray-300'} flex items-center justify-center">${isSel ? '<div class="w-1.5 h-1.5 rounded-full bg-gray-900"></div>' : ''}</div>`;
|
||||
const tag = isOrig ? `<span class="text-[9px] px-1.5 py-0.5 rounded ${isSel ? 'bg-gray-200 text-gray-600' : 'bg-gray-100 text-gray-400'} font-medium ml-auto shrink-0">Domyślny</span>` : '';
|
||||
const n = nutFor(altId, disp, ing.unit);
|
||||
const nLine = n ? `<div class="text-[10px] text-gray-400 mt-0.5 tabular-nums">${n.kcal} kcal · ${n.protein}g B · ${n.fat}g T · ${n.carbs}g W</div>` : '';
|
||||
html += `<button type="button" class="mpe-alt-pick w-full text-left p-2 rounded-lg border transition-all ${cls2}" data-orig-id="${esc(id)}" data-alt-id="${esc(altId)}"><div class="flex items-center gap-2">${radio}<span class="text-[11px] font-semibold text-gray-900">${esc(name)}</span>${tag}</div>${nLine}</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
for (const a of S.added) {
|
||||
const def = INGREDIENTS[a.ingredientId];
|
||||
const name = def?.name || a.ingredientId;
|
||||
const disp = a.amount * S.servings;
|
||||
html += `<div class="mpe-ing-row rounded-xl border border-emerald-200 bg-emerald-50/30 p-2.5" data-ing-id="${esc(a.ingredientId)}" data-type="added">
|
||||
<div class="flex items-center gap-2.5">
|
||||
<span class="shrink-0 w-5 h-5 rounded-md bg-emerald-100 flex items-center justify-center text-emerald-600"><i class="fas fa-plus text-[8px]"></i></span>
|
||||
<span class="flex-1 min-w-0 text-[12px] font-semibold text-gray-900 truncate">${esc(name)}</span>
|
||||
<button type="button" class="mpe-edit-amt shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-gray-100 transition-colors" data-ing-id="${esc(a.ingredientId)}" data-type="added">
|
||||
<span class="text-[12px] font-semibold text-gray-900 tabular-nums">${fmtAmt(disp)}</span>
|
||||
<span class="text-[11px] text-gray-500">${esc(a.unit)}</span>
|
||||
</button>
|
||||
<button type="button" class="mpe-remove-added shrink-0 w-6 h-6 rounded-full border border-gray-200 text-gray-400 hover:text-red-600 hover:border-red-200 hover:bg-red-50 flex items-center justify-center transition-colors" data-ing-id="${esc(a.ingredientId)}"><i class="fas fa-times text-[8px]"></i></button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
list.innerHTML = html;
|
||||
}
|
||||
|
||||
function renderAddArea() {
|
||||
const el = document.getElementById('mpe-add-area');
|
||||
if (!el) return;
|
||||
if (!S.addOpen) {
|
||||
el.innerHTML = `<button type="button" id="mpe-add-btn" class="w-full py-2 rounded-xl border border-dashed border-gray-200 text-[12px] font-semibold text-gray-500 hover:text-gray-900 hover:border-gray-400 hover:bg-gray-50 transition-colors"><i class="fas fa-plus text-[10px] mr-1.5 opacity-70"></i>Dodaj składnik</button>`;
|
||||
return;
|
||||
}
|
||||
const recipe = RECIPES[S.recipeId];
|
||||
const usedIds = new Set([
|
||||
...(recipe?.ingredients.map((i) => i.ingredientId) || []),
|
||||
...S.added.map((a) => a.ingredientId),
|
||||
]);
|
||||
const q = S.addQuery.toLowerCase().trim();
|
||||
const avail = Object.values(INGREDIENTS).filter((i) => !usedIds.has(i.id) && (!q || i.name.toLowerCase().includes(q)));
|
||||
el.innerHTML = `
|
||||
<div class="border border-gray-200 rounded-xl bg-gray-50 p-3">
|
||||
<div class="flex items-center gap-2 mb-2">
|
||||
<input type="text" id="mpe-add-search" class="flex-1 rounded-lg border border-gray-200 bg-white px-3 py-1.5 text-[12px] outline-none focus:border-gray-400 placeholder:text-gray-400" placeholder="Szukaj składnika…" value="${esc(S.addQuery)}">
|
||||
<button type="button" id="mpe-add-cancel" class="text-[11px] font-semibold text-gray-500 hover:text-gray-900 px-2 py-1">Anuluj</button>
|
||||
</div>
|
||||
<div class="max-h-40 overflow-y-auto space-y-0.5 no-scrollbar" id="mpe-add-results">
|
||||
${avail.length === 0
|
||||
? '<p class="text-[11px] text-gray-400 text-center py-3">Brak wyników</p>'
|
||||
: avail.slice(0, 20).map((i) => `<button type="button" class="mpe-add-pick w-full text-left px-2.5 py-2 rounded-lg hover:bg-white transition-colors text-[12px] font-medium text-gray-800" data-ing-id="${esc(i.id)}">${esc(i.name)} <span class="text-gray-400 text-[10px]">${esc(i.category)}</span></button>`).join('')}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function updateAddResults() {
|
||||
const results = document.getElementById('mpe-add-results');
|
||||
if (!results) return;
|
||||
const recipe = RECIPES[S.recipeId];
|
||||
const usedIds = new Set([
|
||||
...(recipe?.ingredients.map((i) => i.ingredientId) || []),
|
||||
...S.added.map((a) => a.ingredientId),
|
||||
]);
|
||||
const q = S.addQuery.toLowerCase().trim();
|
||||
const avail = Object.values(INGREDIENTS).filter((i) => !usedIds.has(i.id) && (!q || i.name.toLowerCase().includes(q)));
|
||||
results.innerHTML = avail.length === 0
|
||||
? '<p class="text-[11px] text-gray-400 text-center py-3">Brak wyników</p>'
|
||||
: avail.slice(0, 20).map((i) => `<button type="button" class="mpe-add-pick w-full text-left px-2.5 py-2 rounded-lg hover:bg-white transition-colors text-[12px] font-medium text-gray-800" data-ing-id="${esc(i.id)}">${esc(i.name)} <span class="text-gray-400 text-[10px]">${esc(i.category)}</span></button>`).join('');
|
||||
}
|
||||
|
||||
function renderIngredients() {
|
||||
renderIngList();
|
||||
renderAddArea();
|
||||
}
|
||||
|
||||
/* ── Nutrition summary ─────────────────────────── */
|
||||
|
||||
function renderNutrition() {
|
||||
const el = document.getElementById('mpe-nutrition-section');
|
||||
if (!el) return;
|
||||
const n = totalNutrition();
|
||||
el.innerHTML = `
|
||||
<div class="rounded-xl border border-gray-100 bg-gray-50/80 p-3">
|
||||
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Wartości odżywcze${S.servings > 1 ? ` · ${S.servings} porcje` : ''}</p>
|
||||
<div class="grid grid-cols-4 gap-3 text-center">
|
||||
<div><span class="block text-[14px] font-bold text-gray-900 tabular-nums">${n.kcal}</span><span class="text-[10px] text-gray-500">kcal</span></div>
|
||||
<div><span class="block text-[14px] font-bold text-gray-900 tabular-nums">${n.protein} g</span><span class="text-[10px] text-gray-500">Białko</span></div>
|
||||
<div><span class="block text-[14px] font-bold text-gray-900 tabular-nums">${n.carbs} g</span><span class="text-[10px] text-gray-500">Węgle</span></div>
|
||||
<div><span class="block text-[14px] font-bold text-gray-900 tabular-nums">${n.fat} g</span><span class="text-[10px] text-gray-500">Tłuszcze</span></div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
/* ── Render all ────────────────────────────────── */
|
||||
|
||||
function renderAll() { renderCal(); renderSlots(); renderServings(); renderIngredients(); renderNutrition(); }
|
||||
|
||||
/* ── Open / Close ─────────────────────────────── */
|
||||
|
||||
function openEditor(opts) {
|
||||
const recipe = RECIPES[opts.recipeId];
|
||||
if (!recipe) return;
|
||||
|
||||
S.mode = opts.mode || 'add';
|
||||
S.recipeId = opts.recipeId;
|
||||
S.servings = opts.servings || opts.entry?.servings || 1;
|
||||
S.subs = { ...(opts.substitutions || opts.entry?.substitutions || {}) };
|
||||
S.excluded = new Set(opts.entry?.excludedIngredients || []);
|
||||
S.overrides = { ...(opts.entry?.amountOverrides || {}) };
|
||||
S.added = (opts.entry?.addedIngredients || []).map((a) => ({ ...a }));
|
||||
S.entryId = opts.entry?.id || null;
|
||||
S.altOpen = new Set();
|
||||
S.addOpen = false;
|
||||
S.addQuery = '';
|
||||
|
||||
if (opts.date && opts.slotId) {
|
||||
S.date = opts.date;
|
||||
S.slotId = opts.slotId;
|
||||
S.showCal = false;
|
||||
} else {
|
||||
const today = startOfDay(new Date());
|
||||
S.date = today;
|
||||
S.calDate = today;
|
||||
S.calExpanded = false;
|
||||
S.slotId = recipe.allowedSlots[0] || MEAL_SLOTS[0]?.id;
|
||||
S.showCal = true;
|
||||
}
|
||||
|
||||
document.getElementById('mpe-title').textContent = S.mode === 'edit' ? 'Edytuj posiłek' : 'Zaplanuj posiłek';
|
||||
document.getElementById('mpe-subtitle').textContent = recipe.title;
|
||||
document.getElementById('mpe-confirm-label').textContent = S.mode === 'edit' ? 'Zapisz zmiany' : 'Dodaj do planu';
|
||||
|
||||
renderAll();
|
||||
|
||||
overlay.classList.remove('hidden');
|
||||
overlay.style.pointerEvents = 'auto';
|
||||
requestAnimationFrame(() => { sheet.style.transform = 'translateY(0)'; });
|
||||
}
|
||||
|
||||
function closeEditor() {
|
||||
sheet.style.transform = 'translateY(100%)';
|
||||
setTimeout(() => { overlay.classList.add('hidden'); overlay.style.pointerEvents = 'none'; }, 300);
|
||||
}
|
||||
|
||||
/* ── Save ──────────────────────────────────────── */
|
||||
|
||||
function buildEntry() {
|
||||
const entry = { id: S.entryId || newPlanEntryId(), recipeId: S.recipeId, servings: S.servings };
|
||||
if (Object.keys(S.subs).length > 0) entry.substitutions = { ...S.subs };
|
||||
if (S.excluded.size > 0) entry.excludedIngredients = [...S.excluded];
|
||||
const recipe = RECIPES[S.recipeId];
|
||||
if (recipe) {
|
||||
const ov = {};
|
||||
for (const [k, v] of Object.entries(S.overrides)) {
|
||||
const orig = recipe.ingredients.find((i) => i.ingredientId === k);
|
||||
if (orig && Math.abs(v - orig.amount) > 0.01) ov[k] = v;
|
||||
}
|
||||
if (Object.keys(ov).length > 0) entry.amountOverrides = ov;
|
||||
}
|
||||
if (S.added.length > 0) entry.addedIngredients = S.added.map((a) => ({ ingredientId: a.ingredientId, amount: a.amount, unit: a.unit }));
|
||||
return entry;
|
||||
}
|
||||
|
||||
function handleConfirm() {
|
||||
if (!S.recipeId || !S.date || !S.slotId) return;
|
||||
const plans = loadPlans();
|
||||
const key = dateKey(S.date);
|
||||
|
||||
if (S.mode === 'edit' && S.entryId) {
|
||||
const arr = plans[key]?.[S.slotId];
|
||||
if (Array.isArray(arr)) {
|
||||
const idx = arr.findIndex((e) => e.id === S.entryId);
|
||||
if (idx >= 0) arr[idx] = buildEntry();
|
||||
}
|
||||
} else {
|
||||
if (!plans[key]) plans[key] = {};
|
||||
if (!plans[key][S.slotId]) plans[key][S.slotId] = [];
|
||||
plans[key][S.slotId].push(buildEntry());
|
||||
}
|
||||
|
||||
savePlans(plans);
|
||||
closeEditor();
|
||||
showAppToast(S.mode === 'edit' ? 'Zapisano zmiany!' : 'Dodano do planera!');
|
||||
window.refreshPlanner?.();
|
||||
}
|
||||
|
||||
/* ── Event bindings ───────────────────────────── */
|
||||
|
||||
document.getElementById('mpe-close-btn')?.addEventListener('click', closeEditor);
|
||||
overlay?.addEventListener('click', (e) => { if (e.target === overlay) closeEditor(); });
|
||||
document.getElementById('mpe-confirm-btn')?.addEventListener('click', handleConfirm);
|
||||
|
||||
document.getElementById('mpe-cal-prev')?.addEventListener('click', () => {
|
||||
if (!S.showCal) return;
|
||||
S.calDate = S.calExpanded ? addMonths(S.calDate, -1) : addDays(S.calDate, -7);
|
||||
renderCal();
|
||||
});
|
||||
document.getElementById('mpe-cal-next')?.addEventListener('click', () => {
|
||||
if (!S.showCal) return;
|
||||
S.calDate = S.calExpanded ? addMonths(S.calDate, 1) : addDays(S.calDate, 7);
|
||||
renderCal();
|
||||
});
|
||||
document.getElementById('mpe-cal-today')?.addEventListener('click', () => {
|
||||
const today = startOfDay(new Date());
|
||||
S.date = today; S.calDate = today;
|
||||
renderCal();
|
||||
});
|
||||
document.getElementById('mpe-cal-toggle')?.addEventListener('click', () => {
|
||||
S.calExpanded = !S.calExpanded;
|
||||
renderCal();
|
||||
});
|
||||
|
||||
document.getElementById('mpe-slot-chips')?.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('.mpe-slot-btn');
|
||||
if (!btn) return;
|
||||
S.slotId = btn.dataset.slotId;
|
||||
renderSlots();
|
||||
});
|
||||
|
||||
document.getElementById('mpe-servings-row')?.addEventListener('click', (e) => {
|
||||
if (e.target.closest('#mpe-serv-minus')) { if (S.servings <= 1) return; S.servings--; }
|
||||
else if (e.target.closest('#mpe-serv-plus')) { if (S.servings >= 12) return; S.servings++; }
|
||||
else return;
|
||||
renderServings();
|
||||
renderIngredients();
|
||||
renderNutrition();
|
||||
});
|
||||
|
||||
/* ── Ingredient section delegation ────────────── */
|
||||
|
||||
const ingSec = document.getElementById('mpe-ing-section');
|
||||
|
||||
ingSec?.addEventListener('click', (e) => {
|
||||
const toggle = e.target.closest('.mpe-toggle');
|
||||
if (toggle) {
|
||||
const id = toggle.dataset.origId;
|
||||
if (S.excluded.has(id)) S.excluded.delete(id); else S.excluded.add(id);
|
||||
renderIngredients(); renderNutrition();
|
||||
return;
|
||||
}
|
||||
|
||||
const shuffle = e.target.closest('.mpe-shuffle');
|
||||
if (shuffle) {
|
||||
const id = shuffle.dataset.origId;
|
||||
if (S.altOpen.has(id)) S.altOpen.delete(id); else S.altOpen.add(id);
|
||||
renderIngList();
|
||||
return;
|
||||
}
|
||||
|
||||
const altPick = e.target.closest('.mpe-alt-pick');
|
||||
if (altPick) {
|
||||
const origId = altPick.dataset.origId;
|
||||
const altId = altPick.dataset.altId;
|
||||
if (altId === origId) delete S.subs[origId]; else S.subs[origId] = altId;
|
||||
S.altOpen.delete(origId);
|
||||
renderIngList(); renderNutrition();
|
||||
return;
|
||||
}
|
||||
|
||||
const editAmt = e.target.closest('.mpe-edit-amt');
|
||||
if (editAmt && !editAmt.disabled) {
|
||||
startAmountEdit(editAmt);
|
||||
return;
|
||||
}
|
||||
|
||||
const removeAdded = e.target.closest('.mpe-remove-added');
|
||||
if (removeAdded) {
|
||||
S.added = S.added.filter((a) => a.ingredientId !== removeAdded.dataset.ingId);
|
||||
renderIngredients(); renderNutrition();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.target.closest('#mpe-add-btn')) {
|
||||
S.addOpen = true; S.addQuery = '';
|
||||
renderAddArea();
|
||||
document.getElementById('mpe-add-search')?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.target.closest('#mpe-add-cancel')) {
|
||||
S.addOpen = false;
|
||||
renderAddArea();
|
||||
return;
|
||||
}
|
||||
|
||||
const addPick = e.target.closest('.mpe-add-pick');
|
||||
if (addPick) {
|
||||
const ingId = addPick.dataset.ingId;
|
||||
const def = INGREDIENTS[ingId];
|
||||
if (!def) return;
|
||||
const unit = def.pantryUnit === 'szt' ? 'szt.' : def.pantryUnit;
|
||||
const amt = def.pantryUnit === 'szt' ? 1 : 100;
|
||||
S.added.push({ ingredientId: ingId, amount: amt, unit });
|
||||
S.addOpen = false;
|
||||
renderIngredients(); renderNutrition();
|
||||
}
|
||||
});
|
||||
|
||||
ingSec?.addEventListener('input', (e) => {
|
||||
if (e.target.id === 'mpe-add-search') {
|
||||
S.addQuery = e.target.value;
|
||||
updateAddResults();
|
||||
}
|
||||
});
|
||||
|
||||
/* ── Inline amount editing ────────────────────── */
|
||||
|
||||
function startAmountEdit(btn) {
|
||||
const type = btn.dataset.type;
|
||||
const id = btn.dataset.origId || btn.dataset.ingId;
|
||||
const amtSpan = btn.querySelector('.tabular-nums');
|
||||
if (!amtSpan) return;
|
||||
|
||||
const currentDisplay = parseFloat(amtSpan.textContent);
|
||||
const spans = btn.querySelectorAll('span');
|
||||
const unitText = spans.length > 0 ? spans[spans.length - 1].textContent.trim() : '';
|
||||
const saved = btn.innerHTML;
|
||||
|
||||
btn.innerHTML = `<input type="number" class="mpe-amt-input w-16 text-right text-[12px] font-semibold text-gray-900 border border-gray-300 rounded-lg px-2 py-1 focus:border-gray-900 focus:ring-1 focus:ring-gray-900 outline-none tabular-nums" value="${currentDisplay}" min="0" step="any"><span class="text-[11px] text-gray-500 ml-1">${esc(unitText)}</span>`;
|
||||
|
||||
const input = btn.querySelector('.mpe-amt-input');
|
||||
if (!input) { btn.innerHTML = saved; return; }
|
||||
input.focus();
|
||||
input.select();
|
||||
|
||||
let done = false;
|
||||
const finish = (save) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
if (save) {
|
||||
const raw = Math.max(0, parseFloat(input.value) || 0);
|
||||
const newBase = S.servings > 0 ? raw / S.servings : raw;
|
||||
const rounded = Math.round(newBase * 100) / 100;
|
||||
|
||||
if (type === 'recipe') {
|
||||
const recipe = RECIPES[S.recipeId];
|
||||
const orig = recipe?.ingredients.find((i) => i.ingredientId === id);
|
||||
if (orig && Math.abs(rounded - orig.amount) > 0.01) S.overrides[id] = rounded;
|
||||
else delete S.overrides[id];
|
||||
} else if (type === 'added') {
|
||||
const a = S.added.find((x) => x.ingredientId === id);
|
||||
if (a) a.amount = rounded;
|
||||
}
|
||||
}
|
||||
renderIngList();
|
||||
renderNutrition();
|
||||
};
|
||||
|
||||
input.addEventListener('blur', () => finish(true));
|
||||
input.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
|
||||
if (e.key === 'Escape') { e.preventDefault(); finish(false); }
|
||||
});
|
||||
}
|
||||
|
||||
/* ── Expose globally ──────────────────────────── */
|
||||
|
||||
window.openMealPlanEditor = openEditor;
|
||||
window.closeMealPlanEditor = closeEditor;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
weekContains,
|
||||
} from '../services/dateUtils.js';
|
||||
import {
|
||||
computeEntryNutrition,
|
||||
computeFullForecast,
|
||||
countDayShortfalls,
|
||||
dayHasAnyMeal,
|
||||
@@ -502,8 +503,7 @@ function renderDayContent(state) {
|
||||
|
||||
let slotKcal = 0;
|
||||
entries.forEach((entry) => {
|
||||
const r = entry?.recipeId ? RECIPES[entry.recipeId] : null;
|
||||
if (r) slotKcal += Math.round(r.nutritionPerServing.kcal * Math.max(1, Number(entry.servings) || 1));
|
||||
if (entry?.recipeId && RECIPES[entry.recipeId]) slotKcal += computeEntryNutrition(entry).kcal;
|
||||
});
|
||||
const kcalBadge = slotKcal > 0
|
||||
? `<span class="text-[10px] font-semibold text-amber-600 tabular-nums shrink-0 ml-auto">${slotKcal} kcal</span>`
|
||||
@@ -516,9 +516,14 @@ function renderDayContent(state) {
|
||||
const recipe = entry && entry.recipeId ? RECIPES[entry.recipeId] : null;
|
||||
if (!recipe) return '';
|
||||
const servings = Math.max(1, Number(entry.servings) || 1);
|
||||
const n = recipe.nutritionPerServing;
|
||||
const kcal = Math.round(n.kcal * servings);
|
||||
const entryN = computeEntryNutrition(entry);
|
||||
const eid = escapeHtml(entry.id);
|
||||
const hasCustom = (entry.excludedIngredients?.length > 0) ||
|
||||
(entry.amountOverrides && Object.keys(entry.amountOverrides).length > 0) ||
|
||||
(entry.addedIngredients?.length > 0) ||
|
||||
(entry.substitutions && Object.keys(entry.substitutions).length > 0);
|
||||
const customDot = hasCustom ? '<span class="w-1.5 h-1.5 rounded-full bg-amber-400 inline-block shrink-0 ml-1"></span>' : '';
|
||||
const servLabel = servings > 1 ? `<span class="mx-1.5 text-gray-300">·</span>×${servings}` : '';
|
||||
return `
|
||||
<div class="rounded-lg border border-gray-200 bg-white p-2 shadow-sm" data-slot-id="${slot.id}" data-entry-id="${eid}">
|
||||
<div class="flex items-start justify-between gap-2">
|
||||
@@ -529,25 +534,22 @@ function renderDayContent(state) {
|
||||
: `<span class="w-full h-full flex items-center justify-center text-white text-[8px] font-medium">${escapeHtml(recipe.thumbLabel)}</span>`}
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<p class="text-[13px] font-bold text-gray-900 truncate underline decoration-1 underline-offset-2">${escapeHtml(recipe.title)}</p>
|
||||
<div class="flex items-center"><p class="text-[13px] font-bold text-gray-900 truncate underline decoration-1 underline-offset-2">${escapeHtml(recipe.title)}</p>${customDot}</div>
|
||||
<p class="text-[11px] text-gray-500 mt-0.5 tabular-nums">
|
||||
<i class="fas fa-clock text-gray-400 mr-0.5" aria-hidden="true"></i>${recipe.minutes} min
|
||||
<span class="mx-1.5 text-gray-300">·</span>
|
||||
<i class="fas fa-fire text-gray-400 mr-0.5" aria-hidden="true"></i>${kcal} kcal
|
||||
<i class="fas fa-fire text-gray-400 mr-0.5" aria-hidden="true"></i>${entryN.kcal} kcal${servLabel}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<button type="button" class="planner-clear-meal w-6 h-6 shrink-0 rounded-full border border-gray-200 text-gray-400 hover:text-red-600 hover:border-red-200 hover:bg-red-50 transition-colors flex items-center justify-center" data-slot-id="${slot.id}" data-entry-id="${eid}" aria-label="Usuń ten przepis">
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<button type="button" class="planner-edit-meal w-6 h-6 rounded-full border border-gray-200 text-gray-400 hover:text-gray-900 hover:border-gray-400 hover:bg-gray-50 flex items-center justify-center transition-colors" data-slot-id="${slot.id}" data-entry-id="${eid}" aria-label="Edytuj ten przepis">
|
||||
<i class="fas fa-pencil text-[9px]" aria-hidden="true"></i>
|
||||
</button>
|
||||
<button type="button" class="planner-clear-meal w-6 h-6 rounded-full border border-gray-200 text-gray-400 hover:text-red-600 hover:border-red-200 hover:bg-red-50 transition-colors flex items-center justify-center" data-slot-id="${slot.id}" data-entry-id="${eid}" aria-label="Usuń ten przepis">
|
||||
<i class="fas fa-times text-[9px]" aria-hidden="true"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex items-center justify-between gap-2 mt-1.5 pt-1.5 border-t border-gray-100">
|
||||
<span class="text-[11px] font-medium text-gray-500">Porcje</span>
|
||||
<div class="flex items-center gap-0.5 bg-gray-100 p-0.5 rounded-lg">
|
||||
<button type="button" class="planner-serv-minus w-6 h-6 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black" data-slot-id="${slot.id}" data-entry-id="${eid}" aria-label="Mniej porcji"><i class="fas fa-minus text-[9px]"></i></button>
|
||||
<span class="planner-serv-count font-bold text-gray-900 text-xs w-5 text-center tabular-nums">${servings}</span>
|
||||
<button type="button" class="planner-serv-plus w-6 h-6 bg-white rounded-md shadow-sm flex items-center justify-center text-gray-600 hover:text-black" data-slot-id="${slot.id}" data-entry-id="${eid}" aria-label="Więcej porcji"><i class="fas fa-plus text-[9px]"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
@@ -1016,6 +1018,24 @@ export function setupMealPlanner() {
|
||||
openSheet(pickerBackdrop, pickerSheet);
|
||||
return;
|
||||
}
|
||||
const editBtn = e.target.closest('.planner-edit-meal');
|
||||
if (editBtn) {
|
||||
const slotId = editBtn.getAttribute('data-slot-id');
|
||||
const entryId = editBtn.getAttribute('data-entry-id');
|
||||
const key = dateKey(state.selected);
|
||||
const arr = state.plans[key]?.[slotId];
|
||||
if (!Array.isArray(arr)) return;
|
||||
const entry = arr.find((x) => x && x.id === entryId);
|
||||
if (!entry) return;
|
||||
window.openMealPlanEditor?.({
|
||||
mode: 'edit',
|
||||
recipeId: entry.recipeId,
|
||||
date: state.selected,
|
||||
slotId,
|
||||
entry,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const clearBtn = e.target.closest('.planner-clear-meal');
|
||||
if (clearBtn) {
|
||||
const slotId = clearBtn.getAttribute('data-slot-id');
|
||||
@@ -1031,21 +1051,6 @@ export function setupMealPlanner() {
|
||||
persist();
|
||||
return;
|
||||
}
|
||||
const minus = e.target.closest('.planner-serv-minus');
|
||||
const plus = e.target.closest('.planner-serv-plus');
|
||||
const slotId = (minus || plus)?.getAttribute('data-slot-id');
|
||||
const entryId = (minus || plus)?.getAttribute('data-entry-id');
|
||||
if (!slotId || !entryId) return;
|
||||
const key = dateKey(state.selected);
|
||||
const arr = state.plans[key]?.[slotId];
|
||||
if (!Array.isArray(arr)) return;
|
||||
const entry = arr.find((x) => x && x.id === entryId);
|
||||
if (!entry) return;
|
||||
let s = Math.max(1, Number(entry.servings) || 1);
|
||||
if (minus) s = Math.max(1, s - 1);
|
||||
if (plus) s = Math.min(12, s + 1);
|
||||
entry.servings = s;
|
||||
persist();
|
||||
});
|
||||
|
||||
const closePicker = () => {
|
||||
@@ -1069,13 +1074,16 @@ export function setupMealPlanner() {
|
||||
if (!pick || !state.pickerSlot) return;
|
||||
const recipeId = pick.getAttribute('data-recipe-id');
|
||||
if (!recipeId || !RECIPES[recipeId]) return;
|
||||
const key = dateKey(state.selected);
|
||||
if (!state.plans[key]) state.plans[key] = {};
|
||||
const slotId = state.pickerSlot;
|
||||
if (!state.plans[key][slotId]) state.plans[key][slotId] = [];
|
||||
state.plans[key][slotId].push({ id: newPlanEntryId(), recipeId, servings: 1 });
|
||||
closePicker();
|
||||
persist();
|
||||
setTimeout(() => {
|
||||
window.openMealPlanEditor?.({
|
||||
mode: 'add',
|
||||
recipeId,
|
||||
date: state.selected,
|
||||
slotId,
|
||||
});
|
||||
}, 320);
|
||||
});
|
||||
|
||||
document.getElementById('planner-open-ingredients')?.addEventListener('click', () => {
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
import { RECIPES, INGREDIENTS } from '../data/catalog.js';
|
||||
import { MEAL_SLOTS } from '../planner/mealSlots.js';
|
||||
import { addDays, addMonths, sameDay, sameMonth, startOfDay, startOfMonth, startOfWeekMonday } from '../services/dateUtils.js';
|
||||
import { dateKey, loadPlans, newPlanEntryId, savePlans } from '../services/planStore.js';
|
||||
import { showAppToast } from '../ui/toast.js';
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s)
|
||||
@@ -13,8 +10,6 @@ function escapeHtml(s) {
|
||||
}
|
||||
|
||||
const slotLabelMap = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));
|
||||
const MONTHS_LONG = ['Styczeń', 'Luty', 'Marzec', 'Kwiecień', 'Maj', 'Czerwiec', 'Lipiec', 'Sierpień', 'Wrzesień', 'Październik', 'Listopad', 'Grudzień'];
|
||||
const WEEKDAYS_SHORT = ['Pn', 'Wt', 'Śr', 'Cz', 'Pt', 'So', 'Nd'];
|
||||
|
||||
export function getRecipeDetailHTML() {
|
||||
return `
|
||||
@@ -28,45 +23,6 @@ export function getRecipeDetailHTML() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="rd-planner-picker" class="absolute inset-0 z-50 bg-black/45 hidden flex items-end" style="pointer-events: none">
|
||||
<div id="rd-planner-sheet" class="w-full bg-white rounded-t-3xl shadow-lg p-5 pb-8 max-h-[85vh] overflow-y-auto" style="pointer-events: auto; transform: translateY(100%); transition: transform 300ms cubic-bezier(0.32, 0.72, 0, 1)">
|
||||
<div class="w-10 h-1 bg-gray-200 rounded-full mx-auto mb-4"></div>
|
||||
<h3 class="text-[15px] font-bold text-gray-900 mb-1">Zaplanuj</h3>
|
||||
<p id="rd-planner-recipe-name" class="text-[11px] text-gray-500 mb-3"></p>
|
||||
|
||||
<div class="mb-4">
|
||||
<div class="flex items-center gap-1 mb-2">
|
||||
<button id="rd-cal-prev" type="button" class="shrink-0 w-8 h-8 flex items-center justify-center rounded-full border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"><i class="fas fa-chevron-left text-xs"></i></button>
|
||||
<p id="rd-cal-title" class="flex-1 min-w-0 text-xs font-medium text-gray-900 text-center tabular-nums leading-none px-1 truncate"></p>
|
||||
<button id="rd-cal-next" type="button" class="shrink-0 w-8 h-8 flex items-center justify-center rounded-full border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"><i class="fas fa-chevron-right text-xs"></i></button>
|
||||
</div>
|
||||
<div class="flex items-center justify-center mb-2">
|
||||
<button id="rd-cal-today" type="button" class="h-6 shrink-0 inline-flex items-center justify-center gap-1 rounded-md border border-gray-200 bg-white px-2.5 text-[10px] font-semibold text-gray-700 shadow-sm hover:bg-gray-50 hover:text-gray-900 transition-colors hidden">
|
||||
<i class="fas fa-calendar-day text-[9px] opacity-70"></i> Dziś
|
||||
</button>
|
||||
</div>
|
||||
<div class="grid grid-cols-7 gap-0.5 text-center text-[9px] font-medium text-gray-400 uppercase tracking-wide mb-0.5 leading-none">
|
||||
${WEEKDAYS_SHORT.map((d) => `<div>${d}</div>`).join('')}
|
||||
</div>
|
||||
<div id="rd-cal-grid" class="grid grid-cols-7 gap-0.5"></div>
|
||||
<button id="rd-cal-toggle" type="button" class="w-full flex items-center justify-center py-1 mt-1 text-gray-400 hover:text-gray-600 transition-colors">
|
||||
<i id="rd-cal-toggle-icon" class="fas fa-chevron-down text-[10px]"></i>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Pora posiłku</p>
|
||||
<div id="rd-planner-slots" class="flex flex-wrap gap-1.5 mb-4"></div>
|
||||
|
||||
<div id="rd-planner-variant" class="mb-4 hidden">
|
||||
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Wymienne składniki</p>
|
||||
<div id="rd-planner-variant-options"></div>
|
||||
</div>
|
||||
<button id="rd-planner-confirm" type="button" class="w-full bg-gray-900 hover:bg-black text-white py-3 rounded-xl font-semibold text-[13px] transition-colors flex items-center justify-center gap-2">
|
||||
<i class="fas fa-check text-xs"></i> Dodaj
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="rd-hero" class="h-[220px] shrink-0 w-full bg-[#d4d4d4] relative overflow-hidden">
|
||||
<img id="rd-hero-img" src="" alt="" class="w-full h-full object-cover hidden">
|
||||
<span id="rd-hero-label" class="absolute inset-0 flex items-center justify-center text-white font-medium text-[15px]"></span>
|
||||
@@ -199,11 +155,6 @@ function nutritionForAmount(ingredientId, amount, unit) {
|
||||
};
|
||||
}
|
||||
|
||||
function renderNutritionLine(nutrition) {
|
||||
if (!nutrition) return '';
|
||||
return `<div class="text-[10px] text-gray-500 mt-1 flex flex-wrap gap-x-3 gap-y-0.5"><span>${nutrition.kcal} kcal</span><span>${nutrition.protein}g białko</span><span>${nutrition.fat}g tłuszcz</span><span>${nutrition.carbs}g węgle</span></div>`;
|
||||
}
|
||||
|
||||
/* ── ingredients tab with inline nutrition + summary ───── */
|
||||
|
||||
function computeEffectiveNutritionTotals(recipe) {
|
||||
@@ -443,298 +394,16 @@ export function setupRecipeDetail() {
|
||||
}
|
||||
});
|
||||
|
||||
/* ── planner picker ──────────────────────────────── */
|
||||
/* ── planner — delegate to MealPlanEditor ─────── */
|
||||
|
||||
let plannerPickerDay = null;
|
||||
let plannerPickerSlot = null;
|
||||
let calViewDate = null;
|
||||
let calExpanded = false;
|
||||
|
||||
const plannerOverlay = document.getElementById('rd-planner-picker');
|
||||
const plannerSheet = document.getElementById('rd-planner-sheet');
|
||||
|
||||
function renderCalendarCell(d, today, activeMonth) {
|
||||
const isToday = sameDay(d, today);
|
||||
const isSelected = plannerPickerDay && sameDay(d, plannerPickerDay);
|
||||
const isOtherMonth = d.getMonth() !== activeMonth;
|
||||
const isPast = d.getTime() < today.getTime();
|
||||
|
||||
let cls = 'flex flex-col items-center justify-center rounded-md text-xs font-medium transition-colors w-full min-h-10 py-1 gap-0.5 leading-tight ';
|
||||
|
||||
if (isSelected) {
|
||||
cls += 'bg-gray-900 text-white ';
|
||||
} else if (isPast) {
|
||||
cls += 'text-gray-300 ';
|
||||
} else if (isOtherMonth) {
|
||||
cls += 'text-gray-300 ';
|
||||
} else {
|
||||
cls += 'text-gray-800 hover:bg-gray-100 ';
|
||||
}
|
||||
|
||||
if (isToday && !isSelected && !isPast) {
|
||||
cls += 'ring-1 ring-inset ring-gray-900 ';
|
||||
}
|
||||
|
||||
const inner = `<span>${d.getDate()}</span><span class="w-1 h-1"></span>`;
|
||||
|
||||
if (isPast && !isSelected) {
|
||||
return `<div class="${cls}">${inner}</div>`;
|
||||
}
|
||||
|
||||
return `<button type="button" class="rd-cal-day ${cls}" data-ts="${d.getTime()}">${inner}</button>`;
|
||||
}
|
||||
|
||||
function renderPlannerCalendar() {
|
||||
const grid = document.getElementById('rd-cal-grid');
|
||||
const titleEl = document.getElementById('rd-cal-title');
|
||||
const todayBtn = document.getElementById('rd-cal-today');
|
||||
const toggleIcon = document.getElementById('rd-cal-toggle-icon');
|
||||
if (!grid || !titleEl) return;
|
||||
|
||||
const today = startOfDay(new Date());
|
||||
|
||||
if (calExpanded) {
|
||||
const ms = startOfMonth(calViewDate);
|
||||
titleEl.textContent = `${MONTHS_LONG[ms.getMonth()]} ${ms.getFullYear()}`;
|
||||
toggleIcon.className = 'fas fa-chevron-up text-[10px]';
|
||||
|
||||
const firstCell = startOfWeekMonday(ms);
|
||||
const cells = [];
|
||||
let d = new Date(firstCell);
|
||||
for (let i = 0; i < 42; i++) {
|
||||
cells.push(new Date(d));
|
||||
d = addDays(d, 1);
|
||||
}
|
||||
while (cells.length > 7) {
|
||||
const last7 = cells.slice(-7);
|
||||
if (last7.every((c) => c.getMonth() !== ms.getMonth())) cells.splice(-7);
|
||||
else break;
|
||||
}
|
||||
|
||||
grid.innerHTML = cells.map((c) => renderCalendarCell(c, today, ms.getMonth())).join('');
|
||||
todayBtn.classList.toggle('hidden', sameMonth(today, calViewDate));
|
||||
} else {
|
||||
const ws = startOfWeekMonday(calViewDate);
|
||||
titleEl.textContent = `${MONTHS_LONG[calViewDate.getMonth()]} ${calViewDate.getFullYear()}`;
|
||||
toggleIcon.className = 'fas fa-chevron-down text-[10px]';
|
||||
|
||||
const cells = [];
|
||||
for (let i = 0; i < 7; i++) cells.push(addDays(ws, i));
|
||||
grid.innerHTML = cells.map((c) => renderCalendarCell(c, today, calViewDate.getMonth())).join('');
|
||||
|
||||
const todayWs = startOfWeekMonday(today);
|
||||
todayBtn.classList.toggle('hidden', sameDay(ws, todayWs));
|
||||
}
|
||||
|
||||
grid.querySelectorAll('.rd-cal-day').forEach((btn) => {
|
||||
btn.addEventListener('click', () => {
|
||||
plannerPickerDay = new Date(Number(btn.dataset.ts));
|
||||
calViewDate = new Date(plannerPickerDay);
|
||||
renderPlannerCalendar();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.getElementById('rd-cal-prev')?.addEventListener('click', () => {
|
||||
calViewDate = calExpanded ? addMonths(calViewDate, -1) : addDays(calViewDate, -7);
|
||||
renderPlannerCalendar();
|
||||
});
|
||||
document.getElementById('rd-cal-next')?.addEventListener('click', () => {
|
||||
calViewDate = calExpanded ? addMonths(calViewDate, 1) : addDays(calViewDate, 7);
|
||||
renderPlannerCalendar();
|
||||
});
|
||||
document.getElementById('rd-cal-today')?.addEventListener('click', () => {
|
||||
const today = startOfDay(new Date());
|
||||
plannerPickerDay = today;
|
||||
calViewDate = today;
|
||||
renderPlannerCalendar();
|
||||
});
|
||||
document.getElementById('rd-cal-toggle')?.addEventListener('click', () => {
|
||||
calExpanded = !calExpanded;
|
||||
renderPlannerCalendar();
|
||||
});
|
||||
|
||||
/* ── planner variant selection ────────────────────── */
|
||||
|
||||
const expandedVariantGroups = new Set();
|
||||
|
||||
function renderPlannerVariants(recipe) {
|
||||
const section = document.getElementById('rd-planner-variant');
|
||||
const container = document.getElementById('rd-planner-variant-options');
|
||||
if (!section || !container) return;
|
||||
|
||||
const altsIngredients = recipe.ingredients.filter((i) => i.alternatives?.length > 0);
|
||||
if (altsIngredients.length === 0) {
|
||||
section.classList.add('hidden');
|
||||
return;
|
||||
}
|
||||
section.classList.remove('hidden');
|
||||
|
||||
let html = '';
|
||||
for (const ing of altsIngredients) {
|
||||
const origId = ing.ingredientId;
|
||||
const scaledAmount = ing.amount * currentServings;
|
||||
const displayAmount = Number.isInteger(scaledAmount) ? scaledAmount : parseFloat(scaledAmount.toFixed(1));
|
||||
const effectiveId = getEffectiveIngredientId(origId);
|
||||
const effectiveDef = INGREDIENTS[effectiveId];
|
||||
const effectiveName = effectiveDef?.name || effectiveId;
|
||||
const isExpanded = expandedVariantGroups.has(origId);
|
||||
const isSwapped = effectiveId !== origId;
|
||||
|
||||
html += `<div class="mb-2 last:mb-0">
|
||||
<button type="button" class="rd-variant-toggle w-full flex items-center gap-2.5 p-2.5 rounded-xl border ${isSwapped ? 'border-amber-200 bg-amber-50/50' : 'border-gray-200 bg-white'} hover:border-gray-300 transition-colors text-left" data-original-id="${escapeHtml(origId)}">
|
||||
<i class="fas fa-shuffle text-[9px] ${isSwapped ? 'text-amber-500' : 'text-gray-400'}"></i>
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-[12px] font-semibold text-gray-900 truncate">${escapeHtml(effectiveName)}</span>
|
||||
<span class="text-[10px] text-gray-400 tabular-nums shrink-0">${displayAmount} ${escapeHtml(ing.unit)}</span>
|
||||
</div>
|
||||
${renderNutritionLine(nutritionForAmount(effectiveId, scaledAmount, ing.unit))}
|
||||
</div>
|
||||
<i class="fas fa-chevron-${isExpanded ? 'up' : 'down'} text-[9px] text-gray-400 shrink-0"></i>
|
||||
</button>`;
|
||||
|
||||
if (isExpanded) {
|
||||
const allOptions = [origId, ...ing.alternatives];
|
||||
html += '<div class="mt-1.5 space-y-1 pl-2">';
|
||||
for (const altId of allOptions) {
|
||||
const def = INGREDIENTS[altId];
|
||||
const altName = def?.name || altId;
|
||||
const isSelected = effectiveId === altId;
|
||||
const isOriginal = altId === origId;
|
||||
const nutrition = nutritionForAmount(altId, scaledAmount, ing.unit);
|
||||
|
||||
const selectedCls = isSelected
|
||||
? 'border-gray-900 bg-gray-50 ring-1 ring-gray-900'
|
||||
: 'border-gray-200 bg-white hover:border-gray-300';
|
||||
|
||||
let tag = '';
|
||||
if (isOriginal) tag = `<span class="text-[9px] px-1.5 py-0.5 rounded ${isSelected ? 'bg-gray-200 text-gray-600' : 'bg-gray-100 text-gray-400'} font-medium shrink-0">Domyślny</span>`;
|
||||
|
||||
html += `
|
||||
<button type="button" class="rd-variant-option w-full text-left p-2.5 rounded-lg border transition-all ${selectedCls}" data-original-id="${escapeHtml(origId)}" data-alt-id="${escapeHtml(altId)}">
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2 min-w-0">
|
||||
<div class="w-3.5 h-3.5 rounded-full border-2 shrink-0 ${isSelected ? 'border-gray-900' : 'border-gray-300'} flex items-center justify-center">
|
||||
${isSelected ? '<div class="w-1.5 h-1.5 rounded-full bg-gray-900"></div>' : ''}
|
||||
</div>
|
||||
<span class="text-[12px] font-semibold text-gray-900 truncate">${escapeHtml(altName)}</span>
|
||||
</div>
|
||||
${tag}
|
||||
</div>
|
||||
${renderNutritionLine(nutrition)}
|
||||
</button>`;
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
container.innerHTML = html;
|
||||
}
|
||||
|
||||
document.getElementById('rd-planner-variant-options')?.addEventListener('click', (e) => {
|
||||
const toggle = e.target.closest('.rd-variant-toggle');
|
||||
if (toggle) {
|
||||
const origId = toggle.dataset.originalId;
|
||||
if (expandedVariantGroups.has(origId)) expandedVariantGroups.delete(origId);
|
||||
else expandedVariantGroups.add(origId);
|
||||
const recipe = RECIPES[currentRecipeId];
|
||||
if (recipe) renderPlannerVariants(recipe);
|
||||
return;
|
||||
}
|
||||
|
||||
const btn = e.target.closest('.rd-variant-option');
|
||||
if (!btn) return;
|
||||
const originalId = btn.dataset.originalId;
|
||||
const altId = btn.dataset.altId;
|
||||
if (altId === originalId) {
|
||||
delete currentSubstitutions[originalId];
|
||||
} else {
|
||||
currentSubstitutions[originalId] = altId;
|
||||
}
|
||||
expandedVariantGroups.delete(originalId);
|
||||
const recipe = RECIPES[currentRecipeId];
|
||||
if (recipe) renderPlannerVariants(recipe);
|
||||
});
|
||||
|
||||
function openPlannerPicker() {
|
||||
const recipe = RECIPES[currentRecipeId];
|
||||
if (!recipe) return;
|
||||
|
||||
document.getElementById('rd-planner-recipe-name').textContent = recipe.title;
|
||||
expandedVariantGroups.clear();
|
||||
|
||||
const today = startOfDay(new Date());
|
||||
plannerPickerDay = today;
|
||||
calViewDate = today;
|
||||
calExpanded = false;
|
||||
renderPlannerCalendar();
|
||||
|
||||
renderPlannerVariants(recipe);
|
||||
|
||||
plannerPickerSlot = recipe.allowedSlots[0] || MEAL_SLOTS[0]?.id;
|
||||
const slotsContainer = document.getElementById('rd-planner-slots');
|
||||
slotsContainer.innerHTML = MEAL_SLOTS.filter((s) => recipe.allowedSlots.includes(s.id)).map((s) => {
|
||||
const sel = s.id === plannerPickerSlot;
|
||||
return `<button type="button" class="rd-plan-slot-btn px-3 py-1.5 rounded-lg border text-[12px] font-semibold transition-all ${sel ? 'border-gray-900 bg-gray-900 text-white' : 'border-gray-200 bg-gray-50 text-gray-700 hover:border-gray-400'}" data-slot-id="${s.id}">${escapeHtml(s.label)}</button>`;
|
||||
}).join('');
|
||||
|
||||
plannerOverlay.classList.remove('hidden');
|
||||
plannerOverlay.style.pointerEvents = 'auto';
|
||||
requestAnimationFrame(() => {
|
||||
plannerSheet.style.transform = 'translateY(0)';
|
||||
});
|
||||
}
|
||||
|
||||
function closePlannerPicker() {
|
||||
plannerSheet.style.transform = 'translateY(100%)';
|
||||
setTimeout(() => {
|
||||
plannerOverlay.classList.add('hidden');
|
||||
plannerOverlay.style.pointerEvents = 'none';
|
||||
}, 300);
|
||||
}
|
||||
|
||||
document.getElementById('rd-add-to-planner-btn')?.addEventListener('click', openPlannerPicker);
|
||||
|
||||
plannerOverlay?.addEventListener('click', (e) => {
|
||||
if (e.target === plannerOverlay) closePlannerPicker();
|
||||
});
|
||||
|
||||
document.getElementById('rd-planner-slots')?.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('.rd-plan-slot-btn');
|
||||
if (!btn) return;
|
||||
plannerPickerSlot = btn.getAttribute('data-slot-id');
|
||||
document.querySelectorAll('.rd-plan-slot-btn').forEach((b) => {
|
||||
b.classList.remove('border-gray-900', 'bg-gray-900', 'text-white');
|
||||
b.classList.add('border-gray-200', 'bg-gray-50', 'text-gray-700');
|
||||
});
|
||||
btn.classList.remove('border-gray-200', 'bg-gray-50', 'text-gray-700');
|
||||
btn.classList.add('border-gray-900', 'bg-gray-900', 'text-white');
|
||||
});
|
||||
|
||||
document.getElementById('rd-planner-confirm')?.addEventListener('click', () => {
|
||||
if (!currentRecipeId || !plannerPickerDay || !plannerPickerSlot) return;
|
||||
const plans = loadPlans();
|
||||
const key = dateKey(plannerPickerDay);
|
||||
if (!plans[key]) plans[key] = {};
|
||||
if (!plans[key][plannerPickerSlot]) plans[key][plannerPickerSlot] = [];
|
||||
|
||||
const entry = {
|
||||
id: newPlanEntryId(),
|
||||
document.getElementById('rd-add-to-planner-btn')?.addEventListener('click', () => {
|
||||
if (!currentRecipeId) return;
|
||||
window.openMealPlanEditor?.({
|
||||
mode: 'add',
|
||||
recipeId: currentRecipeId,
|
||||
servings: currentServings,
|
||||
};
|
||||
if (Object.keys(currentSubstitutions).length > 0) {
|
||||
entry.substitutions = { ...currentSubstitutions };
|
||||
}
|
||||
|
||||
plans[key][plannerPickerSlot].push(entry);
|
||||
savePlans(plans);
|
||||
closePlannerPicker();
|
||||
showAppToast('Dodano do planera!');
|
||||
window.refreshPlanner?.();
|
||||
substitutions: { ...currentSubstitutions },
|
||||
});
|
||||
});
|
||||
|
||||
window.openRecipeDetail = (recipeId) => {
|
||||
@@ -746,7 +415,7 @@ export function setupRecipeDetail() {
|
||||
};
|
||||
|
||||
window.closeRecipeDetail = () => {
|
||||
closePlannerPicker();
|
||||
window.closeMealPlanEditor?.();
|
||||
const view = document.getElementById('recipe-detail-view');
|
||||
view.classList.remove('translate-x-0', 'opacity-100', 'pointer-events-auto');
|
||||
view.classList.add('translate-x-full', 'opacity-0', 'pointer-events-none');
|
||||
|
||||
Reference in New Issue
Block a user