800 lines
35 KiB
JavaScript
800 lines
35 KiB
JavaScript
import {
|
|
INGREDIENTS,
|
|
CATEGORY_LABELS,
|
|
} from '../data/catalog.js?v=9';
|
|
import { loadPantry, getPantryTotal } from '../services/pantryShopping.js?v=2';
|
|
import { loadPlans, dateKey } from '../services/planStore.js?v=2';
|
|
import { addDays, sameDay, startOfDay, startOfMonth } from '../services/dateUtils.js';
|
|
import { aggregateRangeIngredientNeed, dayHasAnyMeal } from '../services/planIngredients.js?v=4';
|
|
import {
|
|
createSwipePopoverCalendarHTML,
|
|
initSwipePopoverCalendar,
|
|
} from '../ui/swipePopoverCalendar.js';
|
|
import {
|
|
createCalendarPopoverHTML,
|
|
stabilizeSwipeCalendarLayout,
|
|
syncCalendarPopoverVisibility,
|
|
} from '../ui/calendarPopover.js';
|
|
import { createIngredientCardController, getIngredientCardHTML } from '../ui/ingredientCard.js?v=20260417-116';
|
|
import { ensureFilterPopoverStyles, filterChipStyle } from '../ui/filterPopover.js?v=1';
|
|
|
|
/* ── helpers ── */
|
|
|
|
function esc(s) {
|
|
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
}
|
|
|
|
function unitLabel(u) {
|
|
return u === 'szt' ? 'szt.' : u;
|
|
}
|
|
|
|
function normalizeSearch(q) {
|
|
return String(q).trim().toLowerCase();
|
|
}
|
|
|
|
function formatQty(n) {
|
|
const rounded = Math.round((Number(n) || 0) * 10) / 10;
|
|
return Number.isInteger(rounded) ? String(rounded) : rounded.toFixed(1).replace(/\.0$/, '');
|
|
}
|
|
|
|
function toggleStringFilter(list, value) {
|
|
return list.includes(value)
|
|
? list.filter((item) => item !== value)
|
|
: [...list, value];
|
|
}
|
|
|
|
function hasActivePantryFilters() {
|
|
return pantryFilters.categories.length > 0 || pantryFilters.sections.length > 0;
|
|
}
|
|
|
|
function getActivePantryFilterCount() {
|
|
return pantryFilters.categories.length + pantryFilters.sections.length;
|
|
}
|
|
|
|
const CATEGORY_ICONS = {
|
|
pieczywo: 'fa-bread-slice',
|
|
nabial: 'fa-cheese',
|
|
mieso_ryby: 'fa-drumstick-bite',
|
|
warzywa: 'fa-carrot',
|
|
owoce: 'fa-apple-whole',
|
|
suche: 'fa-wheat-awn',
|
|
przyprawy: 'fa-leaf',
|
|
inne: 'fa-jar',
|
|
};
|
|
const CATEGORY_ORDER = ['pieczywo', 'nabial', 'mieso_ryby', 'warzywa', 'owoce', 'suche', 'przyprawy', 'inne'];
|
|
const PANTRY_SECTION_FILTERS = [
|
|
{ id: 'shortfalls', label: 'Potrzebne' },
|
|
{ id: 'sufficient', label: 'W spiżarni' },
|
|
{ id: 'notPlanned', label: 'Poza planem' },
|
|
];
|
|
|
|
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 DEFAULT_HORIZON_DAYS = 7;
|
|
const SHORTFALL_ACCENT = 'rgb(var(--danger-rgb))';
|
|
const PANTRY_CALENDAR_THEME = {
|
|
bg: 'rgba(255,255,255,0.08)',
|
|
border: 'rgb(var(--card-raised-rgb))',
|
|
text: 'rgb(var(--text-body-soft-rgb))',
|
|
dimText: 'rgb(var(--text-faint-rgb))',
|
|
dimOpacity: 0.58,
|
|
dimmedBg: 'transparent',
|
|
dimmedBorder: 'transparent',
|
|
dot: 'rgb(var(--text-faint-rgb))',
|
|
selectedBorder: 'rgba(var(--text-emphasis-rgb),0.34)',
|
|
selectedText: 'rgb(var(--text-emphasis-rgb))',
|
|
selectedDot: 'rgb(var(--text-emphasis-rgb))',
|
|
selectedShadow: '0 0 0 1px rgba(var(--text-emphasis-rgb),0.10)',
|
|
};
|
|
|
|
/* ── state ── */
|
|
|
|
let ingredientCard = null;
|
|
let horizonEndDate = addDays(startOfDay(new Date()), DEFAULT_HORIZON_DAYS - 1);
|
|
let isCalendarOpen = false;
|
|
let isFilterOpen = false;
|
|
let calendarMonthAnchor = startOfMonth(horizonEndDate);
|
|
let pantryGlobalListenersBound = false;
|
|
let pantryCalendar = null;
|
|
let pantrySearchQuery = '';
|
|
let pantrySearchOpen = false;
|
|
let pantryFilters = {
|
|
categories: [],
|
|
sections: [],
|
|
};
|
|
|
|
/* ── 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 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:rgb(var(--card-soft-rgb));">
|
|
<i class="fas ${icon} text-[22px]" style="color:var(--icon-watermark);"></i>
|
|
</div>`;
|
|
}
|
|
|
|
/* ══════════════════════ HTML SHELL ══════════════════════ */
|
|
|
|
export function getPantryHTML() {
|
|
return `
|
|
<div id="pantry-view" class="hidden flex flex-col h-full absolute inset-0 overflow-hidden z-10" style="background:rgb(var(--app-bg-rgb)) !important;">
|
|
<style id="pantry-view-styles">
|
|
.pv2-tile {
|
|
background: rgba(var(--surface-rgb), 0.62) !important;
|
|
border: 1px solid rgba(255, 255, 255, 0.26) !important;
|
|
box-shadow:
|
|
inset 0 1px 0 rgba(255, 255, 255, 0.48),
|
|
inset 0 -1px 0 rgba(var(--overlay-rgb), 0.04),
|
|
0 1px 2px rgba(var(--overlay-rgb), 0.06),
|
|
0 6px 14px rgba(var(--overlay-rgb), 0.1) !important;
|
|
backdrop-filter: blur(18px) saturate(160%);
|
|
-webkit-backdrop-filter: blur(18px) saturate(160%);
|
|
}
|
|
|
|
.dark .pv2-tile {
|
|
background: rgba(255, 255, 255, 0.06) !important;
|
|
border-color: rgba(255, 255, 255, 0.1) !important;
|
|
box-shadow:
|
|
inset 0 1px 0 rgba(255, 255, 255, 0.18),
|
|
inset 0 -1px 0 rgba(0, 0, 0, 0.22),
|
|
0 2px 4px rgba(0, 0, 0, 0.24),
|
|
0 8px 18px rgba(0, 0, 0, 0.3) !important;
|
|
}
|
|
|
|
.pv2-track {
|
|
background: rgba(var(--overlay-rgb), 0.12);
|
|
}
|
|
|
|
.dark .pv2-track {
|
|
background: rgba(255, 255, 255, 0.1);
|
|
}
|
|
</style>
|
|
|
|
<!-- ── floating horizon pill — mirrors bottom search-field structure ── -->
|
|
<div id="pantry-top-controls" class="pointer-events-none absolute inset-x-0 z-[24]" style="top:1rem; height:var(--recipe-control-size, 3.05rem); background:transparent !important; border:none !important; box-shadow:none !important; backdrop-filter:none !important; -webkit-backdrop-filter:none !important;">
|
|
<div id="pantry-horizon-wrap" class="pointer-events-auto absolute top-0" style="left:var(--catalog-menu-left, 1rem); width:var(--recipe-dock-width, calc(100% - 2rem)); height:var(--recipe-control-size, 3.05rem);">
|
|
<button type="button" id="pantry-horizon-compact" class="recipe-glass-btn w-full h-full rounded-full flex items-center gap-1.5 px-3">
|
|
<span id="pantry-horizon-compact-label" class="min-w-0 flex-1 text-left text-[13px] font-normal truncate" style="color:rgb(var(--text-body-rgb));"></span>
|
|
<i id="pantry-horizon-chevron" class="fas fa-chevron-down text-[10px] shrink-0 transition-transform duration-200" style="color:rgb(var(--text-dim-rgb));"></i>
|
|
</button>
|
|
${createCalendarPopoverHTML({
|
|
id: 'pantry-calendar-popover',
|
|
calendarHTML: createSwipePopoverCalendarHTML({ idPrefix: 'pantry-cal' }),
|
|
})}
|
|
</div>
|
|
</div>
|
|
|
|
<!-- ── scrollable content ── -->
|
|
<div id="pantry-scroll" class="flex-1 overflow-y-auto no-scrollbar px-4 pb-32" style="background:rgb(var(--app-bg-rgb)) !important; padding-top:calc(1rem + var(--recipe-control-size, 3.05rem) + 1.15rem); scroll-padding-top:calc(1rem + var(--recipe-control-size, 3.05rem) + 1.15rem);">
|
|
<div id="pantry-board"></div>
|
|
</div>
|
|
|
|
<!-- ── floating bottom controls (search + filter) ── -->
|
|
<div id="pantry-filter-popover" class="filter-liquid-surface filter-liquid-panel absolute z-[25] pointer-events-none rounded-[1.35rem] px-3 pt-3 pb-3 transition-all duration-200" style="left:50%; width:min(calc(100% - 1.5rem), 22rem); transform:translateX(-50%) translateY(0.5rem) scale(0.98); transform-origin:bottom center; bottom:calc(1.58rem + env(safe-area-inset-bottom) + var(--recipe-controls-lift, 0.335rem) + var(--recipe-bottom-control-size, 3.9rem) + 0.75rem); opacity:0;">
|
|
<div class="flex items-center justify-between gap-3 px-0.5 pb-2">
|
|
<p class="text-[11px] font-semibold leading-none" style="color:rgb(var(--text-emphasis-rgb));">Filtry</p>
|
|
<button type="button" id="pantry-filter-clear" class="h-8 px-2 rounded-full text-[11px] font-semibold transition-colors" style="background:transparent; border:none; color:rgb(var(--text-muted-rgb));">
|
|
Wyczyść
|
|
</button>
|
|
</div>
|
|
<div id="pantry-filter-panel-body" class="space-y-4"></div>
|
|
</div>
|
|
|
|
<div id="pantry-bottom-controls" class="pointer-events-none absolute inset-x-0 z-[34] h-[3.9rem]" style="bottom:calc(1.58rem + env(safe-area-inset-bottom) + var(--recipe-controls-lift, 0.335rem)); height:var(--recipe-bottom-control-size, 3.9rem); background:transparent !important; border:none !important; box-shadow:none !important; backdrop-filter:none !important; -webkit-backdrop-filter:none !important;">
|
|
<div id="pantry-search-wrap" class="pointer-events-auto absolute bottom-0">
|
|
<button type="button" id="pantry-search-btn" class="recipe-glass-btn recipe-bottom-action relative flex items-center justify-center transition-all duration-200" aria-label="Szukaj w spiżarni">
|
|
<i class="fas fa-search" aria-hidden="true"></i>
|
|
<span id="pantry-search-active-dot" class="hidden absolute -top-1 -right-1 w-[0.65rem] h-[0.65rem] rounded-full" style="background:rgb(var(--text-emphasis-rgb)); border:1px solid rgba(255,255,255,0.42); box-shadow:0 2px 6px rgba(var(--overlay-rgb),0.22);"></span>
|
|
</button>
|
|
</div>
|
|
<div id="pantry-search-shell" class="recipe-glass-btn recipe-search-field pointer-events-none absolute bottom-0 flex items-center gap-2 px-3" style="opacity:0; transform:translateY(0.45rem) scale(0.98); transition:opacity 0.2s ease, transform 0.2s ease;">
|
|
<i class="fas fa-search shrink-0" aria-hidden="true"></i>
|
|
<input type="search" id="pantry-search-input" autocomplete="off" placeholder="Szukaj w spiżarni…"
|
|
class="flex-1 min-w-0 h-full bg-transparent outline-none text-[15px] leading-none py-0" style="appearance:none; -webkit-appearance:none; background:transparent !important; background-color:transparent !important; background-image:none !important; border:none !important; border-radius:0 !important; box-shadow:none !important; backdrop-filter:none !important; -webkit-backdrop-filter:none !important; color:rgb(var(--text-body-rgb)); margin:0; padding:0 !important;">
|
|
</div>
|
|
|
|
<div id="pantry-filter-bottom-wrap" class="pointer-events-auto absolute bottom-0 right-4">
|
|
<button type="button" id="pantry-filter-bottom-btn" class="recipe-glass-btn recipe-bottom-action relative flex items-center justify-center transition-all duration-200" aria-label="Otwórz filtry">
|
|
<i id="pantry-right-btn-icon" class="fas fa-sliders-h" aria-hidden="true"></i>
|
|
<span id="pantry-filter-count" class="hidden absolute -top-1 -right-1 min-w-[1.1rem] h-[1.1rem] px-1 rounded-full text-[9px] font-bold leading-none items-center justify-center" style="background:rgba(var(--text-emphasis-rgb),0.86); background-image:none !important; border:1px solid rgba(255,255,255,0.42); color:rgb(var(--app-bg-rgb)); box-shadow:0 2px 6px rgba(var(--overlay-rgb),0.22);"></span>
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
${getIngredientCardHTML({ idBase: 'pv2-card' })}`;
|
|
}
|
|
|
|
/* ══════════════════════ HORIZON SELECTOR ══════════════════════ */
|
|
|
|
function syncHorizonUI() {
|
|
ensureValidHorizonDate();
|
|
|
|
const popover = document.getElementById('pantry-calendar-popover');
|
|
const filterPopover = document.getElementById('pantry-filter-popover');
|
|
const filterCount = document.getElementById('pantry-filter-count');
|
|
const searchWrap = document.getElementById('pantry-search-wrap');
|
|
const searchShell = document.getElementById('pantry-search-shell');
|
|
const rightBtn = document.getElementById('pantry-filter-bottom-btn');
|
|
const rightIcon = document.getElementById('pantry-right-btn-icon');
|
|
const searchDot = document.getElementById('pantry-search-active-dot');
|
|
const compactLabel = document.getElementById('pantry-horizon-compact-label');
|
|
const compactPill = document.getElementById('pantry-horizon-compact');
|
|
const chevron = document.getElementById('pantry-horizon-chevron');
|
|
|
|
if (compactLabel) compactLabel.textContent = formatHorizonLabel(horizonEndDate);
|
|
|
|
const activeFilterCount = getActivePantryFilterCount();
|
|
|
|
syncCalendarPopoverVisibility({
|
|
popup: popover,
|
|
isOpen: isCalendarOpen,
|
|
chevron,
|
|
trigger: compactPill,
|
|
openTriggerStyle: {},
|
|
closedTriggerStyle: {},
|
|
triggerImportant: true,
|
|
});
|
|
|
|
if (filterPopover) {
|
|
filterPopover.style.opacity = isFilterOpen ? '1' : '0';
|
|
filterPopover.style.transform = isFilterOpen
|
|
? 'translateX(-50%) translateY(0) scale(1)'
|
|
: 'translateX(-50%) translateY(0.5rem) scale(0.98)';
|
|
filterPopover.style.pointerEvents = isFilterOpen ? 'auto' : 'none';
|
|
}
|
|
if (filterCount) {
|
|
filterCount.textContent = String(activeFilterCount);
|
|
filterCount.classList.toggle('hidden', pantrySearchOpen || activeFilterCount === 0);
|
|
filterCount.classList.toggle('flex', !pantrySearchOpen && activeFilterCount > 0);
|
|
}
|
|
if (searchWrap) searchWrap.classList.toggle('hidden', pantrySearchOpen);
|
|
if (searchShell) {
|
|
searchShell.style.opacity = pantrySearchOpen ? '1' : '0';
|
|
searchShell.style.pointerEvents = pantrySearchOpen ? 'auto' : 'none';
|
|
searchShell.style.transform = pantrySearchOpen ? 'translateY(0) scale(1)' : 'translateY(0.45rem) scale(0.98)';
|
|
}
|
|
if (rightIcon) rightIcon.className = `fas ${pantrySearchOpen ? 'fa-xmark' : 'fa-sliders-h'}`;
|
|
if (rightBtn) rightBtn.setAttribute('aria-label', pantrySearchOpen ? 'Zamknij wyszukiwanie' : 'Otwórz filtry');
|
|
if (searchDot) searchDot.classList.toggle('hidden', !pantrySearchQuery);
|
|
|
|
renderCalendarPopover();
|
|
renderFilterPopover();
|
|
}
|
|
|
|
function renderCalendarPopover() {
|
|
pantryCalendar?.render();
|
|
}
|
|
|
|
function bindPantryCalendarInteractions() {
|
|
pantryCalendar = initSwipePopoverCalendar({
|
|
idPrefix: 'pantry-cal',
|
|
selectionMode: 'single',
|
|
panelHandlePx: 10,
|
|
panelHandleMin: 8,
|
|
panelHandleMax: 12,
|
|
getMonthAnchor: () => calendarMonthAnchor,
|
|
setMonthAnchor: (nextMonth) => {
|
|
const nextAnchor = startOfMonth(nextMonth);
|
|
const minAnchor = startOfMonth(getToday());
|
|
if (nextAnchor.getTime() < minAnchor.getTime()) return;
|
|
calendarMonthAnchor = nextAnchor;
|
|
},
|
|
canNavigateToMonth: (nextMonth) => {
|
|
const nextAnchor = startOfMonth(nextMonth);
|
|
const minAnchor = startOfMonth(getToday());
|
|
return nextAnchor.getTime() >= minAnchor.getTime();
|
|
},
|
|
getSelectionKeys: () => dateKey(horizonEndDate),
|
|
onSelectionCommit: (selectedKey) => {
|
|
selectHorizonDate(new Date(`${selectedKey}T00:00:00`));
|
|
},
|
|
resolveDayState: (day, { inCurrentMonth }) => {
|
|
const isPast = day.getTime() < getToday().getTime();
|
|
return {
|
|
disabled: isPast,
|
|
dimmed: isPast || !inCurrentMonth,
|
|
showDot: dayHasAnyMeal(loadPlans(), day),
|
|
};
|
|
},
|
|
theme: PANTRY_CALENDAR_THEME,
|
|
});
|
|
pantryCalendar.render();
|
|
}
|
|
|
|
function filterChipHtml(kind, value, label, active) {
|
|
return `<button
|
|
type="button"
|
|
class="px-3 py-2 rounded-full text-[11px] font-semibold transition-colors"
|
|
style="${filterChipStyle(active)}"
|
|
data-pantry-filter-kind="${esc(kind)}"
|
|
data-pantry-filter-value="${esc(value)}"
|
|
>${esc(label)}</button>`;
|
|
}
|
|
|
|
function renderFilterPopover() {
|
|
const body = document.getElementById('pantry-filter-panel-body');
|
|
if (!body) return;
|
|
|
|
const categoryChips = CATEGORY_ORDER
|
|
.map((category) => filterChipHtml(
|
|
'category',
|
|
category,
|
|
CATEGORY_LABELS[category] || category,
|
|
pantryFilters.categories.includes(category),
|
|
))
|
|
.join('');
|
|
|
|
const sectionChips = PANTRY_SECTION_FILTERS
|
|
.map((item) => filterChipHtml(
|
|
'section',
|
|
item.id,
|
|
item.label,
|
|
pantryFilters.sections.includes(item.id),
|
|
))
|
|
.join('');
|
|
|
|
body.innerHTML = `
|
|
<section>
|
|
<p class="text-[10px] font-bold uppercase tracking-wider mb-3 px-0.5" style="color:rgb(var(--text-muted-rgb));">Kategorie</p>
|
|
<div class="flex flex-wrap gap-2">${categoryChips}</div>
|
|
</section>
|
|
<section>
|
|
<p class="text-[10px] font-bold uppercase tracking-wider mb-3 px-0.5" style="color:rgb(var(--text-muted-rgb));">Sekcje</p>
|
|
<div class="flex flex-wrap gap-2">${sectionChips}</div>
|
|
</section>
|
|
`;
|
|
}
|
|
|
|
function clearSearchInput() {
|
|
const hadQuery = Boolean(pantrySearchQuery);
|
|
pantrySearchQuery = '';
|
|
if (hadQuery) renderBoard();
|
|
}
|
|
|
|
function setPantrySearchOpen(open, { clearQuery = false, focusInput = false } = {}) {
|
|
const hadQuery = Boolean(pantrySearchQuery);
|
|
pantrySearchOpen = open;
|
|
document.documentElement.classList.toggle('is-inline-search-open', pantrySearchOpen);
|
|
if (clearQuery) pantrySearchQuery = '';
|
|
const input = document.getElementById('pantry-search-input');
|
|
if (input) {
|
|
if (open) {
|
|
input.value = pantrySearchQuery;
|
|
if (focusInput) {
|
|
input.focus();
|
|
input.setSelectionRange(input.value.length, input.value.length);
|
|
}
|
|
} else {
|
|
input.blur();
|
|
}
|
|
}
|
|
syncHorizonUI();
|
|
if (clearQuery && hadQuery) renderBoard();
|
|
}
|
|
|
|
function closeCalendar() {
|
|
if (!isCalendarOpen) return;
|
|
isCalendarOpen = false;
|
|
pantryCalendar?.resetTrackPosition();
|
|
syncHorizonUI();
|
|
}
|
|
|
|
function openCalendar() {
|
|
ensureValidHorizonDate();
|
|
calendarMonthAnchor = startOfMonth(horizonEndDate);
|
|
isFilterOpen = false;
|
|
isCalendarOpen = true;
|
|
syncHorizonUI();
|
|
stabilizeSwipeCalendarLayout({
|
|
calendar: pantryCalendar,
|
|
viewport: 'pantry-cal-viewport',
|
|
});
|
|
}
|
|
|
|
function closeFilter() {
|
|
if (!isFilterOpen) return;
|
|
isFilterOpen = false;
|
|
syncHorizonUI();
|
|
}
|
|
|
|
function toggleFilterPanel() {
|
|
if (pantrySearchOpen) return;
|
|
isCalendarOpen = false;
|
|
isFilterOpen = !isFilterOpen;
|
|
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;
|
|
return name.toLowerCase().includes(q) || (CATEGORY_LABELS[category] || '').toLowerCase().includes(q);
|
|
};
|
|
const matchesCategory = (category) => pantryFilters.categories.length === 0 || pantryFilters.categories.includes(category);
|
|
const matchesSection = (section) => pantryFilters.sections.length === 0 || pantryFilters.sections.includes(section);
|
|
|
|
const neededIds = new Set();
|
|
const shortfalls = [];
|
|
const sufficient = [];
|
|
|
|
for (const need of needs) {
|
|
neededIds.add(need.ingredientId);
|
|
if (!matchesSearch(need.name, need.category) || !matchesCategory(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) {
|
|
if (!matchesSection('shortfalls')) continue;
|
|
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 {
|
|
if (!matchesSection('sufficient')) continue;
|
|
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(() => matchesSection('notPlanned'))
|
|
.filter((id) => matchesSearch(INGREDIENTS[id].name, INGREDIENTS[id].category))
|
|
.filter((id) => matchesCategory(INGREDIENTS[id].category))
|
|
.map((id) => {
|
|
const def = INGREDIENTS[id];
|
|
return {
|
|
ingredientId: id,
|
|
name: def.name,
|
|
qty: getPantryTotal(id, pantry),
|
|
unit: def.pantryUnit,
|
|
image: def.image || null,
|
|
icon: CATEGORY_ICONS[def.category] || 'fa-jar',
|
|
};
|
|
})
|
|
.sort((a, b) => a.name.length - b.name.length);
|
|
|
|
return { shortfalls, sufficient, notPlanned };
|
|
}
|
|
|
|
/* ══════════════════════ TILE RENDERING ══════════════════════ */
|
|
|
|
function tileIconHtml(item, size = 'sm') {
|
|
const wrap = size === 'lg' ? 'w-11 h-11' : 'w-7 h-7';
|
|
const iconSize = size === 'lg' ? 'text-[22px]' : 'text-[15px]';
|
|
if (item.image) {
|
|
return `<div class="${wrap} shrink-0 overflow-hidden"><img src="${esc(item.image)}" alt="" class="w-full h-full object-contain"></div>`;
|
|
}
|
|
return `<div class="${wrap} flex items-center justify-center shrink-0"><i class="fas ${item.icon} ${iconSize}" style="color:rgb(var(--text-faint-rgb));"></i></div>`;
|
|
}
|
|
|
|
function shortfallTileHtml(item) {
|
|
const clamp = item.name.length > 25 ? ' min-w-0' : '';
|
|
return `
|
|
<button type="button" class="pv2-tile text-left rounded-2xl flex items-center gap-2 px-2.5 py-2${clamp} transition-all active:scale-[0.98]" style="flex:1 0 auto; min-width:8.5rem; max-width:100%;" data-id="${esc(item.ingredientId)}">
|
|
${tileIconHtml(item, 'lg')}
|
|
<div class="flex-1 min-w-0 flex flex-col gap-1">
|
|
<p class="text-[11px] font-normal leading-tight truncate" style="color:rgb(var(--text-body-rgb));">${esc(item.name)}</p>
|
|
<div class="flex items-center gap-2">
|
|
<div class="pv2-track flex-1 h-1 rounded-full overflow-hidden">
|
|
<div class="h-full rounded-full" style="width:${item.fillPct}%; background:${SHORTFALL_ACCENT};"></div>
|
|
</div>
|
|
<span class="shrink-0 text-[10px] font-semibold tabular-nums" style="color:rgb(var(--text-body-rgb));">${esc(formatQty(item.pantryQty))}<span class="font-medium" style="color:rgb(var(--text-dim-rgb));">/${esc(formatQty(item.needed))} ${esc(unitLabel(item.unit))}</span></span>
|
|
</div>
|
|
</div>
|
|
</button>`;
|
|
}
|
|
|
|
function sufficientTileHtml(item) {
|
|
const clamp = item.name.length > 25 ? ' min-w-0' : '';
|
|
return `
|
|
<button type="button" class="pv2-tile text-left rounded-2xl flex items-center gap-2 px-2.5 py-2${clamp} transition-all active:scale-[0.98]" style="flex:1 0 auto; min-width:8.5rem; max-width:100%;" data-id="${esc(item.ingredientId)}">
|
|
${tileIconHtml(item, 'lg')}
|
|
<div class="flex-1 min-w-0 flex flex-col gap-1">
|
|
<p class="text-[11px] font-normal leading-tight truncate" style="color:rgb(var(--text-body-rgb));">${esc(item.name)}</p>
|
|
<div class="flex items-center gap-2">
|
|
<div class="pv2-track flex-1 h-1 rounded-full overflow-hidden">
|
|
<div class="h-full rounded-full" style="width:100%; background:rgb(var(--success-rgb));"></div>
|
|
</div>
|
|
<span class="shrink-0 text-[10px] font-semibold tabular-nums" style="color:rgb(var(--success-rgb));">${esc(formatQty(item.pantryQty))}<span class="font-medium" style="color:rgb(var(--text-dim-rgb));">/${esc(formatQty(item.needed))} ${esc(unitLabel(item.unit))}</span></span>
|
|
</div>
|
|
</div>
|
|
</button>`;
|
|
}
|
|
|
|
function notPlannedChipHtml(item) {
|
|
const hasStock = item.qty > 0;
|
|
const clamp = item.name.length > 25 ? ' min-w-0' : '';
|
|
return `
|
|
<button type="button" class="pv2-tile text-left rounded-2xl flex items-center gap-1.5 px-2.5 py-2${clamp} transition-all active:scale-[0.98]" style="flex:1 0 auto; min-width:6rem; max-width:100%;" data-id="${esc(item.ingredientId)}">
|
|
${tileIconHtml(item)}
|
|
<p class="text-[11px] font-normal leading-tight truncate min-w-0" style="color:${hasStock ? 'rgb(var(--text-muted-rgb))' : 'rgb(var(--text-dim-rgb))'};">${esc(item.name)}</p>
|
|
<span class="text-[10px] font-semibold tabular-nums shrink-0 ml-auto" style="color:${hasStock ? 'rgb(var(--text-dim-rgb))' : 'rgb(var(--text-subdued-rgb))'};">${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">
|
|
<span class="text-[10px] font-bold uppercase tracking-wider" style="color:${titleColor};">${esc(title)}</span>
|
|
<span class="text-[10px]" style="color:rgb(var(--text-subdued-rgb));">${count}</span>
|
|
</div>`;
|
|
}
|
|
|
|
function renderBoard() {
|
|
const root = document.getElementById('pantry-board');
|
|
if (!root) return;
|
|
|
|
const q = pantrySearchQuery;
|
|
const hasFilters = hasActivePantryFilters();
|
|
const { shortfalls, sufficient, notPlanned } = classifyIngredients(q);
|
|
|
|
const totalVisible = shortfalls.length + sufficient.length + notPlanned.length;
|
|
if (totalVisible === 0 && (q || hasFilters)) {
|
|
root.innerHTML = `<p class="text-sm text-center py-10" style="color:rgb(var(--text-dim-rgb));">Brak wyników — zmień filtry lub wyszukiwanie.</p>`;
|
|
return;
|
|
}
|
|
|
|
let html = '';
|
|
|
|
// Section 1: Potrzebne (shortfalls)
|
|
if (shortfalls.length > 0) {
|
|
html += `<section class="mb-5">`;
|
|
html += sectionHeaderHtml('fa-exclamation', 'rgb(var(--card-soft-rgb))', SHORTFALL_ACCENT, 'Potrzebne', 'rgb(var(--text-faint-rgb))', shortfalls.length);
|
|
html += `<div class="flex flex-wrap gap-2">`;
|
|
html += shortfalls.sort((a, b) => a.name.length - b.name.length).map(shortfallTileHtml).join('');
|
|
html += `</div></section>`;
|
|
}
|
|
|
|
// Section 2: W spiżarni (sufficient)
|
|
if (sufficient.length > 0) {
|
|
html += `<section class="mb-5">`;
|
|
html += sectionHeaderHtml('fa-check', 'rgba(var(--success-rgb), 0.14)', 'rgb(var(--success-rgb))', 'W spiżarni', 'rgb(var(--text-faint-rgb))', sufficient.length);
|
|
html += `<div class="flex flex-wrap gap-2">`;
|
|
html += sufficient.sort((a, b) => a.name.length - b.name.length).map(sufficientTileHtml).join('');
|
|
html += `</div></section>`;
|
|
}
|
|
|
|
// Section 3: Poza planem
|
|
if (notPlanned.length > 0) {
|
|
html += `<section class="mb-5">`;
|
|
html += sectionHeaderHtml('fa-minus', 'rgb(var(--app-bg-rgb))', 'rgb(var(--text-subdued-rgb))', 'Poza planem', 'rgb(var(--text-faint-rgb))', 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 && !hasFilters) {
|
|
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:rgb(var(--card-rgb));">
|
|
<i class="fas fa-calendar-xmark text-lg" style="color:rgb(var(--text-subdued-rgb));"></i>
|
|
</div>
|
|
<p class="text-[13px] font-semibold mb-1" style="color:rgb(var(--text-body-rgb));">Brak zaplanowanych posiłków</p>
|
|
<p class="text-[11px] max-w-[16rem]" style="color:rgb(var(--text-dim-rgb));">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));
|
|
});
|
|
}
|
|
|
|
/* ══════════════════════ INGREDIENT SHEET ══════════════════════ */
|
|
|
|
function openIngredientCard(ingredientId, productId) {
|
|
ingredientCard?.open({
|
|
ingredientId,
|
|
productId,
|
|
sourceNote: 'Ze spiżarni',
|
|
onAfterChange: () => renderBoard(),
|
|
});
|
|
}
|
|
|
|
/* ══════════════════════ PUBLIC API ══════════════════════ */
|
|
|
|
export function refreshPantry() {
|
|
syncHorizonUI();
|
|
renderBoard();
|
|
ingredientCard?.refresh();
|
|
}
|
|
|
|
export function setupPantry() {
|
|
ensureFilterPopoverStyles();
|
|
|
|
if (!ingredientCard) {
|
|
ingredientCard = createIngredientCardController({ idBase: 'pv2-card', defaultSourceNote: 'Ze spiżarni' });
|
|
ingredientCard.bind();
|
|
}
|
|
|
|
syncHorizonUI();
|
|
renderBoard();
|
|
|
|
// Search
|
|
document.getElementById('pantry-search-btn')?.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
setPantrySearchOpen(true, { focusInput: true });
|
|
});
|
|
document.getElementById('pantry-search-input')?.addEventListener('input', (event) => {
|
|
pantrySearchQuery = event.target.value.trim();
|
|
renderBoard();
|
|
});
|
|
document.getElementById('pantry-search-input')?.addEventListener('keydown', (event) => {
|
|
if (event.key !== 'Escape') return;
|
|
event.stopPropagation();
|
|
setPantrySearchOpen(false, { clearQuery: true });
|
|
});
|
|
document.getElementById('pantry-filter-bottom-btn')?.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
if (pantrySearchOpen) {
|
|
setPantrySearchOpen(false, { clearQuery: true });
|
|
return;
|
|
}
|
|
toggleFilterPanel();
|
|
});
|
|
document.getElementById('pantry-filter-clear')?.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
pantryFilters = { categories: [], sections: [] };
|
|
syncHorizonUI();
|
|
renderBoard();
|
|
});
|
|
document.getElementById('pantry-filter-panel-body')?.addEventListener('click', (event) => {
|
|
const target = event.target;
|
|
if (!(target instanceof Element)) return;
|
|
|
|
const chip = target.closest('[data-pantry-filter-kind]');
|
|
if (!(chip instanceof Element)) return;
|
|
|
|
event.stopPropagation();
|
|
|
|
const kind = chip.getAttribute('data-pantry-filter-kind');
|
|
const value = chip.getAttribute('data-pantry-filter-value');
|
|
if (!kind || !value) return;
|
|
|
|
if (kind === 'category') {
|
|
pantryFilters = {
|
|
...pantryFilters,
|
|
categories: toggleStringFilter(pantryFilters.categories, value),
|
|
};
|
|
}
|
|
if (kind === 'section') {
|
|
pantryFilters = {
|
|
...pantryFilters,
|
|
sections: toggleStringFilter(pantryFilters.sections, value),
|
|
};
|
|
}
|
|
|
|
syncHorizonUI();
|
|
renderBoard();
|
|
});
|
|
|
|
// Horizon pill + calendar
|
|
document.getElementById('pantry-horizon-compact')?.addEventListener('click', (event) => {
|
|
event.stopPropagation();
|
|
isCalendarOpen ? closeCalendar() : openCalendar();
|
|
});
|
|
bindPantryCalendarInteractions();
|
|
|
|
if (!pantryGlobalListenersBound) {
|
|
pantryGlobalListenersBound = true;
|
|
document.addEventListener('click', (event) => {
|
|
const target = event.target;
|
|
if (!(target instanceof Element)) return;
|
|
if (isCalendarOpen && !target.closest('#pantry-horizon-wrap, #pantry-horizon-compact')) {
|
|
closeCalendar();
|
|
}
|
|
if (isFilterOpen && !target.closest('#pantry-filter-popover, #pantry-filter-bottom-btn')) {
|
|
closeFilter();
|
|
}
|
|
});
|
|
document.addEventListener('keydown', (event) => {
|
|
if (event.key !== 'Escape') return;
|
|
if (pantrySearchOpen) {
|
|
setPantrySearchOpen(false, { clearQuery: true });
|
|
return;
|
|
}
|
|
if (pantrySearchQuery) clearSearchInput();
|
|
if (isFilterOpen) closeFilter();
|
|
});
|
|
window.addEventListener('app-tab-change', () => {
|
|
if (pantrySearchOpen) setPantrySearchOpen(false);
|
|
closeFilter();
|
|
closeCalendar();
|
|
});
|
|
window.closePantrySearch = () => {
|
|
if (pantrySearchOpen) setPantrySearchOpen(false);
|
|
};
|
|
window.closePantryFilter = () => {
|
|
closeFilter();
|
|
};
|
|
}
|
|
|
|
window.refreshPantry = refreshPantry;
|
|
}
|