Redesign pantry horizon controls

This commit is contained in:
2026-04-14 23:14:28 +02:00
parent 71b91b50b4
commit d3a68a80eb
3 changed files with 495 additions and 100 deletions

View File

@@ -601,7 +601,7 @@
</div> </div>
<script> <script>
const APP_ASSET_VERSION = '20260410-110'; const APP_ASSET_VERSION = '20260414-118';
const APP_VERSION_STORAGE_KEY = 'recipe-app-asset-version'; const APP_VERSION_STORAGE_KEY = 'recipe-app-asset-version';
const APP_VERSION_QUERY_KEY = 'appv'; const APP_VERSION_QUERY_KEY = 'appv';

View File

@@ -1,7 +1,7 @@
import { INGREDIENTS, RECIPES, PRODUCTS, getProductsForIngredient } from '../data/catalog.js?v=8'; import { INGREDIENTS, RECIPES, PRODUCTS, getProductsForIngredient } from '../data/catalog.js?v=8';
import { MEAL_SLOTS } from '../planner/mealSlots.js'; import { MEAL_SLOTS } from '../planner/mealSlots.js';
import { addDays } from './dateUtils.js'; import { addDays } from './dateUtils.js';
import { getDayPlan } from './planStore.js?v=2'; import { dateKey, getDayPlan } from './planStore.js?v=2';
import { getPantryTotal } from './pantryShopping.js?v=2'; import { getPantryTotal } from './pantryShopping.js?v=2';
export function dayHasAnyMeal(plans, d) { export function dayHasAnyMeal(plans, d) {
@@ -182,6 +182,42 @@ export function aggregateWeekIngredientNeed(plans, weekStart) {
return mergeIngredientLines(all); return mergeIngredientLines(all);
} }
/**
* Zapotrzebowanie składników od startDate przez numDays dni.
* Jak aggregateWeekIngredientNeed, ale z dowolnym zakresem i informacją
* w które dni dany składnik jest potrzebny.
* @param {Record<string, unknown>} plans
* @param {Date} startDate
* @param {number} numDays
* @returns {Array<{ingredientId: string, name: string, category: string, amount: number, unit: string, days: string[]}>}
*/
export function aggregateRangeIngredientNeed(plans, startDate, numDays) {
/** @type {Map<string, {ingredientId: string, name: string, category: string, amount: number, unit: string, days: Set<string>}>} */
const map = new Map();
for (let i = 0; i < numDays; i++) {
const day = addDays(startDate, i);
const dk = dateKey(day);
const dayPlan = getDayPlan(plans, day);
const lines = flattenDayIngredientLines(dayPlan);
for (const line of lines) {
const key = `${line.ingredientId}\t${line.unit}`;
const cur = map.get(key);
if (!cur) {
map.set(key, { ...line, days: new Set([dk]) });
} else {
cur.amount = Math.round((cur.amount + line.amount) * 10) / 10;
cur.days.add(dk);
}
}
}
return [...map.values()]
.map((item) => ({ ...item, days: [...item.days].sort() }))
.sort((a, b) => {
const c = a.category.localeCompare(b.category);
return c !== 0 ? c : a.name.localeCompare(b.name, 'pl');
});
}
/** /**
* Jedna grupa na porę dnia: nagłówek pory raz, potem bloki przepisów ze składnikami. * Jedna grupa na porę dnia: nagłówek pory raz, potem bloki przepisów ze składnikami.
*/ */

View File

@@ -1,14 +1,19 @@
import { import {
INGREDIENTS, INGREDIENTS,
CATEGORY_LABELS, CATEGORY_LABELS,
getProductsForIngredient,
ingredientHasProducts,
} from '../data/catalog.js?v=8'; } from '../data/catalog.js?v=8';
import { loadPantry, getPantryTotal } from '../services/pantryShopping.js?v=2';
import { loadPlans } from '../services/planStore.js?v=2';
import { addDays, addMonths, sameDay, sameMonth, startOfDay, startOfMonth } from '../services/dateUtils.js';
import { aggregateRangeIngredientNeed, dayHasAnyMeal } from '../services/planIngredients.js?v=4';
import { import {
categoryLabel, bindCalendarDayClicks,
loadPantry, createCalendarTopbarHTML,
getPantryTotal, createCalendarWeekdayHeaderHTML,
} from '../services/pantryShopping.js?v=2'; formatCalendarMonthYear,
renderCalendarGrid,
syncCalendarTodayButton,
} from '../ui/mealCalendar.js';
import { createIngredientCardController, getIngredientCardHTML } from '../ui/ingredientCard.js?v=20260410-107'; import { createIngredientCardController, getIngredientCardHTML } from '../ui/ingredientCard.js?v=20260410-107';
/* ── helpers ── */ /* ── helpers ── */
@@ -30,21 +35,6 @@ function formatQty(n) {
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1).replace(/\.0$/, ''); return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1).replace(/\.0$/, '');
} }
function formatQtyWithUnit(qty, unit) {
return `${formatQty(qty)} ${unitLabel(unit)}`;
}
function productCountShortLabel(count) {
return `${count} prod.`;
}
function mediaHtml(image, icon, sizeClass = 'w-11 h-11', radiusClass = 'rounded-2xl') {
if (image) {
return `<img src="${esc(image)}" alt="" class="${sizeClass} ${radiusClass} object-cover shrink-0">`;
}
return `<div class="${sizeClass} ${radiusClass} flex items-center justify-center shrink-0" style="background:#2f2f2d;"><i class="fas ${icon} text-sm" style="color:#8f8b84;"></i></div>`;
}
const CATEGORY_ICONS = { const CATEGORY_ICONS = {
pieczywo: 'fa-bread-slice', pieczywo: 'fa-bread-slice',
nabial: 'fa-cheese', nabial: 'fa-cheese',
@@ -56,11 +46,77 @@ const CATEGORY_ICONS = {
inne: 'fa-jar', inne: 'fa-jar',
}; };
const DAY_NAMES_SHORT = ['nd.', 'pon.', 'wt.', 'śr.', 'czw.', 'pt.', 'sob.'];
const MONTHS_SHORT = ['sty', 'lut', 'mar', 'kwi', 'maj', 'cze', 'lip', 'sie', 'wrz', 'paź', 'lis', 'gru'];
const SEARCH_SHELL_SHADOW = '0 5px 10px rgba(0,0,0,0.16), 0 14px 22px rgba(0,0,0,0.24), 0 22px 34px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.04)'; const SEARCH_SHELL_SHADOW = '0 5px 10px rgba(0,0,0,0.16), 0 14px 22px rgba(0,0,0,0.24), 0 22px 34px rgba(0,0,0,0.18), inset 0 1px 0 rgba(255,255,255,0.04)';
const DEFAULT_HORIZON_DAYS = 7;
const PANTRY_CALENDAR_DAY_ATTR = 'data-pantry-calendar-day';
/* ── state ── */ /* ── state ── */
let ingredientCard = null; let ingredientCard = null;
let horizonEndDate = addDays(startOfDay(new Date()), DEFAULT_HORIZON_DAYS - 1);
let isSearchExpanded = false;
let isCalendarOpen = false;
let calendarMonthAnchor = startOfMonth(horizonEndDate);
let pantryGlobalListenersBound = false;
/* ── date formatting ── */
function getToday() {
return startOfDay(new Date());
}
function ensureValidHorizonDate() {
const today = getToday();
if (!(horizonEndDate instanceof Date) || Number.isNaN(horizonEndDate.getTime()) || horizonEndDate.getTime() < today.getTime()) {
horizonEndDate = today;
}
if (!(calendarMonthAnchor instanceof Date) || Number.isNaN(calendarMonthAnchor.getTime())) {
calendarMonthAnchor = startOfMonth(horizonEndDate);
}
}
function getHorizonDays() {
ensureValidHorizonDate();
const diffMs = startOfDay(horizonEndDate).getTime() - getToday().getTime();
return Math.max(1, Math.floor(diffMs / 86400000) + 1);
}
function formatEndDate(date) {
return `${DAY_NAMES_SHORT[date.getDay()]} ${date.getDate()} ${MONTHS_SHORT[date.getMonth()]}`;
}
function formatHorizonLabel(date) {
return sameDay(date, getToday()) ? 'Do dziś' : `Do ${formatEndDate(date)}`;
}
function formatRangeSummary(date) {
return sameDay(date, getToday()) ? 'Zakres: tylko dziś' : `Zakres: dziś - ${formatEndDate(date)}`;
}
function formatDayContext(dayStrings) {
const dayNames = dayStrings.map((ds) => {
const d = new Date(ds + 'T00:00:00');
return DAY_NAMES_SHORT[d.getDay()];
});
if (dayNames.length <= 3) return dayNames.join(', ');
return dayNames.slice(0, 3).join(', ') + ', \u2026';
}
/* ── media helpers ── */
function photoStripMedia(image, icon, accentBg) {
if (image) {
return `<div class="w-[4.5rem] shrink-0 relative self-stretch">
<img src="${esc(image)}" alt="" class="absolute inset-0 w-full h-full object-cover">
</div>`;
}
return `<div class="w-[4.5rem] shrink-0 flex items-center justify-center self-stretch" style="background:#333331;">
<i class="fas ${icon} text-[22px]" style="color:rgba(255,255,255,0.10);"></i>
</div>`;
}
/* ══════════════════════ HTML SHELL ══════════════════════ */ /* ══════════════════════ HTML SHELL ══════════════════════ */
@@ -68,17 +124,58 @@ export function getPantryHTML() {
return ` return `
<div id="pantry-view" class="hidden flex flex-col h-full absolute inset-0 overflow-hidden z-10" style="background:#2d2e2b !important;"> <div id="pantry-view" class="hidden flex flex-col h-full absolute inset-0 overflow-hidden z-10" style="background:#2d2e2b !important;">
<!-- ── floating search bar ── --> <!-- ── floating top bar ── -->
<div class="pointer-events-none absolute inset-x-0 top-0 z-[12] px-4 pt-4" style="background:transparent !important; border:none !important;"> <div class="pointer-events-none absolute inset-x-0 top-0 z-[12] px-4 pt-4" style="background:transparent !important; border:none !important;">
<div id="pantry-search-shell" class="pointer-events-auto relative z-[1] mx-auto flex items-center w-full overflow-hidden" style="width:min(calc(100% - 0.5rem), 22.4rem); background:#393937 !important; border:1px solid #41423f !important; border-radius:999px !important; box-shadow:${SEARCH_SHELL_SHADOW} !important;"> <div class="pointer-events-auto relative z-[1] mx-auto" style="width:min(calc(100% - 0.5rem), 22.4rem);">
<div id="pantry-topbar" class="relative h-11">
<div id="pantry-compact-controls" class="flex items-center gap-2 transition-all duration-200" style="opacity:1; transform:translateY(0) scale(1);">
<div id="pantry-horizon-wrap" class="relative flex-1 min-w-0">
<button type="button" id="pantry-horizon-toggle" class="w-full h-11 rounded-full flex items-center gap-2 px-3 transition-all" style="background:#393937 !important; border:1px solid #41423f !important; box-shadow:${SEARCH_SHELL_SHADOW} !important;">
<div class="w-8 h-8 rounded-full shrink-0 flex items-center justify-center" style="background:#2f2f2d;">
<i class="far fa-calendar text-[12px]" style="color:#9b978f;"></i>
</div>
<span id="pantry-horizon-label" class="flex-1 min-w-0 text-left text-[13px] font-normal truncate" style="color:#ddd6ca;"></span>
<i id="pantry-horizon-chevron" class="fas fa-chevron-down text-[10px] shrink-0 transition-transform duration-200" style="color:#9b978f;"></i>
</button>
<div id="pantry-calendar-popover" class="absolute left-0 right-0 top-full mt-2 rounded-[1.35rem] px-3 py-3 transition-all duration-200 pointer-events-none" style="background:#393937 !important; border:1px solid #41423f !important; box-shadow:${SEARCH_SHELL_SHADOW} !important; opacity:0; transform:translateY(-6px) scale(0.98);">
${createCalendarTopbarHTML({
titleId: 'pantry-cal-title',
prevId: 'pantry-cal-prev',
todayId: 'pantry-cal-today',
nextId: 'pantry-cal-next',
wrapperClass: 'pb-3 flex items-center gap-3',
titleClass: 'text-[13px] font-semibold text-[#ddd6ca] leading-none tracking-[-0.02em]',
})}
${createCalendarWeekdayHeaderHTML()}
<div id="pantry-calendar-grid" class="grid grid-cols-7 gap-1.5"></div>
<div class="mt-3 pt-3 border-t" style="border-color:#444442;">
<p id="pantry-cal-selection" class="min-w-0 text-[11px] leading-snug" style="color:#9b978f;"></p>
</div>
</div>
</div>
<button type="button" id="pantry-search-toggle" class="w-11 h-11 rounded-full shrink-0 flex items-center justify-center transition-all duration-200" style="background:#393937 !important; border:1px solid #41423f !important; box-shadow:${SEARCH_SHELL_SHADOW} !important; color:#ddd6ca;">
<i class="fas fa-search text-[13px]"></i>
</button>
</div>
<div id="pantry-search-shell" class="absolute inset-0 flex items-center gap-2 rounded-full px-3 transition-all duration-200 pointer-events-none" style="background:#393937 !important; border:1px solid #41423f !important; box-shadow:${SEARCH_SHELL_SHADOW} !important; opacity:0; transform:translateY(-2px) scale(0.98);">
<i class="fas fa-search text-[13px] shrink-0" style="color:#9b978f;"></i>
<input type="search" id="pantry-search" autocomplete="off" placeholder="Szukaj w spiżarni…" <input type="search" id="pantry-search" autocomplete="off" placeholder="Szukaj w spiżarni…"
class="w-full bg-transparent outline-none text-[15px] text-center py-[12px] px-8" style="background:transparent !important; border:none !important; box-shadow:none !important; color:#ddd6ca;"> class="flex-1 min-w-0 h-full bg-transparent outline-none text-[15px] leading-none py-0" style="background:transparent !important; border:none !important; box-shadow:none !important; color:#ddd6ca; margin:0;">
<button type="button" id="pantry-search-close" class="w-8 h-8 rounded-full shrink-0 flex items-center justify-center transition-colors" style="background:#2f2f2d; border:none; color:#9b978f;">
<i class="fas fa-xmark text-[13px]"></i>
</button>
</div>
</div>
</div> </div>
</div> </div>
<!-- ── scrollable content ── --> <!-- ── scrollable content ── -->
<div id="pantry-scroll" class="flex-1 overflow-y-auto no-scrollbar px-4 pt-[5.5rem] pb-24" style="background:#2d2e2b !important;"> <div id="pantry-scroll" class="flex-1 overflow-y-auto no-scrollbar px-4 pt-[5.25rem] pb-24" style="background:#2d2e2b !important;">
<div id="pantry-board" class="space-y-4"></div> <div id="pantry-board"></div>
</div> </div>
${getIngredientCardHTML({ ${getIngredientCardHTML({
@@ -88,66 +185,259 @@ export function getPantryHTML() {
</div>`; </div>`;
} }
/* ══════════════════════ BOARD RENDERING ══════════════════════ */ /* ══════════════════════ HORIZON SELECTOR ══════════════════════ */
function getFilteredIds(searchRaw) { function syncHorizonUI() {
const q = normalizeSearch(searchRaw); ensureValidHorizonDate();
return Object.keys(INGREDIENTS).filter((id) => {
const d = INGREDIENTS[id]; const compactControls = document.getElementById('pantry-compact-controls');
const searchShell = document.getElementById('pantry-search-shell');
const popover = document.getElementById('pantry-calendar-popover');
const horizonLabel = document.getElementById('pantry-horizon-label');
const chevron = document.getElementById('pantry-horizon-chevron');
const titleEl = document.getElementById('pantry-cal-title');
const selectionEl = document.getElementById('pantry-cal-selection');
const prevBtn = document.getElementById('pantry-cal-prev');
const todayBtn = document.getElementById('pantry-cal-today');
if (horizonLabel) horizonLabel.textContent = formatHorizonLabel(horizonEndDate);
if (titleEl) titleEl.textContent = formatCalendarMonthYear(calendarMonthAnchor);
if (selectionEl) selectionEl.textContent = formatRangeSummary(horizonEndDate);
const showCalendar = isCalendarOpen && !isSearchExpanded;
if (popover) {
popover.style.opacity = showCalendar ? '1' : '0';
popover.style.transform = showCalendar ? 'translateY(0) scale(1)' : 'translateY(-6px) scale(0.98)';
popover.style.pointerEvents = showCalendar ? 'auto' : 'none';
}
if (chevron) {
chevron.style.transform = showCalendar ? 'rotate(180deg)' : 'rotate(0deg)';
}
if (prevBtn) {
const isCurrentMonth = sameMonth(calendarMonthAnchor, getToday());
prevBtn.disabled = isCurrentMonth;
prevBtn.style.opacity = isCurrentMonth ? '0.45' : '1';
prevBtn.style.cursor = isCurrentMonth ? 'default' : 'pointer';
}
syncCalendarTodayButton(todayBtn, sameMonth(calendarMonthAnchor, getToday()));
if (compactControls) {
compactControls.style.opacity = isSearchExpanded ? '0' : '1';
compactControls.style.transform = isSearchExpanded ? 'translateY(-2px) scale(0.98)' : 'translateY(0) scale(1)';
compactControls.style.pointerEvents = isSearchExpanded ? 'none' : 'auto';
}
if (searchShell) {
searchShell.style.opacity = isSearchExpanded ? '1' : '0';
searchShell.style.transform = isSearchExpanded ? 'translateY(0) scale(1)' : 'translateY(-2px) scale(0.98)';
searchShell.style.pointerEvents = isSearchExpanded ? 'auto' : 'none';
}
renderCalendarPopover();
}
function renderCalendarPopover() {
const gridEl = document.getElementById('pantry-calendar-grid');
if (!gridEl) return;
ensureValidHorizonDate();
const today = getToday();
const plans = loadPlans();
renderCalendarGrid({
gridEl,
mode: 'month',
anchorDate: calendarMonthAnchor,
selectedDate: horizonEndDate,
resolveDayState: (day, meta) => {
const isPast = day.getTime() < today.getTime();
return {
disabled: isPast,
dimmed: isPast || !meta.inCurrentMonth,
showIndicator: dayHasAnyMeal(plans, day),
};
},
dayAttr: PANTRY_CALENDAR_DAY_ATTR,
});
}
function closeSearch() {
const input = document.getElementById('pantry-search');
const hadQuery = Boolean(input?.value);
if (input) {
input.value = '';
input.blur();
}
isSearchExpanded = false;
syncHorizonUI();
if (hadQuery) renderBoard();
}
function openSearch() {
isSearchExpanded = true;
isCalendarOpen = false;
syncHorizonUI();
window.requestAnimationFrame(() => {
document.getElementById('pantry-search')?.focus();
});
}
function closeCalendar() {
if (!isCalendarOpen) return;
isCalendarOpen = false;
syncHorizonUI();
}
function openCalendar() {
ensureValidHorizonDate();
calendarMonthAnchor = startOfMonth(horizonEndDate);
isCalendarOpen = true;
syncHorizonUI();
}
function selectHorizonDate(date) {
const next = startOfDay(date);
if (next.getTime() < getToday().getTime()) return;
horizonEndDate = next;
calendarMonthAnchor = startOfMonth(next);
isCalendarOpen = false;
syncHorizonUI();
renderBoard();
}
/* ══════════════════════ DATA CLASSIFICATION ══════════════════════ */
/**
* Classify all ingredients into 3 groups based on plan needs and pantry stock.
*/
function classifyIngredients(searchQuery) {
const plans = loadPlans();
const pantry = loadPantry();
const today = getToday();
const needs = aggregateRangeIngredientNeed(plans, today, getHorizonDays());
const q = normalizeSearch(searchQuery);
const matchesSearch = (name, category) => {
if (!q) return true; if (!q) return true;
return d.name.toLowerCase().includes(q) || (CATEGORY_LABELS[d.category] || '').toLowerCase().includes(q); return name.toLowerCase().includes(q) || (CATEGORY_LABELS[category] || '').toLowerCase().includes(q);
}).sort((a, b) => INGREDIENTS[a].name.localeCompare(INGREDIENTS[b].name, 'pl')); };
}
function getCategoryItemLabel(count) { const neededIds = new Set();
if (count === 1) return 'składnik'; const shortfalls = [];
const mod10 = count % 10; const sufficient = [];
const mod100 = count % 100;
if (mod10 >= 2 && mod10 <= 4 && !(mod100 >= 12 && mod100 <= 14)) return 'składniki';
return 'składników';
}
function ingredientRowHtml(id, pantry) { for (const need of needs) {
neededIds.add(need.ingredientId);
if (!matchesSearch(need.name, need.category)) continue;
const have = getPantryTotal(need.ingredientId, pantry);
const def = INGREDIENTS[need.ingredientId];
const icon = CATEGORY_ICONS[def?.category] || 'fa-jar';
const item = {
ingredientId: need.ingredientId,
name: need.name,
category: need.category,
needed: need.amount,
unit: need.unit,
pantryQty: have,
days: need.days,
image: def?.image || null,
icon,
};
if (have < need.amount) {
shortfalls.push({
...item,
shortfall: Math.round((need.amount - have) * 10) / 10,
fillPct: need.amount > 0 ? Math.min(100, Math.round((have / need.amount) * 100)) : 0,
});
} else {
sufficient.push({
...item,
fillPct: 100,
});
}
}
// "Poza planem": all ingredients NOT in any plan need
const notPlanned = Object.keys(INGREDIENTS)
.filter((id) => !neededIds.has(id))
.filter((id) => matchesSearch(INGREDIENTS[id].name, INGREDIENTS[id].category))
.map((id) => {
const def = INGREDIENTS[id]; const def = INGREDIENTS[id];
const icon = CATEGORY_ICONS[def.category] || 'fa-jar'; return {
const qty = getPantryTotal(id, pantry); ingredientId: id,
const hasProducts = ingredientHasProducts(id); name: def.name,
const products = hasProducts ? getProductsForIngredient(id) : []; qty: getPantryTotal(id, pantry),
const hasStock = qty > 0; unit: def.pantryUnit,
const accent = hasStock ? '#6ee7b7' : '#4b4a46'; };
const qtyColor = hasStock ? '#6ee7b7' : '#d7d2c8'; })
const badgeText = hasProducts ? productCountShortLabel(products.length) : unitLabel(def.pantryUnit); .sort((a, b) => a.name.localeCompare(b.name, 'pl'));
return `<button type="button" class="pv2-chip shrink-0 w-[9.5rem] rounded-2xl px-3 py-2.5 text-left transition-colors active:scale-[0.99]" style="background:#393937; border:1px solid #444442; box-shadow:inset 0 1px 0 rgba(255,255,255,0.02);" data-id="${esc(id)}"> return { shortfalls, sufficient, notPlanned };
<div class="w-full h-1 rounded-full mb-2" style="background:${accent}; opacity:${hasStock ? '1' : '0.45'};"></div> }
<div class="flex items-start gap-2">
${mediaHtml(def.image, icon, 'w-8 h-8', 'rounded-lg')} /* ══════════════════════ TILE RENDERING ══════════════════════ */
<div class="min-w-0 flex-1">
<span class="block text-[12px] font-semibold leading-[1.2] overflow-hidden" style="color:#ddd6ca; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical;"> function shortfallTileHtml(item) {
${esc(def.name)} const dayCtx = formatDayContext(item.days);
</span> return `
<button type="button" class="pv2-tile w-full text-left rounded-2xl flex items-center gap-3 px-3 py-3 transition-all active:scale-[0.99] mb-2" style="background:#393937; border:none; box-shadow:0 2px 8px rgba(0,0,0,0.28);" data-id="${esc(item.ingredientId)}">
<div class="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style="background:#2f2f2d;">
<i class="fas ${item.icon} text-[17px]" style="color:#914945;"></i>
</div> </div>
<div class="flex-1 min-w-0">
<p class="text-[13px] font-normal leading-tight truncate mb-1.5" style="color:#ddd6ca;">${esc(item.name)}</p>
<div class="flex items-center gap-2">
<div class="flex-1 h-2 rounded-full overflow-hidden" style="background:#2a2a28;">
<div class="h-full rounded-full" style="width:${item.fillPct}%; background:#914945;"></div>
</div> </div>
<div class="mt-4"> <span class="text-[11px] font-semibold tabular-nums shrink-0" style="color:#ddd6ca;">${esc(formatQty(item.pantryQty))} <span class="font-medium text-[10px]" style="color:#9b978f;">/ ${esc(formatQty(item.needed))} ${esc(unitLabel(item.unit))}</span></span>
<div class="flex items-end justify-between gap-2">
<span class="text-[14px] font-bold tabular-nums leading-none block" style="color:${qtyColor};">${esc(formatQtyWithUnit(qty, def.pantryUnit))}</span>
<span class="inline-flex items-center rounded-full px-1.5 py-0.5 text-[9px] font-semibold shrink-0" style="background:#2f2f2d; color:#9b978f;">${esc(badgeText)}</span>
</div> </div>
</div> </div>
</button>`; </button>`;
} }
function groupByCategory(ids) { function sufficientTileHtml(item) {
/** @type {Map<string, string[]>} */ const dayCtx = formatDayContext(item.days);
const groups = new Map(); return `
for (const id of ids) { <button type="button" class="pv2-tile w-full text-left rounded-2xl flex items-center gap-3 px-3 py-3 transition-all active:scale-[0.99] mb-2" style="background:#393937; border:none; box-shadow:0 2px 8px rgba(0,0,0,0.28);" data-id="${esc(item.ingredientId)}">
const cat = INGREDIENTS[id].category; <div class="w-10 h-10 rounded-xl flex items-center justify-center shrink-0" style="background:#2f2f2d;">
if (!groups.has(cat)) groups.set(cat, []); <i class="fas ${item.icon} text-[17px]" style="color:#6ee7b7;"></i>
groups.get(cat).push(id); </div>
} <div class="flex-1 min-w-0">
return [...groups.keys()] <p class="text-[13px] font-normal leading-tight truncate mb-1.5" style="color:#ddd6ca;">${esc(item.name)}</p>
.sort((a, b) => categoryLabel(a).localeCompare(categoryLabel(b))) <div class="flex items-center gap-2">
.map((cat) => ({ cat, ids: groups.get(cat) })); <div class="flex-1 h-2 rounded-full overflow-hidden" style="background:#2a2a28;">
<div class="h-full rounded-full" style="width:100%; background:#6ee7b7;"></div>
</div>
<span class="text-[11px] font-semibold tabular-nums shrink-0" style="color:#6ee7b7;">${esc(formatQty(item.pantryQty))} <span class="font-medium text-[10px]" style="color:#9b978f;">/ ${esc(formatQty(item.needed))} ${esc(unitLabel(item.unit))}</span></span>
</div>
</div>
</button>`;
}
function notPlannedChipHtml(item) {
const hasStock = item.qty > 0;
return `
<button type="button" class="pv2-tile rounded-xl px-3 py-2 flex items-center gap-2 transition-all active:scale-[0.98] overflow-hidden" style="background:#333331; border:none; box-shadow:0 1px 4px rgba(0,0,0,0.22); max-width:100%;" data-id="${esc(item.ingredientId)}">
<span class="text-[11px] font-normal truncate min-w-0" style="color:${hasStock ? '#b7ada1' : '#9b978f'};">${esc(item.name)}</span>
<span class="text-[11px] font-semibold tabular-nums shrink-0" style="color:${hasStock ? '#9b978f' : '#6d6c67'};">${esc(formatQty(item.qty))} ${esc(unitLabel(item.unit))}</span>
</button>`;
}
/* ══════════════════════ SECTION RENDERING ══════════════════════ */
function sectionHeaderHtml(icon, iconBg, iconColor, title, titleColor, count) {
return `
<div class="flex items-center gap-2 mb-2.5 px-0.5">
<div class="w-6 h-6 rounded-lg flex items-center justify-center" style="background:${iconBg};">
<i class="fas ${icon} text-[10px]" style="color:${iconColor};"></i>
</div>
<span class="text-[10px] font-bold uppercase tracking-wider" style="color:${titleColor};">${esc(title)}</span>
<span class="text-[10px]" style="color:#6d6c67;">${count}</span>
</div>`;
} }
function renderBoard() { function renderBoard() {
@@ -155,34 +445,57 @@ function renderBoard() {
if (!root) return; if (!root) return;
const q = document.getElementById('pantry-search')?.value || ''; const q = document.getElementById('pantry-search')?.value || '';
const pantry = loadPantry(); const { shortfalls, sufficient, notPlanned } = classifyIngredients(q);
const visible = getFilteredIds(q);
if (visible.length === 0) { const totalVisible = shortfalls.length + sufficient.length + notPlanned.length;
if (totalVisible === 0 && q) {
root.innerHTML = `<p class="text-sm text-center py-10" style="color:#9b978f;">Brak wyników — zmień wyszukiwanie.</p>`; root.innerHTML = `<p class="text-sm text-center py-10" style="color:#9b978f;">Brak wyników — zmień wyszukiwanie.</p>`;
return; return;
} }
const groups = groupByCategory(visible); let html = '';
root.innerHTML = groups.map(({ cat, ids }) => {
const icon = CATEGORY_ICONS[cat] || 'fa-jar';
return `
<section class="mb-4 last:mb-0">
<div class="mb-2 px-0.5">
<p class="text-[10px] font-bold uppercase tracking-wider" style="color:#9b978f;">
<i class="fas ${icon} text-[10px] mr-1"></i>${esc(categoryLabel(cat))}
</p>
<p class="text-[10px] mt-1" style="color:#6d6c67;">${ids.length} ${getCategoryItemLabel(ids.length)}</p>
</div>
<div class="overflow-x-auto no-scrollbar -mx-4 px-4">
<div class="flex gap-2.5 pb-1">
${ids.map((rowId) => ingredientRowHtml(rowId, pantry)).join('')}
</div>
</div>
</section>`;
}).join('');
root.querySelectorAll('.pv2-chip').forEach((btn) => { // Section 1: Potrzebne (shortfalls)
if (shortfalls.length > 0) {
html += `<section class="mb-5">`;
html += sectionHeaderHtml('fa-exclamation', '#914945', '#f2efe8', 'Potrzebne', '#7B756D', shortfalls.length);
html += shortfalls.map(shortfallTileHtml).join('');
html += `</section>`;
}
// Section 2: W spiżarni (sufficient)
if (sufficient.length > 0) {
html += `<section class="mb-5">`;
html += sectionHeaderHtml('fa-check', '#1a2e22', '#6ee7b7', 'W spiżarni', '#7B756D', sufficient.length);
html += sufficient.map(sufficientTileHtml).join('');
html += `</section>`;
}
// Section 3: Poza planem
if (notPlanned.length > 0) {
html += `<section class="mb-5">`;
html += sectionHeaderHtml('fa-minus', '#2a2a28', '#6d6c67', 'Poza planem', '#7B756D', notPlanned.length);
html += `<div class="flex flex-wrap gap-2">`;
html += notPlanned.map(notPlannedChipHtml).join('');
html += `</div></section>`;
}
// Empty state: no plans at all
if (shortfalls.length === 0 && sufficient.length === 0 && !q) {
html = `
<div class="flex flex-col items-center justify-center py-10 text-center mb-6">
<div class="w-12 h-12 rounded-2xl flex items-center justify-center mb-3" style="background:#393937;">
<i class="fas fa-calendar-xmark text-lg" style="color:#6d6c67;"></i>
</div>
<p class="text-[13px] font-semibold mb-1" style="color:#ddd6ca;">Brak zaplanowanych posiłków</p>
<p class="text-[11px] max-w-[16rem]" style="color:#9b978f;">Zaplanuj posiłki, a spiżarnia pokaże czego potrzebujesz i co masz na stanie.</p>
</div>` + html;
}
root.innerHTML = html;
// Bind tile clicks
root.querySelectorAll('.pv2-tile').forEach((btn) => {
btn.addEventListener('click', () => openIngredientCard(btn.dataset.id, null)); btn.addEventListener('click', () => openIngredientCard(btn.dataset.id, null));
}); });
} }
@@ -201,6 +514,7 @@ function openIngredientCard(ingredientId, productId) {
/* ══════════════════════ PUBLIC API ══════════════════════ */ /* ══════════════════════ PUBLIC API ══════════════════════ */
export function refreshPantry() { export function refreshPantry() {
syncHorizonUI();
renderBoard(); renderBoard();
ingredientCard?.refresh(); ingredientCard?.refresh();
} }
@@ -210,9 +524,54 @@ export function setupPantry() {
ingredientCard = createIngredientCardController({ idBase: 'pv2-card', defaultSourceNote: 'Ze spiżarni' }); ingredientCard = createIngredientCardController({ idBase: 'pv2-card', defaultSourceNote: 'Ze spiżarni' });
ingredientCard.bind(); ingredientCard.bind();
} }
syncHorizonUI();
renderBoard(); renderBoard();
// Search
document.getElementById('pantry-search')?.addEventListener('input', () => renderBoard()); document.getElementById('pantry-search')?.addEventListener('input', () => renderBoard());
document.getElementById('pantry-search')?.addEventListener('keydown', (event) => {
if (event.key === 'Escape') closeSearch();
});
document.getElementById('pantry-search-toggle')?.addEventListener('click', () => openSearch());
document.getElementById('pantry-search-close')?.addEventListener('click', () => closeSearch());
// Horizon pill + calendar
document.getElementById('pantry-horizon-toggle')?.addEventListener('click', () => {
if (isCalendarOpen) {
closeCalendar();
return;
}
openCalendar();
});
document.getElementById('pantry-cal-prev')?.addEventListener('click', () => {
const prevMonth = addMonths(calendarMonthAnchor, -1);
if (prevMonth.getTime() < startOfMonth(getToday()).getTime()) return;
calendarMonthAnchor = prevMonth;
syncHorizonUI();
});
document.getElementById('pantry-cal-next')?.addEventListener('click', () => {
calendarMonthAnchor = addMonths(calendarMonthAnchor, 1);
syncHorizonUI();
});
document.getElementById('pantry-cal-today')?.addEventListener('click', () => {
calendarMonthAnchor = startOfMonth(getToday());
syncHorizonUI();
});
bindCalendarDayClicks(document.getElementById('pantry-calendar-grid'), (date) => {
selectHorizonDate(date);
}, PANTRY_CALENDAR_DAY_ATTR);
if (!pantryGlobalListenersBound) {
pantryGlobalListenersBound = true;
document.addEventListener('click', (event) => {
const target = event.target;
if (!(target instanceof Element)) return;
if (isCalendarOpen && !target.closest('#pantry-horizon-wrap')) {
closeCalendar();
}
});
}
window.refreshPantry = refreshPantry; window.refreshPantry = refreshPantry;
} }