/** * Modul: Dashboard * Zweck: Startseite mit Begrüßung, Terminen, Aufgaben, Essen, Notizen und FAB * Abhängigkeiten: /api.js */ import { api } from '/api.js'; // Hält den AbortController des aktuellen FAB-Listeners — wird bei jedem render() erneuert. let _fabController = null; // -------------------------------------------------------- // Hilfsfunktionen // -------------------------------------------------------- function greeting(displayName) { const h = new Date().getHours(); const tageszeit = h < 12 ? 'Morgen' : h < 18 ? 'Tag' : 'Abend'; return `Guten ${tageszeit}, ${displayName}`; } function formatDate(date = new Date()) { return date.toLocaleDateString('de-DE', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', }); } function formatDateTime(isoString) { if (!isoString) return ''; const d = new Date(isoString); const today = new Date(); const tomorrow = new Date(today); tomorrow.setDate(today.getDate() + 1); const dateStr = d.toDateString() === today.toDateString() ? 'Heute' : d.toDateString() === tomorrow.toDateString() ? 'Morgen' : d.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' }); const timeStr = d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }); return `${dateStr}, ${timeStr} Uhr`; } function formatDueDate(dateStr) { if (!dateStr) return null; const due = new Date(dateStr); const now = new Date(); const diffMs = due - now; const diffH = diffMs / (1000 * 60 * 60); if (diffMs < 0) return { text: 'Überfällig', overdue: true }; if (diffH < 24) return { text: 'Heute fällig', overdue: false }; if (diffH < 48) return { text: 'Morgen fällig', overdue: false }; return { text: due.toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' }), overdue: false, }; } const MEAL_LABELS = { breakfast: 'Frühstück', lunch: 'Mittagessen', dinner: 'Abendessen', snack: 'Snack', }; const MEAL_ICONS = { breakfast: 'sunrise', lunch: 'sun', dinner: 'moon', snack: 'apple', }; function initials(name = '') { return name.split(' ').map((w) => w[0]).join('').slice(0, 2).toUpperCase(); } function widgetHeader(icon, title, count, linkHref, linkLabel = 'Alle') { const badge = count != null ? `${count}` : ''; return `
${title} ${badge} ${linkLabel}
`; } // -------------------------------------------------------- // Skeleton // -------------------------------------------------------- function skeletonWidget(lines = 3) { const lineHtml = Array.from({ length: lines }, (_, i) => `
`).join(''); return `
${lineHtml}
`; } // -------------------------------------------------------- // Widget-Renderer // -------------------------------------------------------- function renderGreeting(user, stats = {}) { const { urgentCount = 0, todayEventCount = 0, todayMealTitle = null } = stats; const chipIcon = 'width:12px;height:12px;flex-shrink:0;'; const statChips = []; if (urgentCount > 0) statChips.push(` ${urgentCount} dring. Aufgabe${urgentCount > 1 ? 'n' : ''} `); if (todayEventCount > 0) statChips.push(` ${todayEventCount} Termin${todayEventCount > 1 ? 'e' : ''} heute `); if (todayMealTitle) statChips.push(` Heute: ${todayMealTitle} `); return `
${greeting(user.display_name)}
${formatDate()}
${statChips.length ? `
${statChips.join('')}
` : ''}
`; } function renderUrgentTasks(tasks) { if (!tasks.length) { return `
${widgetHeader('check-square', 'Aufgaben', 0, '/tasks')}
Alles erledigt
`; } const items = tasks.map((t) => { const due = formatDueDate(t.due_date); return `
${t.title}
${due ? `
${due.text}
` : ''}
${t.assigned_color ? `
${initials(t.assigned_name || '')}
` : ''}
`; }).join(''); return `
${widgetHeader('check-square', 'Aufgaben', tasks.length, '/tasks')}
${items}
`; } function renderUpcomingEvents(events) { if (!events.length) { return `
${widgetHeader('calendar', 'Termine', 0, '/calendar')}
Keine Termine
`; } const today = new Date().toDateString(); const items = events.map((e) => { const d = new Date(e.start_datetime); const isToday = d.toDateString() === today; const timeStr = e.all_day ? 'Ganztägig' : d.toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }) + ' Uhr'; return `
${e.title}
${isToday ? 'Heute' : formatDateTime(e.start_datetime).split(',')[0]} ${timeStr} ${e.location ? ` · ${e.location}` : ''}
`; }).join(''); return `
${widgetHeader('calendar', 'Termine', events.length, '/calendar')}
${items}
`; } function renderTodayMeals(meals) { const MEAL_ORDER = ['breakfast', 'lunch', 'dinner', 'snack']; const slots = MEAL_ORDER.map((type) => { const meal = meals.find((m) => m.meal_type === type); return `
${MEAL_LABELS[type]}
${meal ? meal.title : '—'}
`; }).join(''); return `
${widgetHeader('utensils', 'Heute essen', null, '/meals', 'Woche')}
${slots}
`; } function renderPinnedNotes(notes) { if (!notes.length) { return `
${widgetHeader('pin', 'Pinnwand', 0, '/notes')}
Keine angepinnten Notizen
`; } const items = notes.map((n) => `
${n.title ? `
${n.title}
` : ''}
${n.content}
`).join(''); return `
${widgetHeader('pin', 'Pinnwand', notes.length, '/notes')}
${items}
`; } // -------------------------------------------------------- // Wetter-Widget // -------------------------------------------------------- const WEATHER_ICON_BASE = 'https://openweathermap.org/img/wn/'; function renderWeatherWidget(weather) { if (!weather) return ''; const { city, current, forecast } = weather; const forecastHtml = forecast.map((d, i) => { const date = new Date(d.date + 'T12:00:00'); const label = date.toLocaleDateString('de-DE', { weekday: 'short' }); const extraCls = i >= 3 ? ' weather-forecast__day--extended' : ''; return `
${label}
${d.desc}
${d.temp_max}° ${d.temp_min}°
`; }).join(''); return `
${current.temp}°C
${current.desc}
${city}
Gefühlt ${current.feels_like}° · ${current.humidity}% · Wind ${current.wind_speed} km/h
${current.desc}
${forecast.length ? `
${forecastHtml}
` : ''}
`; } // -------------------------------------------------------- // FAB Speed-Dial // -------------------------------------------------------- const FAB_ACTIONS = [ { route: '/tasks', label: 'Aufgabe', icon: 'check-square' }, { route: '/calendar', label: 'Termin', icon: 'calendar-plus' }, { route: '/shopping', label: 'Einkauf', icon: 'shopping-cart' }, { route: '/notes', label: 'Notiz', icon: 'sticky-note' }, ]; function renderFab() { const actionsHtml = FAB_ACTIONS.map((a) => `
${a.label}
`).join(''); return `
`; } function initFab(container, signal) { const fabMain = container.querySelector('#fab-main'); const fabActions = container.querySelector('#fab-actions'); if (!fabMain) return; let open = false; function toggleFab(force) { open = force !== undefined ? force : !open; fabMain.classList.toggle('fab-main--open', open); fabMain.setAttribute('aria-expanded', String(open)); fabActions.classList.toggle('fab-actions--visible', open); fabActions.setAttribute('aria-hidden', String(!open)); fabActions.querySelectorAll('[role="button"]').forEach((el) => { el.tabIndex = open ? 0 : -1; }); if (window.lucide) window.lucide.createIcons(); } fabMain.addEventListener('click', (e) => { e.stopPropagation(); toggleFab(); }); fabActions.querySelectorAll('[data-route]').forEach((el) => { const go = () => { toggleFab(false); window.oikos.navigate(el.dataset.route); }; el.addEventListener('click', go); el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); }); document.addEventListener('click', () => { if (open) toggleFab(false); }, { signal }); } // -------------------------------------------------------- // Navigations-Links verdrahten // -------------------------------------------------------- function wireLinks(container) { container.querySelectorAll('[data-route]').forEach((el) => { if (el.id === 'fab-main' || el.closest('#fab-actions')) return; const go = () => window.oikos.navigate(el.dataset.route); if (el.tagName === 'A') { el.addEventListener('click', (e) => { e.preventDefault(); go(); }); } else { el.addEventListener('click', go); el.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); } }); } // -------------------------------------------------------- // Haupt-Render // -------------------------------------------------------- export async function render(container, { user }) { _fabController?.abort(); _fabController = new AbortController(); container.innerHTML = `
${greeting(user.display_name)}
${formatDate()}
${skeletonWidget(3)} ${skeletonWidget(3)} ${skeletonWidget(2)} ${skeletonWidget(3)}
${renderFab()} `; let data = { upcomingEvents: [], urgentTasks: [], todayMeals: [], pinnedNotes: [] }; let weather = null; try { const [dashRes, weatherRes] = await Promise.all([ api.get('/dashboard'), api.get('/weather').catch(() => ({ data: null })), ]); data = dashRes; weather = weatherRes.data ?? null; } catch (err) { console.error('[Dashboard] Ladefehler:', err.message); window.oikos?.showToast('Dashboard konnte nicht vollständig geladen werden.', 'warning'); } const today = new Date().toDateString(); const stats = { urgentCount: (data.urgentTasks ?? []).filter((t) => t.priority === 'urgent' || t.priority === 'high').length, todayEventCount: (data.upcomingEvents ?? []).filter((e) => new Date(e.start_datetime).toDateString() === today ).length, todayMealTitle: (data.todayMeals ?? []).find((m) => m.meal_type === 'lunch')?.title ?? (data.todayMeals ?? [])[0]?.title ?? null, }; container.innerHTML = `

Übersicht

${renderGreeting(user, stats)} ${renderWeatherWidget(weather)} ${renderUrgentTasks(data.urgentTasks ?? [])} ${renderUpcomingEvents(data.upcomingEvents ?? [])} ${renderTodayMeals(data.todayMeals ?? [])} ${renderPinnedNotes(data.pinnedNotes ?? [])}
${renderFab()} `; wireLinks(container); initFab(container, _fabController.signal); if (window.lucide) window.lucide.createIcons(); }