Redesign recipe details

This commit is contained in:
2026-04-04 22:26:19 +02:00
parent bfe3074a26
commit b44b985e76
6 changed files with 206 additions and 815 deletions

37
.idea/workspace.xml generated
View File

@@ -4,17 +4,24 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="ae0e4ce8-372f-4cfd-a04f-600640f32223" name="Changes" comment=""> <list default="true" id="ae0e4ce8-372f-4cfd-a04f-600640f32223" name="Changes" comment="Redesign meal plan editor">
<change beforePath="$PROJECT_DIR$/index.html" beforeDir="false" afterPath="$PROJECT_DIR$/index.html" afterDir="false" /> <change beforePath="$PROJECT_DIR$/VIEWS_AND_SCENARIOS.md" beforeDir="false" afterPath="$PROJECT_DIR$/VIEWS_AND_SCENARIOS.md" afterDir="false" />
<change beforePath="$PROJECT_DIR$/js/app.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/app.js" afterDir="false" /> <change beforePath="$PROJECT_DIR$/js/app.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/app.js" afterDir="false" />
<change beforePath="$PROJECT_DIR$/js/ui/mealPlanEditor.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/ui/mealPlanEditor.js" afterDir="false" /> <change beforePath="$PROJECT_DIR$/js/ui/mealPlanEditor.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/ui/mealPlanEditor.js" afterDir="false" />
<change beforePath="$PROJECT_DIR$/js/views/MealPlanner.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/views/MealPlanner.js" afterDir="false" /> <change beforePath="$PROJECT_DIR$/js/views/RecipeDetail.js" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/js/views/RecipeDetailV2.js" beforeDir="false" afterPath="$PROJECT_DIR$/js/views/RecipeDetailV2.js" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" /> <option name="LAST_RESOLUTION" value="IGNORE" />
</component> </component>
<component name="ChangesViewManager">
<option name="groupingKeys">
<option value="directory" />
<option value="repository" />
</option>
</component>
<component name="EmbeddingIndexingInfo"> <component name="EmbeddingIndexingInfo">
<option name="cachedIndexableFilesCount" value="35" /> <option name="cachedIndexableFilesCount" value="35" />
<option name="fileBasedEmbeddingIndicesEnabled" value="true" /> <option name="fileBasedEmbeddingIndicesEnabled" value="true" />
@@ -81,8 +88,25 @@
<option name="number" value="Default" /> <option name="number" value="Default" />
<option name="presentableId" value="Default" /> <option name="presentableId" value="Default" />
<updated>1775222853874</updated> <updated>1775222853874</updated>
<workItem from="1775222854878" duration="3585000" /> <workItem from="1775222854878" duration="5449000" />
</task> </task>
<task id="LOCAL-00001" summary="Rework calendar">
<option name="closed" value="true" />
<created>1775314482369</created>
<option name="number" value="00001" />
<option name="presentableId" value="LOCAL-00001" />
<option name="project" value="LOCAL" />
<updated>1775314482369</updated>
</task>
<task id="LOCAL-00002" summary="Redesign meal plan editor">
<option name="closed" value="true" />
<created>1775332140771</created>
<option name="number" value="00002" />
<option name="presentableId" value="LOCAL-00002" />
<option name="project" value="LOCAL" />
<updated>1775332140771</updated>
</task>
<option name="localTasksCounter" value="3" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@@ -131,4 +155,9 @@
</map> </map>
</option> </option>
</component> </component>
<component name="VcsManagerConfiguration">
<MESSAGE value="Rework calendar" />
<MESSAGE value="Redesign meal plan editor" />
<option name="LAST_COMMIT_MESSAGE" value="Redesign meal plan editor" />
</component>
</project> </project>

View File

@@ -47,7 +47,6 @@ js/
RecipeList.js ← lista przepisów RecipeList.js ← lista przepisów
Filter.js ← overlay filtrów Filter.js ← overlay filtrów
RecipeDetailV2.js ← detal przepisu (aktywna wersja) RecipeDetailV2.js ← detal przepisu (aktywna wersja)
RecipeDetail.js ← detal przepisu (oryginał, nieużywany — 3-zakładkowy)
MealPlanner.js ← planer posiłków + kalendarz MealPlanner.js ← planer posiłków + kalendarz
Pantry.js ← spiżarnia Pantry.js ← spiżarnia
Shopping.js ← listy zakupów Shopping.js ← listy zakupów
@@ -88,8 +87,6 @@ Slide-in overlay z detalami przepisu. Dwie zakładki: **Składniki** i **Kroki**
3. Wymienne składniki — **wstępnie ustawione z wyborów na liście składników**, z możliwością dalszej zmiany 3. Wymienne składniki — **wstępnie ustawione z wyborów na liście składników**, z możliwością dalszej zmiany
4. Przycisk "Dodaj" → zapis do `planStore` (z opcjonalnym obiektem `substitutions`) 4. Przycisk "Dodaj" → zapis do `planStore` (z opcjonalnym obiektem `substitutions`)
> **Uwaga:** Istnieje starsza wersja (`RecipeDetail.js`) z 3 zakładkami (Składniki, Kroki, Wartości) i read-only alternatywami. Aktualnie nieużywana — import w `app.js` wskazuje na `RecipeDetailV2.js`.
**Model danych — wymienne składniki:** **Model danych — wymienne składniki:**
- W `RECIPES`, składnik może mieć pole `alternatives: ['id1', 'id2', ...]` - W `RECIPES`, składnik może mieć pole `alternatives: ['id1', 'id2', ...]`
- Wybrane zamienniki zapisywane jako `substitutions: { originalId: chosenAltId }` w `planStore` - Wybrane zamienniki zapisywane jako `substitutions: { originalId: chosenAltId }` w `planStore`

View File

@@ -3,7 +3,7 @@ import { getFilterHTML, setupFilter } from './views/Filter.js?v=2';
import { getRecipeDetailHTML, setupRecipeDetail } from './views/RecipeDetailV2.js?v=2'; import { getRecipeDetailHTML, setupRecipeDetail } from './views/RecipeDetailV2.js?v=2';
import { getMealPlannerHTML, setupMealPlanner } from './views/MealPlanner.js?v=4'; import { getMealPlannerHTML, setupMealPlanner } from './views/MealPlanner.js?v=4';
import { getPantryHTML, refreshPantry, setupPantry } from './views/Pantry.js?v=2'; import { getPantryHTML, refreshPantry, setupPantry } from './views/Pantry.js?v=2';
import { getMealPlanEditorHTML, setupMealPlanEditor } from './ui/mealPlanEditor.js?v=5'; import { getMealPlanEditorHTML, setupMealPlanEditor } from './ui/mealPlanEditor.js?v=7';
function getAppToastHTML() { function getAppToastHTML() {
return ` return `

View File

@@ -70,7 +70,7 @@ export function getMealPlanEditorHTML() {
<div id="mpe-summary-wrap" class="relative z-[1] shrink-0 px-5 pb-3 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;"> <div id="mpe-summary-wrap" class="relative z-[1] shrink-0 px-5 pb-3 bg-[#2d2e2b]" style="background:#2d2e2b !important; background-image:none !important;">
<div class="flex items-stretch gap-3"> <div class="flex items-stretch gap-3">
<div id="mpe-nutrition-section" class="flex-1 min-w-0"></div> <div id="mpe-nutrition-section" class="flex-1 min-w-0"></div>
<div id="mpe-servings-row" class="shrink-0 w-[6.75rem]"></div> <div id="mpe-servings-row" class="shrink-0 w-[5.25rem]"></div>
</div> </div>
<div id="mpe-top-shadow" class="pointer-events-none absolute inset-x-0 -bottom-3 h-3 opacity-0 transition-opacity duration-200" style="background:linear-gradient(to bottom, rgba(0,0,0,0.12), rgba(0,0,0,0.03), rgba(0,0,0,0));"></div> <div id="mpe-top-shadow" class="pointer-events-none absolute inset-x-0 -bottom-3 h-3 opacity-0 transition-opacity duration-200" style="background:linear-gradient(to bottom, rgba(0,0,0,0.12), rgba(0,0,0,0.03), rgba(0,0,0,0));"></div>
</div> </div>
@@ -103,6 +103,8 @@ export function setupMealPlanEditor() {
recipeId: null, recipeId: null,
date: null, date: null,
slotId: null, slotId: null,
originalDate: null,
originalSlotId: null,
servings: 1, servings: 1,
subs: {}, subs: {},
excluded: new Set(), excluded: new Set(),
@@ -436,6 +438,8 @@ export function setupMealPlanEditor() {
S.mode = opts.mode || 'add'; S.mode = opts.mode || 'add';
S.recipeId = opts.recipeId; S.recipeId = opts.recipeId;
S.originalDate = opts.date ? startOfDay(new Date(opts.date)) : null;
S.originalSlotId = opts.slotId || null;
S.servings = opts.servings || opts.entry?.servings || 1; S.servings = opts.servings || opts.entry?.servings || 1;
S.subs = { ...(opts.substitutions || opts.entry?.substitutions || {}) }; S.subs = { ...(opts.substitutions || opts.entry?.substitutions || {}) };
S.excluded = new Set(opts.entry?.excludedIngredients || []); S.excluded = new Set(opts.entry?.excludedIngredients || []);
@@ -447,9 +451,11 @@ export function setupMealPlanEditor() {
S.addQuery = ''; S.addQuery = '';
if (opts.date && opts.slotId) { if (opts.date && opts.slotId) {
S.date = opts.date; S.date = startOfDay(new Date(opts.date));
S.calDate = new Date(S.date);
S.calExpanded = false;
S.slotId = opts.slotId; S.slotId = opts.slotId;
S.showCal = false; S.showCal = S.mode === 'edit';
} else { } else {
const today = startOfDay(new Date()); const today = startOfDay(new Date());
S.date = today; S.date = today;
@@ -500,18 +506,38 @@ export function setupMealPlanEditor() {
function handleConfirm() { function handleConfirm() {
if (!S.recipeId || !S.date || !S.slotId) return; if (!S.recipeId || !S.date || !S.slotId) return;
const plans = loadPlans(); const plans = loadPlans();
const key = dateKey(S.date); const targetKey = dateKey(S.date);
const nextEntry = buildEntry();
if (S.mode === 'edit' && S.entryId) { if (S.mode === 'edit' && S.entryId) {
const arr = plans[key]?.[S.slotId]; const sourceDate = S.originalDate || S.date;
if (Array.isArray(arr)) { const sourceSlotId = S.originalSlotId || S.slotId;
const sourceKey = dateKey(sourceDate);
const sameTarget = sourceKey === targetKey && sourceSlotId === S.slotId;
if (sameTarget) {
if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
const arr = plans[targetKey][S.slotId];
const idx = arr.findIndex((e) => e.id === S.entryId); const idx = arr.findIndex((e) => e.id === S.entryId);
if (idx >= 0) arr[idx] = buildEntry(); if (idx >= 0) arr[idx] = nextEntry;
else arr.push(nextEntry);
} else {
const sourceArr = plans[sourceKey]?.[sourceSlotId];
if (Array.isArray(sourceArr)) {
const idx = sourceArr.findIndex((e) => e.id === S.entryId);
if (idx >= 0) sourceArr.splice(idx, 1);
if (sourceArr.length === 0 && plans[sourceKey]) delete plans[sourceKey][sourceSlotId];
if (plans[sourceKey] && Object.keys(plans[sourceKey]).length === 0) delete plans[sourceKey];
}
if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
plans[targetKey][S.slotId].push(nextEntry);
} }
} else { } else {
if (!plans[key]) plans[key] = {}; if (!plans[targetKey]) plans[targetKey] = {};
if (!plans[key][S.slotId]) plans[key][S.slotId] = []; if (!plans[targetKey][S.slotId]) plans[targetKey][S.slotId] = [];
plans[key][S.slotId].push(buildEntry()); plans[targetKey][S.slotId].push(nextEntry);
} }
savePlans(plans); savePlans(plans);

View File

@@ -1,667 +0,0 @@
import { RECIPES, INGREDIENTS } from '../data/catalog.js?v=2';
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)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
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 `
<div id="recipe-detail-view" class="absolute inset-0 bg-white z-30 transition-all duration-300 ease-in-out translate-x-full opacity-0 pointer-events-none flex flex-col overflow-hidden">
<div class="absolute top-0 w-full p-3.5 flex justify-between z-40 mt-3">
<button onclick="closeRecipeDetail()" class="w-9 h-9 bg-white/90 backdrop-blur rounded-full flex items-center justify-center shadow-sm text-gray-800 hover:bg-white transition-colors">
<i class="fas fa-arrow-left text-[13px]"></i>
</button>
<button id="rd-add-to-planner-btn" class="h-9 px-3 bg-white/90 backdrop-blur rounded-full flex items-center justify-center gap-1.5 shadow-sm text-gray-800 hover:bg-white transition-colors text-[12px] font-semibold">
<i class="fas fa-calendar-plus text-[11px]"></i> Zaplanuj
</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] flex items-center justify-center relative">
<span id="rd-hero-label" class="text-white font-medium text-[15px]"></span>
</div>
<div class="bg-white rounded-t-3xl -mt-6 relative z-30 pt-6 flex flex-col flex-1 overflow-hidden">
<div class="mb-3 px-5 shrink-0">
<div class="flex justify-between items-start mb-2.5">
<h1 id="rd-title" class="text-xl font-bold text-gray-900"></h1>
</div>
<div id="rd-tags" class="flex flex-wrap gap-1.5 mb-3"></div>
<div class="flex justify-between items-center text-[13px] text-gray-600 font-medium">
<div class="flex gap-3.5">
<div class="flex items-center gap-1.5"><i class="fas fa-clock text-gray-400 text-xs"></i><span id="rd-time"></span></div>
<div class="flex items-center gap-1.5"><i class="fas fa-fire text-gray-400 text-xs"></i><span id="rd-kcal"></span></div>
</div>
<div class="flex items-center gap-0.5 bg-gray-100 p-0.5 rounded-lg">
<button id="rd-serv-minus" class="w-6 h-6 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>
<div class="flex items-center gap-1 px-1.5">
<span id="rd-servings" class="font-bold text-gray-900 text-[13px] w-3 text-center tabular-nums">1</span>
<span class="text-[11px] text-gray-500"><i class="fas fa-user-friends"></i></span>
</div>
<button id="rd-serv-plus" class="w-6 h-6 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>
</div>
</div>
<div class="flex border-b border-gray-200 mb-2 px-5 shrink-0">
<button class="flex-1 pb-2.5 text-[13px] font-semibold text-gray-900 border-b-2 border-gray-900 rd-tab-btn" data-rd-tab="ingredients">Składniki</button>
<button class="flex-1 pb-2.5 text-[13px] font-medium text-gray-500 border-b-2 border-transparent hover:text-gray-700 rd-tab-btn" data-rd-tab="steps">Kroki</button>
<button class="flex-1 pb-2.5 text-[13px] font-medium text-gray-500 border-b-2 border-transparent hover:text-gray-700 rd-tab-btn" data-rd-tab="nutrition">Wartości</button>
</div>
<div class="flex-1 overflow-y-auto px-5 pt-2 pb-10 no-scrollbar relative">
<div id="rd-tab-ingredients" class="rd-tab-content block animate-fade-in"></div>
<div id="rd-tab-steps" class="rd-tab-content hidden animate-fade-in"></div>
<div id="rd-tab-nutrition" class="rd-tab-content hidden animate-fade-in"></div>
</div>
</div>
</div>
`;
}
/* ── state ─────────────────────────────────────────────── */
let currentRecipeId = null;
let currentServings = 1;
let currentSubstitutions = {};
let expandedAlternatives = new Set();
function getEffectiveIngredientId(originalId) {
return currentSubstitutions[originalId] || originalId;
}
/* ── populate ──────────────────────────────────────────── */
function populateDetail(recipeId) {
const recipe = RECIPES[recipeId];
if (!recipe) return;
currentRecipeId = recipeId;
currentServings = 1;
currentSubstitutions = {};
expandedAlternatives.clear();
document.getElementById('rd-hero-label').textContent = `Zdjęcie: ${recipe.title}`;
document.getElementById('rd-title').textContent = recipe.title;
document.getElementById('rd-time').textContent = `${recipe.minutes} min`;
updateKcalDisplay();
const tagsHtml = [];
for (const slotId of recipe.allowedSlots) {
const label = slotLabelMap[slotId];
if (label) tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(label)}</span>`);
}
for (const tag of (recipe.tags || [])) {
tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(tag)}</span>`);
}
document.getElementById('rd-tags').innerHTML = tagsHtml.join('');
document.getElementById('rd-servings').textContent = '1';
renderIngredients(recipe);
renderSteps(recipe);
renderNutrition(recipe);
const tabBtns = document.querySelectorAll('.rd-tab-btn');
const tabs = document.querySelectorAll('.rd-tab-content');
tabBtns.forEach((b) => {
b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold');
b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
});
tabBtns[0]?.classList.remove('text-gray-500', 'border-transparent', 'font-medium');
tabBtns[0]?.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
tabs.forEach((t) => { t.classList.add('hidden'); t.classList.remove('block'); });
document.getElementById('rd-tab-ingredients')?.classList.remove('hidden');
document.getElementById('rd-tab-ingredients')?.classList.add('block');
}
/* ── helpers ───────────────────────────────────────────── */
function updateKcalDisplay() {
const recipe = RECIPES[currentRecipeId];
if (!recipe) return;
const kcal = Math.round(recipe.nutritionPerServing.kcal * currentServings);
document.getElementById('rd-kcal').textContent = `${kcal} kcal`;
}
function nutritionForAmount(ingredientId, amount, unit) {
const def = INGREDIENTS[ingredientId];
if (!def?.nutritionPer100g) return null;
let grams = amount;
if ((unit === 'szt.' || unit === 'szt') && def.weightPerPiece) {
grams = amount * def.weightPerPiece;
}
const f = grams / 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 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 (read-only) ───────────────────────── */
function renderIngredients(recipe) {
const container = document.getElementById('rd-tab-ingredients');
if (!container) return;
const rows = recipe.ingredients.map((ing) => {
const def = INGREDIENTS[ing.ingredientId];
const name = def?.name || ing.ingredientId;
const scaledAmount = ing.amount * currentServings;
const displayAmount = Number.isInteger(scaledAmount) ? scaledAmount : parseFloat(scaledAmount.toFixed(1));
const hasAlts = ing.alternatives && ing.alternatives.length > 0;
const isExpanded = expandedAlternatives.has(ing.ingredientId);
const toggleBtn = hasAlts
? `<button type="button" class="rd-alt-toggle shrink-0 w-6 h-6 rounded-full ${isExpanded ? 'bg-amber-50 text-amber-500' : 'bg-gray-100 text-gray-400 hover:bg-gray-200'} flex items-center justify-center transition-colors" data-original-id="${escapeHtml(ing.ingredientId)}"><i class="fas fa-shuffle text-[9px]"></i></button>`
: '';
let altListHtml = '';
if (hasAlts) {
const altCards = ing.alternatives.map((altId) => {
const altDef = INGREDIENTS[altId];
const altName = escapeHtml(altDef?.name || altId);
const nutrition = nutritionForAmount(altId, scaledAmount, ing.unit);
return `<div class="bg-gray-50 rounded-lg p-2.5 border border-gray-100">
<p class="text-[12px] font-medium text-gray-700">${altName}</p>
${renderNutritionLine(nutrition)}
</div>`;
});
altListHtml = `
<div class="rd-alt-list ${isExpanded ? '' : 'hidden'} mt-2 mb-0.5 space-y-1.5" data-original-id="${escapeHtml(ing.ingredientId)}">
<p class="text-[10px] text-gray-400 font-medium mb-1">Można zamienić na:</p>
${altCards.join('')}
</div>`;
}
return `
<li class="py-2.5 border-b border-gray-100">
<div class="flex items-center gap-2.5 py-0.5">
<span class="text-gray-700 text-[13px] flex-1">${escapeHtml(name)}</span>
${toggleBtn}
<span class="font-medium text-gray-900 text-[13px] tabular-nums">${displayAmount} ${escapeHtml(ing.unit)}</span>
</div>${altListHtml}
</li>`;
}).join('');
container.innerHTML = `
<ul class="space-y-0" id="rd-ingredient-list">${rows}</ul>`;
container.querySelectorAll('.rd-alt-toggle').forEach((btn) => {
btn.addEventListener('click', () => {
const origId = btn.dataset.originalId;
if (expandedAlternatives.has(origId)) {
expandedAlternatives.delete(origId);
} else {
expandedAlternatives.add(origId);
}
const list = container.querySelector(`.rd-alt-list[data-original-id="${origId}"]`);
if (list) list.classList.toggle('hidden');
btn.classList.toggle('bg-gray-100');
btn.classList.toggle('text-gray-400');
btn.classList.toggle('bg-amber-50');
btn.classList.toggle('text-amber-500');
});
});
}
/* ── steps tab ─────────────────────────────────────────── */
function renderSteps(recipe) {
const container = document.getElementById('rd-tab-steps');
if (!container) return;
const steps = recipe.steps || [];
if (steps.length === 0) {
container.innerHTML = '<p class="text-sm text-gray-500 text-center py-8">Brak kroków przygotowania.</p>';
return;
}
container.innerHTML = `
<div class="space-y-5 pb-5">
${steps.map((step, i) => `
<div class="flex gap-3">
<div class="w-6 h-6 rounded-full bg-gray-900 text-white flex items-center justify-center text-[11px] font-bold shrink-0 shadow-sm">${i + 1}</div>
<div class="pt-0.5"><p class="text-[13px] text-gray-600 leading-relaxed">${escapeHtml(step)}</p></div>
</div>`).join('')}
</div>`;
}
/* ── nutrition tab ─────────────────────────────────────── */
function renderNutrition(recipe) {
const container = document.getElementById('rd-tab-nutrition');
if (!container) return;
const n = recipe.nutritionPerServing;
const s = currentServings;
container.innerHTML = `
<div class="bg-gray-50 rounded-xl p-4 border border-gray-100 mb-5">
<p class="text-[11px] text-gray-500 mb-3 font-medium">${s > 1 ? `Wartości dla ${s} porcji` : 'Wartości na 1 porcję'}</p>
<ul class="space-y-0 divide-y divide-gray-200">
<li class="flex justify-between py-2 font-bold"><span class="text-gray-900 text-[13px]">Kalorie</span><span class="text-gray-900 text-[13px] tabular-nums">${Math.round(n.kcal * s)} kcal</span></li>
<li class="flex justify-between py-2"><span class="text-gray-800 text-[13px] font-medium">Białko</span><span class="font-medium text-gray-900 text-[13px] tabular-nums">${Math.round(n.protein * s * 10) / 10} g</span></li>
<li class="flex justify-between py-2"><span class="text-gray-800 text-[13px] font-medium">Tłuszcze</span><span class="font-medium text-gray-900 text-[13px] tabular-nums">${Math.round(n.fat * s * 10) / 10} g</span></li>
<li class="flex justify-between py-2"><span class="text-gray-800 text-[13px] font-medium">Węglowodany</span><span class="font-medium text-gray-900 text-[13px] tabular-nums">${Math.round(n.carbs * s * 10) / 10} g</span></li>
</ul>
</div>`;
}
/* ── setup ─────────────────────────────────────────────── */
export function setupRecipeDetail() {
document.querySelectorAll('.rd-tab-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const tabId = btn.dataset.rdTab;
document.querySelectorAll('.rd-tab-content').forEach((el) => {
el.classList.add('hidden');
el.classList.remove('block');
});
const target = document.getElementById(`rd-tab-${tabId}`);
if (target) {
target.classList.remove('hidden');
target.classList.add('block');
target.parentElement.scrollTop = 0;
}
document.querySelectorAll('.rd-tab-btn').forEach((b) => {
b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold');
b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
});
btn.classList.remove('text-gray-500', 'border-transparent', 'font-medium');
btn.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
});
});
document.getElementById('rd-serv-minus')?.addEventListener('click', () => {
if (currentServings <= 1) return;
currentServings--;
document.getElementById('rd-servings').textContent = currentServings;
const recipe = RECIPES[currentRecipeId];
if (recipe) {
renderIngredients(recipe);
renderNutrition(recipe);
updateKcalDisplay();
}
});
document.getElementById('rd-serv-plus')?.addEventListener('click', () => {
if (currentServings >= 12) return;
currentServings++;
document.getElementById('rd-servings').textContent = currentServings;
const recipe = RECIPES[currentRecipeId];
if (recipe) {
renderIngredients(recipe);
renderNutrition(recipe);
updateKcalDisplay();
}
});
/* ── planner picker ──────────────────────────────── */
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;
currentSubstitutions = {};
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(),
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?.();
});
window.openRecipeDetail = (recipeId) => {
if (!recipeId || !RECIPES[recipeId]) return;
populateDetail(recipeId);
const view = document.getElementById('recipe-detail-view');
view.classList.remove('translate-x-full', 'opacity-0', 'pointer-events-none');
view.classList.add('translate-x-0', 'opacity-100', 'pointer-events-auto');
};
window.closeRecipeDetail = () => {
closePlannerPicker();
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');
};
}

View File

@@ -10,51 +10,79 @@ function escapeHtml(s) {
} }
const slotLabelMap = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label])); const slotLabelMap = Object.fromEntries(MEAL_SLOTS.map((s) => [s.id, s.label]));
const RD_THEME = Object.freeze({
surface: '#393937',
surfaceSoft: '#2f2f2d',
surfaceActive: '#23221e',
border: '#444442',
borderSoft: '#56534f',
borderStrong: '#787876',
textPrimary: '#ddd6ca',
textSecondary: '#d7d2c8',
textMuted: '#9b978f',
});
function forceBg(bg) {
return `background:${bg} !important; background-image:none !important; box-shadow:none !important;`;
}
function forceBgBorder(bg, border) {
return `${forceBg(bg)} border:1px solid ${border} !important;`;
}
function renderTagChip(label) {
return `<span class="px-3 py-1 rounded-full text-[11px] font-semibold inline-flex items-center" style="${forceBgBorder(RD_THEME.surfaceSoft, RD_THEME.border)} color:${RD_THEME.textSecondary} !important;">${escapeHtml(label)}</span>`;
}
function setTabButtonState(btn, active) {
if (!btn) return;
btn.style.color = active ? RD_THEME.textPrimary : RD_THEME.textMuted;
btn.style.borderBottomColor = active ? RD_THEME.borderStrong : 'transparent';
btn.style.fontWeight = active ? '600' : '500';
}
export function getRecipeDetailHTML() { export function getRecipeDetailHTML() {
return ` return `
<div id="recipe-detail-view" class="absolute inset-0 bg-[#2d2e2b] z-30 transition-all duration-300 ease-in-out translate-x-full opacity-0 pointer-events-none flex flex-col overflow-hidden"> <div id="recipe-detail-view" class="absolute inset-0 bg-[#2d2e2b] z-30 transition-all duration-300 ease-in-out translate-x-full opacity-0 pointer-events-none flex flex-col overflow-hidden" style="background:#2d2e2b !important; background-image:none !important;">
<div class="absolute top-0 w-full p-3.5 flex justify-between z-40 mt-3"> <div class="absolute top-0 w-full p-3.5 flex justify-between z-40 mt-3">
<button onclick="closeRecipeDetail()" class="w-9 h-9 bg-white/90 backdrop-blur rounded-full flex items-center justify-center shadow-sm text-gray-800 hover:bg-white transition-colors"> <button onclick="closeRecipeDetail()" class="w-9 h-9 rounded-full border flex items-center justify-center transition-opacity opacity-95 hover:opacity-100" style="background:rgba(47,47,45,0.92) !important; backdrop-filter:none !important; border-color:#444442 !important; color:#ddd6ca !important;">
<i class="fas fa-arrow-left text-[13px]"></i> <i class="fas fa-arrow-left text-[13px]"></i>
</button> </button>
<button id="rd-add-to-planner-btn" class="h-9 px-3 bg-white/90 backdrop-blur rounded-full flex items-center justify-center gap-1.5 shadow-sm text-gray-800 hover:bg-white transition-colors text-[12px] font-semibold"> <button id="rd-add-to-planner-btn" class="h-9 px-3 rounded-full border flex items-center justify-center gap-1.5 transition-opacity opacity-95 hover:opacity-100 text-[12px] font-semibold" style="background:rgba(47,47,45,0.92) !important; backdrop-filter:none !important; border-color:#444442 !important; color:#ddd6ca !important;">
<i class="fas fa-calendar-plus text-[11px]"></i> Zaplanuj <i class="fas fa-calendar-plus text-[11px]"></i> Zaplanuj
</button> </button>
</div> </div>
<div id="rd-hero" class="h-[220px] shrink-0 w-full bg-[#d4d4d4] relative overflow-hidden"> <div id="rd-hero" class="h-[236px] shrink-0 w-full relative overflow-hidden" style="background:linear-gradient(180deg, #3a3937 0%, #23221e 100%) !important;">
<img id="rd-hero-img" src="" alt="" class="w-full h-full object-cover 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> <div class="absolute inset-0 pointer-events-none" style="background:linear-gradient(to bottom, rgba(45,46,43,0.1), rgba(45,46,43,0.4), rgba(45,46,43,0.92));"></div>
<span id="rd-hero-label" class="absolute inset-0 z-10 flex items-center justify-center font-medium text-[15px]" style="color:#ddd6ca;"></span>
</div> </div>
<div class="bg-[#2d2e2b] rounded-t-3xl -mt-6 relative z-30 pt-6 flex flex-col flex-1 overflow-hidden"> <div class="bg-[#2d2e2b] rounded-t-3xl -mt-6 relative z-30 pt-6 flex flex-col flex-1 overflow-hidden" style="background:#2d2e2b !important; background-image:none !important;">
<div class="mb-3 px-5 shrink-0"> <div class="mb-3 px-5 shrink-0">
<div class="flex justify-between items-start mb-2.5"> <div class="flex justify-between items-start mb-2.5">
<h1 id="rd-title" class="text-xl font-bold text-gray-900"></h1> <h1 id="rd-title" class="text-xl font-bold leading-tight" style="color:#ddd6ca;"></h1>
</div> </div>
<div id="rd-tags" class="flex flex-wrap gap-1.5 mb-3"></div> <div id="rd-tags" class="flex flex-wrap gap-1.5 mb-3"></div>
<div class="flex justify-between items-center text-[13px] text-gray-600 font-medium"> <div class="flex flex-wrap gap-2 text-[13px] font-medium">
<div class="flex gap-3.5"> <div class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border" style="background:#2f2f2d; border-color:#444442; color:#d7d2c8;">
<div class="flex items-center gap-1.5"><i class="fas fa-clock text-gray-400 text-xs"></i><span id="rd-time"></span></div> <i class="fas fa-clock text-[10px]" style="color:#9b978f;"></i>
<span id="rd-time"></span>
</div> </div>
<div class="flex items-center gap-0.5 bg-gray-100 p-0.5 rounded-lg"> <div class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border" style="background:#2f2f2d; border-color:#444442; color:#d7d2c8;">
<button id="rd-serv-minus" class="w-6 h-6 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> <i class="fas fa-fire text-[10px]" style="color:#9b978f;"></i>
<div class="flex items-center gap-1 px-1.5"> <span id="rd-kcal" class="tabular-nums"></span>
<span id="rd-servings" class="font-bold text-gray-900 text-[13px] w-3 text-center tabular-nums">1</span>
<span class="text-[11px] text-gray-500"><i class="fas fa-user-friends"></i></span>
</div>
<button id="rd-serv-plus" class="w-6 h-6 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> </div>
</div> </div>
</div> </div>
<div class="flex border-b border-gray-200 mb-2 px-5 shrink-0"> <div class="flex border-b mb-2 px-5 shrink-0" style="border-color:#444442;">
<button class="flex-1 pb-2.5 text-[13px] font-semibold text-gray-900 border-b-2 border-gray-900 rd-tab-btn" data-rd-tab="ingredients">Składniki</button> <button class="flex-1 pb-2.5 text-[13px] border-b-2 rd-tab-btn" data-rd-tab="ingredients" style="color:#ddd6ca; border-bottom-color:#787876; font-weight:600;">Składniki</button>
<button class="flex-1 pb-2.5 text-[13px] font-medium text-gray-500 border-b-2 border-transparent hover:text-gray-700 rd-tab-btn" data-rd-tab="steps">Kroki</button> <button class="flex-1 pb-2.5 text-[13px] border-b-2 rd-tab-btn" data-rd-tab="steps" style="color:#9b978f; border-bottom-color:transparent; font-weight:500;">Kroki</button>
</div> </div>
<div class="flex-1 overflow-y-auto px-5 pt-2 pb-10 no-scrollbar relative"> <div class="flex-1 overflow-y-auto px-5 pt-2 pb-10 no-scrollbar relative" style="background:#2d2e2b !important; background-image:none !important; padding-bottom:calc(2.5rem + env(safe-area-inset-bottom));">
<div id="rd-tab-ingredients" class="rd-tab-content block animate-fade-in"></div> <div id="rd-tab-ingredients" class="rd-tab-content block animate-fade-in"></div>
<div id="rd-tab-steps" class="rd-tab-content hidden animate-fade-in"></div> <div id="rd-tab-steps" class="rd-tab-content hidden animate-fade-in"></div>
</div> </div>
@@ -104,13 +132,12 @@ function populateDetail(recipeId) {
const tagsHtml = []; const tagsHtml = [];
for (const slotId of recipe.allowedSlots) { for (const slotId of recipe.allowedSlots) {
const label = slotLabelMap[slotId]; const label = slotLabelMap[slotId];
if (label) tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(label)}</span>`); if (label) tagsHtml.push(renderTagChip(label));
} }
for (const tag of (recipe.tags || [])) { for (const tag of (recipe.tags || [])) {
tagsHtml.push(`<span class="px-2.5 py-0.5 bg-gray-100 text-gray-700 text-[11px] rounded-md font-medium">${escapeHtml(tag)}</span>`); tagsHtml.push(renderTagChip(tag));
} }
document.getElementById('rd-tags').innerHTML = tagsHtml.join(''); document.getElementById('rd-tags').innerHTML = tagsHtml.join('');
document.getElementById('rd-servings').textContent = '1';
renderIngredients(recipe); renderIngredients(recipe);
renderSteps(recipe); renderSteps(recipe);
@@ -118,11 +145,9 @@ function populateDetail(recipeId) {
const tabBtns = document.querySelectorAll('.rd-tab-btn'); const tabBtns = document.querySelectorAll('.rd-tab-btn');
const tabs = document.querySelectorAll('.rd-tab-content'); const tabs = document.querySelectorAll('.rd-tab-content');
tabBtns.forEach((b) => { tabBtns.forEach((b) => {
b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold'); setTabButtonState(b, false);
b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
}); });
tabBtns[0]?.classList.remove('text-gray-500', 'border-transparent', 'font-medium'); setTabButtonState(tabBtns[0], true);
tabBtns[0]?.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
tabs.forEach((t) => { t.classList.add('hidden'); t.classList.remove('block'); }); tabs.forEach((t) => { t.classList.add('hidden'); t.classList.remove('block'); });
document.getElementById('rd-tab-ingredients')?.classList.remove('hidden'); document.getElementById('rd-tab-ingredients')?.classList.remove('hidden');
document.getElementById('rd-tab-ingredients')?.classList.add('block'); document.getElementById('rd-tab-ingredients')?.classList.add('block');
@@ -155,6 +180,10 @@ function nutritionForAmount(ingredientId, amount, unit) {
}; };
} }
function fmtAmt(n) {
return Number.isInteger(n) ? String(n) : String(parseFloat(n.toFixed(1)));
}
/* ── ingredients tab with inline nutrition + summary ───── */ /* ── ingredients tab with inline nutrition + summary ───── */
function computeEffectiveNutritionTotals(recipe) { function computeEffectiveNutritionTotals(recipe) {
@@ -178,58 +207,42 @@ function computeEffectiveNutritionTotals(recipe) {
} }
function renderNutritionSummary(recipe) { function renderNutritionSummary(recipe) {
const s = currentServings;
const total = computeEffectiveNutritionTotals(recipe); const total = computeEffectiveNutritionTotals(recipe);
return ` return `
<div class="mb-4 pt-1 pb-3 border-b border-gray-100"> <div class="mb-4">
${s > 1 ? `<p class="text-[10px] text-gray-400 font-medium mb-2">Wartości dla ${s} porcji</p>` : ''} <div class="flex items-stretch gap-3">
<div class="grid grid-cols-4 gap-3 text-center">
<div>
<span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.kcal}</span>
<span class="text-[10px] text-gray-500">Kalorie</span>
</div>
<div>
<span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.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">${total.carbs} g</span>
<span class="text-[10px] text-gray-500">Węglo.</span>
</div>
<div>
<span class="block text-[14px] font-bold text-gray-900 tabular-nums">${total.fat} g</span>
<span class="text-[10px] text-gray-500">Tłuszcze</span>
</div>
</div>
</div>`;
}
function renderIngredientCard(name, amount, unit, nutrition, extra) {
const displayAmount = Number.isInteger(amount) ? amount : parseFloat(amount.toFixed(1));
const macroHtml = nutrition
? `<div class="flex flex-wrap gap-x-2.5 text-[10px] text-gray-400 tabular-nums">
<span>${nutrition.protein}g B</span><span>${nutrition.fat}g T</span><span>${nutrition.carbs}g W</span>
</div>`
: '';
const kcalHtml = nutrition
? `<span class="text-[10px] font-medium text-gray-400 tabular-nums whitespace-nowrap">${nutrition.kcal} kcal</span>`
: '';
return `
<div class="${extra?.cls || 'bg-white'} rounded-xl p-2.5 border ${extra?.border || 'border-gray-200'} flex items-center gap-2.5" ${extra?.dataAttrs || ''}>
<div class="flex-1 min-w-0"> <div class="flex-1 min-w-0">
<div class="flex items-center gap-2"> <div class="h-full pb-2 flex flex-col" style="background:#2d2e2b !important; background-image:none !important; box-shadow:none !important;">
${extra?.prefix || ''} <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Wartości odżywcze</p>
<span class="text-[12px] font-semibold text-gray-900 truncate">${escapeHtml(name)}</span> <div class="flex-1 flex items-center">
${extra?.suffix || ''} <div class="rounded-xl border px-3 py-2" style="border-color:#444442 !important;">
<div class="grid grid-flow-col auto-cols-max gap-3 text-left">
<div><span class="block text-[15px] font-semibold text-[#ddd6ca] tabular-nums leading-none">${total.kcal}</span><span class="text-[9px] text-gray-500">kcal</span></div>
<div><span class="block text-[15px] font-semibold text-[#ddd6ca] tabular-nums leading-none">${total.protein}<span class="ml-0.5 text-[12px] font-medium text-[#9b978f]">g</span></span><span class="text-[9px] text-gray-500">Białko</span></div>
<div><span class="block text-[15px] font-semibold text-[#ddd6ca] tabular-nums leading-none">${total.carbs}<span class="ml-0.5 text-[12px] font-medium text-[#9b978f]">g</span></span><span class="text-[9px] text-gray-500">Węgle</span></div>
<div><span class="block text-[15px] font-semibold text-[#ddd6ca] tabular-nums leading-none">${total.fat}<span class="ml-0.5 text-[12px] font-medium text-[#9b978f]">g</span></span><span class="text-[9px] text-gray-500">Tłuszcze</span></div>
</div>
</div>
</div>
</div>
</div>
<div class="shrink-0 w-[5.25rem]">
<div class="h-full rounded-xl pb-2 flex flex-col" style="background:#2d2e2b !important; background-image:none !important; box-shadow:none !important;">
<p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-2">Porcje</p>
<div class="flex items-center pt-2">
<div class="flex h-[2rem] w-full items-center gap-0.5 rounded-full border px-0.5" style="background:#2f2f2d;border-color:#444442;">
<button type="button" id="rd-serv-minus" class="shrink-0 w-7 h-full flex items-center justify-center rounded-full border-0 bg-transparent text-[#d7d2c8] transition-colors" aria-label="Zmniejsz liczbę porcji">
<i class="fas fa-minus text-[10px]"></i>
</button>
<span id="rd-servings" class="flex-1 h-full inline-flex items-center justify-center px-0.5 text-[12px] font-semibold leading-none text-[#d7d2c8] tabular-nums">${currentServings}</span>
<button type="button" id="rd-serv-plus" class="shrink-0 w-7 h-full flex items-center justify-center rounded-full border-0 bg-transparent text-[#d7d2c8] transition-colors" aria-label="Zwiększ liczbę porcji">
<i class="fas fa-plus text-[10px]"></i>
</button>
</div>
</div>
</div> </div>
${macroHtml}
${extra?.badge || ''}
</div> </div>
<div class="flex flex-col items-end shrink-0 gap-0.5">
<span class="text-[12px] font-semibold text-gray-900 tabular-nums whitespace-nowrap">${displayAmount} ${escapeHtml(unit)}</span>
${kcalHtml}
</div> </div>
</div>`; </div>`;
} }
@@ -245,21 +258,24 @@ function renderIngredients(recipe) {
const effectiveDef = INGREDIENTS[effectiveId]; const effectiveDef = INGREDIENTS[effectiveId];
const effectiveName = effectiveDef?.name || effectiveId; const effectiveName = effectiveDef?.name || effectiveId;
const scaledAmount = ing.amount * currentServings; const scaledAmount = ing.amount * currentServings;
const nutrition = nutritionForAmount(effectiveId, scaledAmount, ing.unit);
const isSwapped = effectiveId !== origId;
const isExpanded = expandedAlternatives.has(origId); const isExpanded = expandedAlternatives.has(origId);
const rowStyle = 'background:#393937 !important; background-image:none !important; box-shadow:none !important; border:none !important;';
const toggleBtn = hasAlts const toggleBtn = hasAlts
? `<button type="button" class="rd-alt-toggle shrink-0 w-5 h-5 rounded-full ${isExpanded ? 'bg-amber-50 text-amber-500' : isSwapped ? 'bg-amber-50 text-amber-500' : 'bg-gray-100 text-gray-400 hover:bg-gray-200'} flex items-center justify-center transition-colors" data-original-id="${escapeHtml(origId)}"><i class="fas fa-shuffle text-[8px]"></i></button>` ? `<button type="button" class="rd-alt-toggle shrink-0 w-5 h-5 flex items-center justify-center transition-colors text-gray-400 hover:text-gray-300" style="background:transparent !important; box-shadow:none !important;" data-original-id="${escapeHtml(origId)}" aria-label="Wybierz zamiennik składnika"><i class="fas fa-shuffle text-[10px]"></i></button>`
: ''; : '';
const cardBorder = isSwapped ? 'border-amber-200' : 'border-gray-200'; let rowHtml = `<div class="rd-ing-row rounded-xl p-2.5" style="${rowStyle}" data-original-id="${escapeHtml(origId)}">`;
const cardCls = isSwapped ? 'bg-amber-50/30' : 'bg-white'; rowHtml += '<div class="flex items-center gap-2">';
const cardHtml = renderIngredientCard(effectiveName, scaledAmount, ing.unit, nutrition, { rowHtml += `<div class="flex-1 min-w-0"><span class="text-[12px] font-semibold text-gray-900 truncate block">${escapeHtml(effectiveName)}</span></div>`;
suffix: toggleBtn, rowHtml += '<div class="shrink-0 flex items-center gap-2">';
border: cardBorder, rowHtml += toggleBtn;
cls: cardCls, rowHtml += `<div class="shrink-0 flex items-center gap-1 px-2 py-1 rounded-lg">
}); <span class="text-[12px] font-semibold text-gray-900 tabular-nums">${fmtAmt(scaledAmount)}</span>
<span class="text-[11px] text-gray-500">${escapeHtml(ing.unit)}</span>
</div>`;
rowHtml += '</div>';
rowHtml += '</div>';
let altListHtml = ''; let altListHtml = '';
if (hasAlts && isExpanded) { if (hasAlts && isExpanded) {
@@ -268,32 +284,46 @@ function renderIngredients(recipe) {
const def = INGREDIENTS[altId]; const def = INGREDIENTS[altId];
const altName = def?.name || altId; const altName = def?.name || altId;
const isSelected = effectiveId === altId; const isSelected = effectiveId === altId;
const isOriginal = altId === origId;
const altNutrition = nutritionForAmount(altId, scaledAmount, ing.unit); const altNutrition = nutritionForAmount(altId, scaledAmount, ing.unit);
const checkbox = `
<span class="ml-auto self-center w-[18px] h-[18px] rounded-full shrink-0 flex items-center justify-center"
style="border:1.5px solid #56534f; background:transparent;">
${isSelected ? '<i class="fas fa-check" style="color:#9b978f; font-size:8px; line-height:1; display:block; transform:translateY(0.5px);"></i>' : ''}
</span>`;
const nutritionLine = altNutrition
? `<div class="text-[10px] text-gray-400 mt-0.5 tabular-nums">${altNutrition.kcal} kcal · ${altNutrition.protein}g B · ${altNutrition.fat}g T · ${altNutrition.carbs}g W</div>`
: '';
const radioDot = `<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>`; return `<button type="button" class="rd-alt-pick w-full text-left p-2.5 rounded-lg transition-all" style="background:#2f2f2d !important; background-image:none !important; border:none !important; box-shadow:none !important;" data-original-id="${escapeHtml(origId)}" data-alt-id="${escapeHtml(altId)}"><div class="flex items-center gap-3"><div class="min-w-0 flex-1"><div class="text-[11px] font-semibold text-gray-900">${escapeHtml(altName)}</div>${nutritionLine}</div>${checkbox}</div></button>`;
const defaultTag = isOriginal ? `<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 ml-1">Domyślny</span>` : '';
return renderIngredientCard(altName, scaledAmount, ing.unit, altNutrition, {
cls: isSelected ? 'bg-gray-50' : 'bg-white hover:bg-gray-50 cursor-pointer',
border: isSelected ? 'border-gray-900 ring-1 ring-gray-900' : 'border-gray-100',
prefix: radioDot,
badge: defaultTag,
dataAttrs: `data-original-id="${escapeHtml(origId)}" data-alt-id="${escapeHtml(altId)}"`,
});
}); });
altListHtml = ` altListHtml = `
<div class="mt-1.5 space-y-1.5 rd-alt-options" data-original-id="${escapeHtml(origId)}"> <div class="mt-2 ml-1 space-y-1 rd-alt-options" data-original-id="${escapeHtml(origId)}">
${optionCards.join('')} ${optionCards.join('')}
</div>`; </div>`;
} }
return `<li>${cardHtml}${altListHtml}</li>`; rowHtml += altListHtml;
rowHtml += '</div>';
return `<li>${rowHtml}</li>`;
}).join(''); }).join('');
container.innerHTML = ` container.innerHTML = `
${renderNutritionSummary(recipe)} ${renderNutritionSummary(recipe)}
<ul class="space-y-2" id="rd-ingredient-list">${rows}</ul>`; <ul class="space-y-1.5" id="rd-ingredient-list">${rows}</ul>`;
container.querySelector('#rd-serv-minus')?.addEventListener('click', () => {
if (currentServings <= 1) return;
currentServings--;
renderIngredients(recipe);
updateKcalDisplay();
});
container.querySelector('#rd-serv-plus')?.addEventListener('click', () => {
if (currentServings >= 12) return;
currentServings++;
renderIngredients(recipe);
updateKcalDisplay();
});
container.querySelectorAll('.rd-alt-toggle').forEach((btn) => { container.querySelectorAll('.rd-alt-toggle').forEach((btn) => {
btn.addEventListener('click', () => { btn.addEventListener('click', () => {
@@ -332,16 +362,16 @@ function renderSteps(recipe) {
const steps = recipe.steps || []; const steps = recipe.steps || [];
if (steps.length === 0) { if (steps.length === 0) {
container.innerHTML = '<p class="text-sm text-gray-500 text-center py-8">Brak kroków przygotowania.</p>'; container.innerHTML = `<p class="text-sm text-center py-8" style="color:${RD_THEME.textMuted};">Brak kroków przygotowania.</p>`;
return; return;
} }
container.innerHTML = ` container.innerHTML = `
<div class="space-y-5 pb-5"> <div class="space-y-2 pb-5">
${steps.map((step, i) => ` ${steps.map((step, i) => `
<div class="flex gap-3"> <div class="rounded-xl p-3 flex gap-3" style="${forceBg(RD_THEME.surface)} border:none !important;">
<div class="w-6 h-6 rounded-full bg-gray-900 text-white flex items-center justify-center text-[11px] font-bold shrink-0 shadow-sm">${i + 1}</div> <div class="w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-bold shrink-0" style="${forceBgBorder(RD_THEME.surfaceActive, RD_THEME.borderSoft)} color:${RD_THEME.textSecondary} !important;">${i + 1}</div>
<div class="pt-0.5"><p class="text-[13px] text-gray-600 leading-relaxed">${escapeHtml(step)}</p></div> <div class="pt-0.5"><p class="text-[13px] leading-relaxed" style="color:${RD_THEME.textSecondary};">${escapeHtml(step)}</p></div>
</div>`).join('')} </div>`).join('')}
</div>`; </div>`;
} }
@@ -364,36 +394,12 @@ export function setupRecipeDetail() {
} }
document.querySelectorAll('.rd-tab-btn').forEach((b) => { document.querySelectorAll('.rd-tab-btn').forEach((b) => {
b.classList.remove('text-gray-900', 'border-gray-900', 'font-semibold'); setTabButtonState(b, false);
b.classList.add('text-gray-500', 'border-transparent', 'font-medium');
}); });
btn.classList.remove('text-gray-500', 'border-transparent', 'font-medium'); setTabButtonState(btn, true);
btn.classList.add('text-gray-900', 'border-gray-900', 'font-semibold');
}); });
}); });
document.getElementById('rd-serv-minus')?.addEventListener('click', () => {
if (currentServings <= 1) return;
currentServings--;
document.getElementById('rd-servings').textContent = currentServings;
const recipe = RECIPES[currentRecipeId];
if (recipe) {
renderIngredients(recipe);
updateKcalDisplay();
}
});
document.getElementById('rd-serv-plus')?.addEventListener('click', () => {
if (currentServings >= 12) return;
currentServings++;
document.getElementById('rd-servings').textContent = currentServings;
const recipe = RECIPES[currentRecipeId];
if (recipe) {
renderIngredients(recipe);
updateKcalDisplay();
}
});
/* ── planner — delegate to MealPlanEditor ─────── */ /* ── planner — delegate to MealPlanEditor ─────── */
document.getElementById('rd-add-to-planner-btn')?.addEventListener('click', () => { document.getElementById('rd-add-to-planner-btn')?.addEventListener('click', () => {