/* ============================================================ BAN YARO — Tagebuch (Sprint 1) Seiten-Modul: Timeline aller Einträge, Erstellen, Bearbeiten, Löschen, Foto-Upload, Meilensteine. ============================================================ */ window.Page_diary = (() => { // ---------------------------------------------------------- // MODUL-STATE // ---------------------------------------------------------- let _container = null; let _appState = null; let _entries = []; let _offset = 0; let _searchQuery = ''; let _filterMilestone = false; const LIMIT = 20; function _sourceIcon(source) { if (source === 'places') return 'star'; if (source === 'osm') return 'map-pin'; return 'map-trifold'; } const _VIDEO_EXT = new Set(['.mp4','.mov','.webm','.m4v','.avi']); function _isVideo(url) { if (!url) return false; return _VIDEO_EXT.has(url.slice(url.lastIndexOf('.')).toLowerCase()); } function _mediaHtml(url, style = '') { if (!url) return ''; return _isVideo(url) ? `` : `Foto`; } /** Alle Mediendateien eines Eintrags normalisiert als Array zurückgeben. * Rückwärtskompatibel: wenn media_items leer, aber media_url gesetzt → altes Format. */ function _allMedia(entry) { const items = entry.media_items || []; if (items.length > 0) return items; if (entry.media_url) { return [{ id: null, url: entry.media_url, media_type: _isVideo(entry.media_url) ? 'video' : 'image', sort_order: 0 }]; } return []; } const TYPEN = { eintrag: { label: 'Eintrag', icon: '' }, foto: { label: 'Foto', icon: '' }, meilenstein:{ label: 'Meilenstein',icon: '' }, training: { label: 'Training', icon: '' }, gesundheit: { label: 'Gesundheit', icon: '' }, spaziergang:{ label: 'Spaziergang', icon: '' }, ausflug: { label: 'Ausflug', icon: '' }, }; // ---------------------------------------------------------- // INIT — erster Aufruf, Container leer // ---------------------------------------------------------- async function init(container, appState) { _container = container; _appState = appState; UI.loadLeaflet(); // Leaflet im Hintergrund vorladen — kein await await _render(); } // ---------------------------------------------------------- // REFRESH — erneuter Navigations-Aufruf (Tap auf Tab) // ---------------------------------------------------------- async function refresh() { if (!_appState.activeDog) return; // Mehrere Hunde → Picker zeigen (User kann Hund wählen) if (_appState.dogs.length > 1) { _renderDogPicker(); return; } // Einzelner Hund → Diary direkt neu laden _offset = 0; _entries = []; await _renderDiary(); } // ---------------------------------------------------------- // ON DOG CHANGE — vom Header-Switcher ausgelöst // ---------------------------------------------------------- async function onDogChange(dog) { _offset = 0; _entries = []; _searchQuery = ''; await _renderDiary(); } // ---------------------------------------------------------- // OPEN NEW — vom + Button oder Quick-Add // ---------------------------------------------------------- function openNew() { _showForm(null); } // ---------------------------------------------------------- // RENDER — Einstieg: Picker bei mehreren Hunden, sonst direkt // ---------------------------------------------------------- async function _render() { if (!_appState.activeDog) { _container.innerHTML = UI.emptyState({ icon: '', title: 'Noch kein Hund angelegt', text: 'Erstelle zuerst ein Hundeprofil, um das Tagebuch zu nutzen.', action: ``, }); _container.querySelector('#diary-goto-profile') ?.addEventListener('click', () => App.navigate('dog-profile')); return; } if (_appState.dogs.length > 1) { _renderDogPicker(); } else { await _renderDiary(); } } // ---------------------------------------------------------- // HUNDE-PICKER — Einstiegsseite bei mehreren Hunden // ---------------------------------------------------------- function _renderDogPicker() { const activeDogId = _appState.activeDog?.id; const cards = _appState.dogs.map(dog => { const isActive = dog.id === activeDogId; const av = dog.foto_url ? `${UI.escape(dog.name)}` : `${UI.icon('dog')}`; return `
${av}
${UI.escape(dog.name)}
${dog.rasse ? `
${UI.escape(dog.rasse)}
` : ''}
`; }).join(''); _container.innerHTML = `

Wessen Tagebuch?

${cards}
`; _container.querySelectorAll('.diary-picker-card').forEach(el => { el.addEventListener('click', async () => { const id = parseInt(el.dataset.dogId); if (id === _appState.activeDog?.id) { // Bereits aktiver Hund → direkt Diary laden _offset = 0; _entries = []; await _renderDiary(); } else { App.setActiveDog(id); // onDogChange() → _renderDiary() via _notifyDogChange() } }); }); } // ---------------------------------------------------------- // DIARY-ANSICHT — Timeline mit Einträgen // ---------------------------------------------------------- async function _renderDiary() { _container.innerHTML = `
`; _container.querySelector('#diary-milestone-filter') ?.addEventListener('click', async () => { _filterMilestone = !_filterMilestone; _offset = 0; _entries = []; const btn = _container.querySelector('#diary-milestone-filter'); btn?.classList.toggle('btn-active', _filterMilestone); await _load(); _renderList(); }); _container.querySelector('#diary-import-btn') ?.addEventListener('click', _showImport); _container.querySelector('#diary-btn-more') ?.addEventListener('click', () => _loadMore()); // Suche mit Debounce let _searchTimer = null; _container.querySelector('#diary-search-input') ?.addEventListener('input', e => { clearTimeout(_searchTimer); _searchTimer = setTimeout(async () => { _offset = 0; _entries = []; _searchQuery = e.target.value.trim(); await _load(); _renderList(); }, 350); }); await _load(); _renderList(); } // ---------------------------------------------------------- // DATEN LADEN // ---------------------------------------------------------- async function _load() { const dog = _appState.activeDog; if (!dog) return; try { const params = { limit: LIMIT, offset: _offset }; if (_searchQuery) params.q = _searchQuery; if (_filterMilestone) params.milestone = 1; const batch = await API.diary.list(dog.id, params); _entries = _entries.concat(batch); // "Mehr laden" anzeigen wenn volle Page geladen wurde const loadMore = _container.querySelector('#diary-load-more'); if (loadMore) { loadMore.style.display = batch.length === LIMIT ? 'block' : 'none'; } } catch (err) { UI.toast.error('Einträge konnten nicht geladen werden.'); } } async function _loadMore() { _offset += LIMIT; const btn = _container.querySelector('#diary-btn-more'); UI.setLoading(btn, true); await _load(); _renderList(); UI.setLoading(btn, false); } // ---------------------------------------------------------- // LISTE RENDERN — Timeline gruppiert nach Monat // ---------------------------------------------------------- function _renderList() { const listEl = _container.querySelector('#diary-list'); if (!listEl) return; if (_entries.length === 0) { listEl.innerHTML = UI.emptyState({ icon: UI.icon('book-open'), title: 'Noch keine Tagebucheinträge', text: 'Halte besondere Momente mit deinem Hund fest — Spaziergänge, Erlebnisse, Erinnerungen.', action: ``, }); listEl.querySelector('#diary-first-entry') ?.addEventListener('click', () => _showForm(null)); return; } // Gruppieren nach Jahr-Monat (Anzeigereihenfolge: chronologisch absteigend) const groups = new Map(); _entries.forEach(e => { const key = e.datum ? e.datum.slice(0, 7) : 'unbekannt'; // "2025-04" if (!groups.has(key)) groups.set(key, []); groups.get(key).push(e); }); let html = ''; groups.forEach((items, key) => { const monthLabel = key === 'unbekannt' ? 'Datum unbekannt' : _formatMonth(key); html += `
${monthLabel}
`; html += items.map(e => _entryCard(e)).join(''); }); listEl.innerHTML = html; // Events an Karten binden listEl.querySelectorAll('[data-entry-id]').forEach(card => { const id = parseInt(card.dataset.entryId); card.addEventListener('click', () => _openDetail(id)); }); } // ---------------------------------------------------------- // ENTRY CARD // ---------------------------------------------------------- function _entryCard(e) { const typ = TYPEN[e.typ] || TYPEN.eintrag; const isMile = e.is_milestone || e.typ === 'meilenstein'; const dateStr = e.datum ? UI.time.format(e.datum + 'T00:00:00') : ''; const tags = (e.tags || []).filter(t => t && t.trim()).slice(0, 4); const allMedia = _allMedia(e); const coverMedia = allMedia.find(m => m.is_cover) || allMedia[0] || null; const mediaCount = allMedia.length; const photo = coverMedia ? `
${coverMedia.media_type === 'video' ? `
` : `Foto`} ${mediaCount > 1 ? `${mediaCount}` : ''}
` : ''; const tagsHtml = tags.length ? `
${tags.map(t => `${t}`).join('')}
` : ''; const locationHtml = e.location_name ? `

${UI.escape(e.location_name)}

` : ''; const textPreview = e.text ? `

${UI.escape(e.text.slice(0, 140))}${e.text.length > 140 ? '…' : ''}

` : ''; // Meilenstein-Badge (nur bei is_milestone=1, nicht bei manuell gewähltem Typ 'meilenstein') const milestoneBadge = e.is_milestone ? `
${UI.icon('calendar-dots')} Meilenstein
` : ''; // Mehrere Hunde: kleine Avatare in der Karte const dogAvatars = _dogAvatarRow(e.dog_ids || []); return `
${photo}
${milestoneBadge}
${typ.icon} ${typ.label} ${dateStr}
${e.titel ? `
${UI.escape(e.titel)}
` : ''} ${locationHtml} ${textPreview} ${tagsHtml} ${dogAvatars}
`; } function _dogAvatarRow(dogIds) { if (!dogIds || dogIds.length <= 1) return ''; const avatars = dogIds.map(did => { const dog = _appState.dogs.find(d => d.id === did); if (!dog) return ''; return `
${dog.foto_url ? `` : `${UI.icon('dog')}`}
`; }).join(''); return `
${avatars}
`; } // ---------------------------------------------------------- // LIGHTBOX // ---------------------------------------------------------- function _showLightbox(src) { const lb = document.createElement('div'); lb.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,.92);z-index:9999;display:flex;align-items:center;justify-content:center;cursor:zoom-out'; lb.innerHTML = ` `; lb.addEventListener('click', () => lb.remove()); document.body.appendChild(lb); } // ---------------------------------------------------------- // DETAIL-ANSICHT // ---------------------------------------------------------- function _openDetail(entryId) { const entry = _entries.find(e => e.id === entryId); if (!entry) return; const typ = TYPEN[entry.typ] || TYPEN.eintrag; const isMile = entry.is_milestone || entry.typ === 'meilenstein'; const tags = (entry.tags || []).filter(t => t && t.trim()); const allMedia = _allMedia(entry); const photo = allMedia.length > 0 ? (allMedia.length === 1 ? `
${_mediaHtml(allMedia[0].url)}
` : ``) : ''; // Hunde-Anzeige wenn mehrere beteiligt const dogIds = entry.dog_ids || [entry.dog_id]; const dogsHtml = dogIds.length > 1 ? `
${dogIds.map(did => { const dog = _appState.dogs.find(d => d.id === did); return dog ? `
${dog.foto_url ? `` : `${UI.icon('dog')}`}
${UI.escape(dog.name)}
` : ''; }).join('')}
` : ''; const body = ` ${isMile ? `
${UI.icon('trophy')} Meilenstein
` : ''}
${typ.icon} ${typ.label} ${entry.datum ? UI.time.format(entry.datum + 'T00:00:00') : ''}
${entry.location_name ? `
${entry.gps_lat ? `${UI.escape(entry.location_name)}` : UI.escape(entry.location_name)}
` : ''} ${entry.text ? `

${UI.escape(_cleanText(entry.text))}

` : ''} ${tags.length ? `
${tags.map(t => `${t}`).join('')}
` : ''} ${dogsHtml} ${photo} ${!_appState?.activeDog?.is_guest ? `` : ''} `; UI.modal.open({ title: entry.titel || typ.label, body }); // Bilder anklickbar machen (Lightbox) document.querySelector('#modal-container .modal-body')?.querySelectorAll('img').forEach(img => { img.style.cursor = 'zoom-in'; img.addEventListener('click', () => _showLightbox(img.src)); }); // Stern-Buttons: Cover-Bild setzen document.querySelectorAll('.diary-cover-btn').forEach(btn => { btn.addEventListener('click', async (ev) => { ev.stopPropagation(); const mediaId = parseInt(btn.dataset.mediaId); try { await API.diary.setCover(_appState.activeDog.id, entry.id, mediaId); // Lokalen State aktualisieren if (entry.media_items) { entry.media_items.forEach(m => { m.is_cover = m.id === mediaId ? 1 : 0; }); } entry.cover_url = (entry.media_items || []).find(m => m.id === mediaId)?.url || null; _updateEntryInList(entry); // Alle Sterne im Modal aktualisieren document.querySelectorAll('.diary-cover-btn').forEach(b => { const active = parseInt(b.dataset.mediaId) === mediaId; b.classList.toggle('diary-cover-btn--active', active); b.style.background = active ? '#f5c518' : 'rgba(0,0,0,.45)'; b.style.color = active ? '#fff' : 'rgba(255,255,255,.7)'; b.setAttribute('aria-label', active ? 'Cover-Bild' : 'Als Cover setzen'); b.setAttribute('title', active ? 'Cover-Bild' : 'Als Cover setzen'); const use = b.querySelector('use'); if (use) use.setAttribute('href', `/icons/phosphor.svg#${active ? 'star-fill' : 'star'}`); }); UI.toast.success('Cover-Bild gesetzt.'); } catch { UI.toast.error('Cover konnte nicht gesetzt werden.'); } }); }); document.getElementById('detail-edit')?.addEventListener('click', async () => { UI.modal.close(); // Nur nachladen wenn location_name/gps_lat fehlen (älterer In-Memory-Eintrag) if (entry.location_name !== undefined || entry.gps_lat !== undefined) { _showForm(entry); } else { try { const fresh = await API.diary.get(_appState.activeDog.id, entry.id); const idx = _entries.findIndex(e => e.id === entry.id); if (idx !== -1) _entries[idx] = fresh; _showForm(fresh); } catch { _showForm(entry); } } }); } // ---------------------------------------------------------- // FORMULAR — Neu erstellen / Bearbeiten // ---------------------------------------------------------- function _showForm(entry) { const isEdit = !!entry; const today = new Date().toISOString().slice(0, 10); const activeDog = _appState.activeDog; const typOpts = Object.entries(TYPEN) .map(([val, { icon, label }]) => ``) .join(''); // Weitere Hunde: alle außer dem aktiven const otherDogs = _appState.dogs.filter(d => d.id !== activeDog?.id); const entryDogIds = entry?.dog_ids || [activeDog?.id]; const dogPickerHtml = otherDogs.length > 0 ? `
${otherDogs.map(d => ` `).join('')}
` : ''; const body = `
${UI.escape(entry?.location_name || '')}
${dogPickerHtml}
`; const footer = `
${isEdit ? `` : ''}
`; UI.modal.open({ title: isEdit ? 'Eintrag bearbeiten' : 'Neuer Eintrag', body, footer }); const form = document.getElementById('diary-form'); // Fokus auf Titel-Feld → öffnet Keyboard auf Mobile, zeigt dem User was zu tun ist setTimeout(() => form?.querySelector('[name="titel"]')?.focus(), 150); // ---- Multi-Media-Verwaltung ---- const mediaInput = document.getElementById('diary-media-input'); // Neue Dateien die noch nicht hochgeladen wurden const _newFiles = []; function _renderNewGrid() { const grid = document.getElementById('diary-new-media-grid'); if (!grid) return; if (_newFiles.length === 0) { grid.style.display = 'none'; grid.innerHTML = ''; return; } grid.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:8px;margin-bottom:8px'; grid.innerHTML = _newFiles.map((f, i) => { const objUrl = URL.createObjectURL(f); const thumb = f.type.startsWith('video/') ? `` : ``; return `
${thumb}
`; }).join(''); grid.querySelectorAll('.diary-media-thumb-del').forEach(btn => { btn.addEventListener('click', () => { const idx = parseInt(btn.dataset.newIdx); _newFiles.splice(idx, 1); _renderNewGrid(); }); }); } // Bestehende Medien im Edit-Modus rendern function _renderExistingMedia() { const wrap = document.getElementById('diary-existing-media'); if (!wrap) return; const items = isEdit ? _allMedia(entry) : []; if (items.length === 0) { wrap.innerHTML = ''; return; } const GRID_STYLE = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(90px,1fr));gap:8px;margin-bottom:8px'; const grid = `
${items.map((m, idx) => `
${m.media_type === 'video' ? `` : ``} ${m.id != null ? ` ` : ''}
`).join('')}
`; wrap.innerHTML = grid; wrap.querySelectorAll('.diary-media-thumb-del').forEach(btn => { btn.addEventListener('click', async () => { const wrap2 = btn.closest('.diary-media-thumb-wrap'); const mediaId = btn.dataset.mediaId ? parseInt(btn.dataset.mediaId) : null; const isLegacy = !!btn.dataset.legacy; btn.disabled = true; try { if (mediaId != null) { await API.diary.deleteMediaItem(_appState.activeDog.id, entry.id, mediaId); // aus entry.media_items entfernen if (entry.media_items) entry.media_items = entry.media_items.filter(m => m.id !== mediaId); } else if (isLegacy) { await API.diary.deleteMedia(_appState.activeDog.id, entry.id); entry.media_url = null; } wrap2.remove(); UI.toast.success('Medium entfernt.'); } catch (e) { btn.disabled = false; UI.toast.error(e.message || 'Fehler beim Löschen.'); } }); }); // Stern-Buttons im Edit-Formular wrap.querySelectorAll('.diary-cover-btn--form').forEach(btn => { btn.addEventListener('click', async () => { const mediaId = parseInt(btn.dataset.mediaId); try { await API.diary.setCover(_appState.activeDog.id, entry.id, mediaId); if (entry.media_items) { entry.media_items.forEach(m => { m.is_cover = m.id === mediaId ? 1 : 0; }); } entry.cover_url = (entry.media_items || []).find(m => m.id === mediaId)?.url || null; _updateEntryInList(entry); // Alle Sterne in diesem Formular aktualisieren wrap.querySelectorAll('.diary-cover-btn--form').forEach(b => { const active = parseInt(b.dataset.mediaId) === mediaId; b.classList.toggle('diary-cover-btn--active', active); b.style.background = active ? '#f5c518' : 'rgba(0,0,0,.45)'; b.style.color = active ? '#fff' : 'rgba(255,255,255,.7)'; b.setAttribute('aria-label', active ? 'Cover-Bild' : 'Als Cover setzen'); b.setAttribute('title', active ? 'Cover-Bild' : 'Als Cover setzen'); const use = b.querySelector('use'); if (use) use.setAttribute('href', `/icons/phosphor.svg#${active ? 'star-fill' : 'star'}`); }); UI.toast.success('Cover-Bild gesetzt.'); } catch { UI.toast.error('Cover konnte nicht gesetzt werden.'); } }); }); } _renderExistingMedia(); function _addFiles(fileList) { for (const f of fileList) _newFiles.push(f); _renderNewGrid(); } function _openPicker(opts = {}) { const tmp = document.createElement('input'); tmp.type = 'file'; tmp.accept = 'image/*,video/*'; tmp.style.display = 'none'; if (opts.capture) tmp.setAttribute('capture', opts.capture); if (opts.noAccept) tmp.removeAttribute('accept'); tmp.addEventListener('change', () => { _addFiles(tmp.files); tmp.remove(); }); document.body.appendChild(tmp); tmp.click(); } mediaInput?.addEventListener('change', () => { if (mediaInput.files.length) { _addFiles(mediaInput.files); mediaInput.value = ''; } }); document.getElementById('diary-form-cancel')?.addEventListener('click', UI.modal.close); // Milestone-Toggle document.getElementById('diary-milestone-btn')?.addEventListener('click', () => { const cb = document.getElementById('diary-milestone-cb'); const btn = document.getElementById('diary-milestone-btn'); cb.checked = !cb.checked; btn.classList.toggle('diary-milestone-toggle--active', cb.checked); btn.querySelector('span').textContent = cb.checked ? 'Meilenstein ✓' : 'Als Meilenstein markieren'; }); // --- Location Picker --- let _locLat = (entry?.gps_lat != null) ? entry.gps_lat : null; let _locLon = (entry?.gps_lon != null) ? entry.gps_lon : null; let _locName = entry?.location_name || null; let _miniMap = null, _miniMarker = null; const _pinSvg = ''; const _mkIcon = () => L.divIcon({ html: _pinSvg, className: '', iconSize: [32,40], iconAnchor: [16,40] }); function _setName(name) { _locName = name; document.getElementById('diary-location-label').textContent = name; document.getElementById('diary-location-chip-wrap').style.display = ''; document.getElementById('diary-location-suggestions').style.display = 'none'; } function _placeMarker(lat, lon) { if (_miniMarker) { _miniMarker.setLatLng([lat, lon]); return; } _miniMarker = L.marker([lat, lon], { draggable: false, icon: _mkIcon() }).addTo(_miniMap); _miniMarker.on('dragend', () => { const p = _miniMarker.getLatLng(); _locLat = p.lat; _locLon = p.lng; document.getElementById('diary-location-btn-label').textContent = 'POI suchen'; }); } document.getElementById('diary-location-clear')?.addEventListener('click', () => { _locName = null; document.getElementById('diary-location-chip-wrap').style.display = 'none'; }); const _clearBtn = document.getElementById('diary-coords-clear'); let _clearPending = false; _clearBtn?.addEventListener('click', () => { if (!_clearPending) { _clearPending = true; _clearBtn.textContent = 'Wirklich entfernen?'; _clearBtn.style.color = 'var(--c-danger)'; setTimeout(() => { if (_clearPending) { _clearPending = false; _clearBtn.textContent = 'Ort entfernen'; _clearBtn.style.color = 'var(--c-text-muted)'; } }, 3000); return; } _clearPending = false; _clearBtn.textContent = 'Ort entfernen'; _clearBtn.style.color = 'var(--c-text-muted)'; _locLat = null; _locLon = null; _locName = null; document.getElementById('diary-location-chip-wrap').style.display = 'none'; document.getElementById('diary-location-suggestions').style.display = 'none'; document.getElementById('diary-location-btn-label').textContent = 'POI suchen'; if (_miniMarker) { _miniMarker.remove(); _miniMarker = null; } if (_miniMap) { _miniMap.setView([48.0, 11.9], 7); _setMapEditing(false); } }); let _mapEditing = false; function _setMapEditing(on) { _mapEditing = on; const lbl = document.getElementById('diary-map-edit-label'); if (lbl) lbl.textContent = on ? 'Fertig' : 'Position ändern'; if (!_miniMap) return; if (on) { if (_miniMarker) _miniMarker.dragging.enable(); } else { if (_miniMarker) _miniMarker.dragging.disable(); } } document.getElementById('diary-map-edit-btn')?.addEventListener('click', () => { _setMapEditing(!_mapEditing); }); // Karte beim Formular-Open automatisch laden UI.loadLeaflet().then(() => { setTimeout(() => { const lat = _locLat || 48.0, lon = _locLon || 11.9, zoom = _locLat ? 15 : 7; _miniMap = L.map('diary-map-wrap', { zoomControl: true, attributionControl: false, dragging: true, scrollWheelZoom: false, }).setView([lat, lon], zoom); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }) .addTo(_miniMap); _miniMap.invalidateSize(); if (_locLat) { _placeMarker(lat, lon); _miniMarker.dragging.disable(); // Lesemodus: kein Drag } // Klick nur im Edit-Modus _miniMap.on('click', e => { if (!_mapEditing) return; _locLat = e.latlng.lat; _locLon = e.latlng.lng; _placeMarker(_locLat, _locLon); if (!_mapEditing) _miniMarker.dragging.disable(); document.getElementById('diary-location-btn-label').textContent = 'POI suchen'; }); }, 150); }); async function _showSuggestions() { const btn = document.getElementById('diary-location-btn'); UI.setLoading(btn, true); try { let lat = _locLat, lon = _locLon; if (lat == null || lon == null) { const pos = await API.getLocation(); lat = pos.lat; lon = pos.lon; _locLat = lat; _locLon = lon; if (_miniMap) { _miniMap.setView([lat, lon], 15); _placeMarker(lat, lon); } document.getElementById('diary-location-btn-label').textContent = 'POI suchen'; } const suggestions = await API.diary.nearby(_appState.activeDog.id, lat, lon); const sugEl = document.getElementById('diary-location-suggestions'); if (suggestions.length === 0) { sugEl.innerHTML = '

Keine Orte in der Nähe gefunden.

'; } else { sugEl.innerHTML = suggestions.map(s => ` `).join(''); sugEl.querySelectorAll('.diary-location-suggestion').forEach(el => { el.addEventListener('click', () => _setName(el.dataset.name)); }); } sugEl.style.display = ''; } catch (err) { UI.toast.error(err?.message?.includes('GPS') || lat == null ? 'GPS nicht verfügbar.' : 'Ortssuche fehlgeschlagen.'); } finally { UI.setLoading(btn, false); } } document.getElementById('diary-location-btn')?.addEventListener('click', _showSuggestions); document.getElementById('diary-form-delete')?.addEventListener('click', async () => { const ok = await UI.modal.confirm({ title: 'Eintrag löschen?', message: 'Dieser Vorgang kann nicht rückgängig gemacht werden.', confirmText: 'Löschen', danger: true, }); if (ok) await _deleteEntry(entry.id); }); // Checked-Klasse auf Dog-Picker-Items toggeln form.querySelectorAll('.diary-dog-pick-item input').forEach(cb => { cb.addEventListener('change', () => { cb.closest('.diary-dog-pick-item').classList.toggle('checked', cb.checked); }); }); form.addEventListener('submit', async e => { e.preventDefault(); const submitBtn = document.querySelector('[form="diary-form"][type="submit"]') || form.querySelector('[type="submit"]'); const fd = UI.formData(form); // dog_ids zusammenbauen: aktiver Hund + gewählte weitere const dogIds = [_appState.activeDog.id]; form.querySelectorAll('.diary-dog-pick-item input:checked').forEach(cb => { const id = parseInt(cb.value); if (!dogIds.includes(id)) dogIds.push(id); }); await UI.asyncButton(submitBtn, async () => { const payload = { datum: fd.datum || null, typ: fd.typ, titel: fd.titel || null, text: fd.text || null, is_milestone: 'is_milestone' in fd, dog_ids: dogIds, gps_lat: _locLat, gps_lon: _locLon, location_name: _locName, }; async function _uploadNewFiles(entryId) { let failCount = 0; const uploaded = []; for (const file of _newFiles) { try { const formData = new FormData(); formData.append('file', file); const m = await API.diary.uploadMedia(_appState.activeDog.id, entryId, formData); uploaded.push(m); } catch { failCount++; } } if (failCount > 0) { UI.toast.warning(`${failCount} Medium${failCount > 1 ? 'en' : ''} konnte${failCount > 1 ? 'n' : ''} nicht hochgeladen werden.`); } return uploaded; } if (isEdit) { const updated = await API.diary.update(_appState.activeDog.id, entry.id, payload); if (_newFiles.length > 0) { const uploaded = await _uploadNewFiles(entry.id); if (!updated.media_items) updated.media_items = []; updated.media_items.push(...uploaded); } else { // media_items aus dem aktuellen entry-State übernehmen (evtl. gelöscht via X-Button) updated.media_items = entry.media_items || updated.media_items || []; updated.media_url = entry.media_url ?? updated.media_url; } _updateEntryInList(updated); UI.toast.success('Eintrag gespeichert.'); } else { const created = await API.diary.create(_appState.activeDog.id, payload); if (_newFiles.length > 0) { const uploaded = await _uploadNewFiles(created.id); created.media_items = uploaded; } _entries.unshift(created); UI.toast.success('Eintrag erstellt.'); } UI.modal.close(); _renderList(); }); }); } // ---------------------------------------------------------- // EINTRAG LÖSCHEN // ---------------------------------------------------------- async function _deleteEntry(entryId) { try { await API.diary.delete(_appState.activeDog.id, entryId); _entries = _entries.filter(e => e.id !== entryId); UI.modal.close(); _renderList(); UI.toast.success('Eintrag gelöscht.'); } catch (err) { UI.toast.error(err.message || 'Fehler beim Löschen.'); } } // ---------------------------------------------------------- // HELPER // ---------------------------------------------------------- function _updateEntryInList(updated) { const i = _entries.findIndex(e => e.id === updated.id); if (i !== -1) _entries[i] = updated; } function _formatMonth(yearMonth) { const [y, m] = yearMonth.split('-'); return new Intl.DateTimeFormat('de-DE', { month: 'long', year: 'numeric' }) .format(new Date(+y, +m - 1, 1)); } // ---------------------------------------------------------- // IMPORT // ---------------------------------------------------------- function _showImport() { UI.modal.open({ title: 'Tagebuch importieren', body: `

Importiere Einträge aus einer anderen App in das Tagebuch von ${UI.escape(_appState.activeDog?.name || 'deinem Hund')}.

`, footer: ` `, }); // Format-Karten klickbar machen document.querySelectorAll('.import-format-card').forEach(card => { card.addEventListener('click', () => { document.querySelectorAll('.import-format-card').forEach(c => c.classList.remove('import-format-card--active')); card.classList.add('import-format-card--active'); card.querySelector('input[type=radio]').checked = true; // Accept-Attribut anpassen const fmt = card.querySelector('input').value; document.getElementById('import-file-input').accept = fmt === 'nsx' ? '.nsx' : '.csv'; }); }); // Erste Karte direkt aktiv setzen document.getElementById('fmt-nsx')?.classList.add('import-format-card--active'); document.getElementById('import-start-btn').addEventListener('click', async () => { const fileInput = document.getElementById('import-file-input'); const fmt = document.querySelector('input[name="import-fmt"]:checked')?.value; const btn = document.getElementById('import-start-btn'); const resultEl = document.getElementById('import-result'); if (!fileInput.files.length) { UI.toast('Bitte zuerst eine Datei auswählen.', 'warning'); return; } const file = fileInput.files[0]; const dogId = _appState.activeDog?.id; UI.setLoading(btn, true); resultEl.style.display = 'none'; try { const res = fmt === 'nsx' ? await API.importData.notestation(dogId, file) : await API.importData.csv(dogId, file); const errHtml = res.errors?.length ? `
${res.errors.length} Fehler anzeigen
${UI.escape(res.errors.join('\n'))}
` : ''; resultEl.innerHTML = `
${res.imported} Einträge importiert ${res.skipped ? ` · ${res.skipped} übersprungen` : ''} ${errHtml}
`; resultEl.style.display = 'block'; UI.setLoading(btn, false); // Diary neu laden falls etwas importiert wurde if (res.imported > 0) { _offset = 0; _entries = []; await _load(); _renderList(); } } catch (e) { resultEl.innerHTML = `
Fehler: ${UI.escape(e.message || String(e))}
`; resultEl.style.display = 'block'; UI.setLoading(btn, false); } }); } // ---------------------------------------------------------- // PUBLIC // ---------------------------------------------------------- function _cleanText(text) { if (!text) return text; return text .replace(/!\[([^\]]*)\]\([^\)]*\)/g, '') // Markdown-Bilder ![]() .replace(/\[([^\]]*)\]\([^\)]*\)/g, '$1') // Markdown-Links [text](url) → text .replace(/^\[\]\s*$/gm, '') // leere [] auf eigener Zeile .replace(/\n{3,}/g, '\n\n') // mehrfache Leerzeilen kürzen .trim(); } return { init, refresh, openNew, onDogChange, openDetail: _openDetail }; })();