import { ChatView } from './views/chat/chat-view.js?v=13'; import { db } from './db/database.js'; import { Clipboard } from '@capacitor/clipboard'; import { authService } from './services/auth-service.js'; import { syncManager } from './services/sync-service.js'; import { ttsService } from './services/tts-service.js'; import { appShortcutsService } from './services/app-shortcuts-service.js'; import { showVocabularyModal } from './views/vocabulary-modal.js'; import { TextToSpeech } from '@capacitor-community/text-to-speech'; // Handle PWA Service Worker if ('serviceWorker' in navigator) { if (window.Capacitor) { // IMPORTANT: If we are in the native Capacitor app, we MUST NOT use a Service Worker. // A Service Worker here would aggressively cache local files and prevent app updates! navigator.serviceWorker.getRegistrations().then(function(registrations) { for(let registration of registrations) { registration.unregister(); console.log('Successfully unregistered old PWA Service Worker in Capacitor'); } }); } else { // We are in a normal browser (e.g. HuggingFace). Register the PWA Service Worker. import('virtual:pwa-register').then(({ registerSW }) => { registerSW({ immediate: true }); }).catch(err => console.warn('PWA Registration failed', err)); } } // Handle App Shortcuts and Intents globally window.addEventListener('appShortcutAction', (e) => { if (e.detail && e.detail.shortcutId === 'add_vocabulary') { showVocabularyModal(); } }); window.ttsService = ttsService; window.TextToSpeech = TextToSpeech; window.appPrompt = function(message) { return new Promise(resolve => { const overlay = document.createElement('div'); overlay.className = 'custom-modal-overlay'; overlay.innerHTML = `

Eingabe

${message}

`; document.body.appendChild(overlay); const input = overlay.querySelector('#app-prompt-input'); const cancelBtn = overlay.querySelector('.cancel'); const confirmBtn = overlay.querySelector('.confirm'); input.focus(); const close = (val) => { input.blur(); overlay.classList.add('fade-out'); setTimeout(() => { overlay.remove(); resolve(val); }, 300); }; cancelBtn.onclick = () => close(null); confirmBtn.onclick = () => close(input.value.trim() ? input.value.trim() : null); input.onkeydown = (e) => { if (e.key === 'Enter') close(input.value.trim() ? input.value.trim() : null); if (e.key === 'Escape') close(null); }; }); }; window.appConfirm = function(message, confirmText = "Löschen", cancelText = "Abbrechen") { return new Promise(resolve => { const overlay = document.createElement('div'); overlay.className = 'custom-modal-overlay'; overlay.innerHTML = `

Bestätigung

${message}

`; document.body.appendChild(overlay); const cancelBtn = overlay.querySelector('.cancel'); const confirmBtn = overlay.querySelector('.confirm'); const close = (val) => { overlay.classList.add('fade-out'); setTimeout(() => { overlay.remove(); resolve(val); }, 300); }; cancelBtn.onclick = () => close(false); confirmBtn.onclick = () => close(true); }); }; window.copyToClipboard = async (text, btnElement) => { const showCheckmark = () => { if (!btnElement) return; const svg = btnElement.querySelector('svg'); if (!svg) return; const oldHtml = svg.outerHTML; svg.outerHTML = ''; setTimeout(() => { btnElement.innerHTML = oldHtml; }, 2000); }; const formatForNotes = (raw) => { if (!raw) return raw; // 1. Strip inline formatting and block markers let text = raw .replace(/\*\*(.*?)\*\*/g, '$1') .replace(/__(.*?)__/g, '$1') .replace(/\*(.*?)\*/g, '$1') .replace(/_(.*?)_/g, '$1') .replace(/~~(.*?)~~/g, '$1') .replace(/`(.*?)`/g, '$1') .replace(/\[(.*?)\]\(.*?\)/g, '$1') .replace(/^```[a-z]*\n/gm, '') .replace(/^```\s*$/gm, '') .replace(/^>\s+/gm, ''); const lines = text.split('\n'); const processedLines = []; let previousRealLineWasList = false; let emptyLinesSeen = 0; for (let i = 0; i < lines.length; i++) { let line = lines[i].trim(); if (line === '') { emptyLinesSeen++; continue; } const headerMatch = line.match(/^#+\s+(.*)$/); const listMatch = line.match(/^([\*\-]|\d+\.)\s+(.*)$/); if (headerMatch) { // Empty line before header if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') { processedLines.push(''); } processedLines.push(headerMatch[1]); // Empty line after header processedLines.push(''); previousRealLineWasList = false; emptyLinesSeen = 0; } else if (listMatch) { if (!previousRealLineWasList) { // Empty line before first list item if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') { processedLines.push(''); } } const bullet = (listMatch[1] === '*' || listMatch[1] === '-') ? '• ' : `${listMatch[1]} `; processedLines.push(`${bullet}${listMatch[2]}`); previousRealLineWasList = true; emptyLinesSeen = 0; } else { // Normal text if (previousRealLineWasList) { // Ensure empty line after list if (processedLines.length > 0 && processedLines[processedLines.length - 1] !== '') { processedLines.push(''); } } else if (emptyLinesSeen > 0 && processedLines.length > 0) { // Maintain paragraph breaks for text if (processedLines[processedLines.length - 1] !== '') { processedLines.push(''); } } processedLines.push(line); previousRealLineWasList = false; emptyLinesSeen = 0; } } return processedLines.join('\n').trim(); }; const formattedText = formatForNotes(text); try { await Clipboard.write({ string: formattedText }); showCheckmark(); } catch (e) { console.log('Capacitor Clipboard fallback:', e); // Legacy fallback for non-secure HTTP contexts try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(formattedText); } else { const textArea = document.createElement("textarea"); textArea.value = formattedText; textArea.style.position = "fixed"; textArea.style.left = "-999999px"; textArea.style.top = "-999999px"; document.body.appendChild(textArea); textArea.focus(); textArea.select(); document.execCommand('copy'); textArea.remove(); } showCheckmark(); } catch (err) { console.error('Copy failed:', err); } } }; const initApp = async () => { // FAST PATH: Check for overlay mode IMMEDIATELY, before any heavy initialization. // This cuts ~1-2 seconds off overlay startup by skipping auth, sync, etc. const isNative = window.Capacitor && typeof window.Capacitor.isNativePlatform === 'function' && window.Capacitor.isNativePlatform(); if (isNative) { const { QuickSettings } = window.Capacitor.Plugins; if (QuickSettings) { const intentResult = await QuickSettings.getPendingIntentAction(); if (intentResult && intentResult.overlay_mode === true) { // Force transparent on EVERY layer via cssText (highest inline priority) document.documentElement.style.cssText = 'background: transparent !important; background-color: transparent !important;'; document.body.style.cssText = 'background: transparent !important; background-color: transparent !important; margin: 0; padding: 0; visibility: visible !important;'; // Hide ALL non-modal elements const hideSelectors = ['#app', '.aurora-background', '#ambient-light', '#live-version-badge', 'svg[style*="pointer-events: none"]']; hideSelectors.forEach(sel => { const el = document.querySelector(sel); if (el) el.style.display = 'none'; }); window.isOverlayMode = true; await db.initPromise; showVocabularyModal(); // Signal native side to fade in the window (prevents black flash) QuickSettings.overlayReady(); return; // Early return — skip ALL heavy initialization } } } // NORMAL APP PATH: Full initialization await db.initPromise; await authService.initialize(); await syncManager.initialize(); await appShortcutsService.initialize(); // Load background style const bgStyle = db.getSetting('background_style') || 'standard'; document.body.setAttribute('data-bg-style', bgStyle); // Make body visible for normal app document.body.style.visibility = 'visible'; // Process any pending vocabulary from the Quick Settings native overlay const processOfflineVocabularyQueue = async () => { if (!isNative) return; try { const { QuickSettings } = window.Capacitor.Plugins; if (QuickSettings) { const { queue } = await QuickSettings.getPendingVocab(); if (queue && queue !== '[]') { const words = JSON.parse(queue); if (words.length > 0) { console.log("Processing offline vocabulary queue:", words); // Start background translation process setTimeout(async () => { const { aiRouter } = await import('./ai/router.js'); let addedCount = 0; for (const word of words) { try { const prompt = `Übersetze das folgende Wort oder den Satz. Wenn es Deutsch ist, übersetze es ins Englische. Wenn es Englisch ist, übersetze es ins Deutsche. Falls das Wort extrem falsch geschrieben ist (z.B. phonetisch nach Gehör geschrieben), erkenne das korrekte Wort automatisch und übersetze es. Das korrekte Wort soll in "front" stehen und die Übersetzung in "back". Zusätzlich generiere: - "explanation": 1-2 kurze Sätze in der Sprache der Übersetzung ('back'), die genau dieses Wort erklären. WICHTIG: Markiere das Lernwort (und seine Abwandlungen) IMMER fett mit HTML-Tags (z.B. Wort). - "example": Ein prägnanter Beispielsatz mit der Übersetzung ('back'). Das Lernwort MUSS auch hier mit ... fett markiert sein. - "imageQuery": Ein präziser englischer Suchbegriff für die Bing-Bildersuche. Das Bild muss EINDEUTIG zur Übersetzung passen. Füge IMMER 'single photo, clear focus, high quality' am Ende hinzu. Keine abstrakten Cartoons. Antworte AUSSCHLIESSLICH mit einem validen JSON-Objekt. Keine Markdown-Formatierung. Beispiel für "abanden": {"front": "abandon", "back": "verlassen", "explanation": "Jemanden oder etwas verlassen oder aufgeben.", "example": "Er musste das alte Auto verlassen.", "imageQuery": "abandoned old car single photo clear focus"} Zu übersetzen: "${word}"`; const response = await aiRouter.sendMessage(prompt, { model: db.getSetting('model') || 'gemini-1.5-flash' }); let jsonStr = response.trim(); if (jsonStr.startsWith('```json')) jsonStr = jsonStr.replace(/```json/g, '').replace(/```/g, '').trim(); else if (jsonStr.startsWith('```')) jsonStr = jsonStr.replace(/```/g, '').trim(); let parsed = null; try { parsed = JSON.parse(jsonStr); } catch (e) { console.warn("JSON parse failed, trying fallback...", jsonStr); parsed = { front: word, back: response.replace(/\{|\}/g, '').replace(/"/g, '').replace(/back:|front:|\\n/gi, '').trim(), explanation: "", example: "", imageQuery: encodeURIComponent(word) }; } if (parsed && parsed.back) { let decks = db.getDecks(); let schnelldeck = decks.find(d => d.title === 'Schnelleingabe' || d.title === 'Inbox'); if (!schnelldeck) schnelldeck = db.createDeck('Schnelleingabe', 'Automatisch gespeicherte Vokabeln aus der Schnelleingabe', '#8a53e6', 'Englisch', 'Deutsch'); let finalBack = parsed.back; if (parsed.explanation && parsed.example) { finalBack = `${parsed.back}\n\n**Erklärung:** ${parsed.explanation}\n\n**Beispiel:** ${parsed.example}`; } const searchTerms = encodeURIComponent(parsed.imageQuery || parsed.front); const imageUrl = `https://tse1.mm.bing.net/th?q=${searchTerms}&w=800&h=1000&c=7&rs=1`; db.addFlashcard(schnelldeck.id, parsed.front, finalBack, imageUrl); addedCount++; } } catch (e) { console.error("Failed to translate offline word:", word, e); } } await QuickSettings.clearPendingVocab(); if (addedCount > 0) { // Dispatch event so UI can refresh if user is on flashcards page window.dispatchEvent(new CustomEvent('flashcards-updated')); // Show a small toast notification const toast = document.createElement('div'); toast.style = "position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: rgba(52, 199, 89, 0.95); color: white; padding: 12px 24px; border-radius: 30px; font-weight: 600; font-size: 15px; z-index: 99999; box-shadow: 0 8px 24px rgba(0,0,0,0.3); animation: slide-down 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);"; toast.innerHTML = `✨ ${addedCount} Vokabel(n) hinzugefügt!`; document.body.appendChild(toast); setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.4s'; setTimeout(() => toast.remove(), 400); }, 4000); } }, 1000); // Wait 1s instead of 2s } } } } catch (e) { console.warn("Error reading pending vocab queue:", e); } }; const processEnrichmentQueue = async () => { // Only run if we're not in the tiny transparent overlay mode if (window.isOverlayMode) return; let pendingCards = db.getPendingCards(); if (!pendingCards || pendingCards.length === 0) return; if (!window.isEnriching) { window.isEnriching = true; try { const { aiRouter } = await import('./ai/router.js'); // Process sequentially for (const card of pendingCards) { const word = card.front; const pureTranslation = card.back.replace('', '').replace('', '').trim(); const prompt = `Erstelle eine kurze Erklärung und ein passendes Beispiel für diese Vokabelkarte, sowie einen Suchbegriff für ein Bild. Wort: "${word}" Übersetzung: "${pureTranslation}" WICHTIG: Prüfe, ob das "Wort" offensichtlich falsch geschrieben ist (z.B. phonetisch nach Gehör geschrieben). Falls es einen Tippfehler enthält, gib das richtig geschriebene Wort im Feld "correctedWord" zurück. Wenn es korrekt geschrieben ist, lass das Feld weg oder setze es auf null. Generiere: - "explanation": 1-2 kurze Sätze in der Sprache der Übersetzung, die genau dieses Wort erklären. WICHTIG: Markiere das Lernwort (und seine Abwandlungen) IMMER fett mit HTML-Tags (z.B. Wort). - "example": Ein prägnanter Beispielsatz mit der Übersetzung. Das Lernwort MUSS auch hier mit ... fett markiert sein. - "imageQuery": Ein präziser englischer Suchbegriff für die Bing-Bildersuche. Das Bild muss EINDEUTIG zur Übersetzung passen. Füge IMMER 'single photo, clear focus, high quality' am Ende hinzu. Keine abstrakten Cartoons. Antworte AUSSCHLIESSLICH mit einem validen JSON-Objekt. Keine Markdown-Formatierung. Beispiel für Tippfehler bei "abanden": {"correctedWord": "abandon", "explanation": "Jemanden oder etwas verlassen oder aufgeben.", "example": "Er musste das alte Auto verlassen.", "imageQuery": "abandoned old car single photo clear focus"}`; const response = await aiRouter.sendMessage(prompt, { model: db.getSetting('model') || 'gemini-1.5-flash', // Use standard model to ensure it doesn't fail disableTools: true // VERY IMPORTANT: Prevent AI from calling create_flashcards and duplicating the deck }); let jsonStr = response.trim(); if (jsonStr.startsWith('```json')) jsonStr = jsonStr.replace(/```json/g, '').replace(/```/g, '').trim(); else if (jsonStr.startsWith('```')) jsonStr = jsonStr.replace(/```/g, '').trim(); try { const parsed = JSON.parse(jsonStr); if (parsed.explanation && parsed.example) { const finalBack = `${pureTranslation}\n\n**Erklärung:** ${parsed.explanation}\n\n**Beispiel:** ${parsed.example}`; const searchTerms = encodeURIComponent(parsed.imageQuery || word); const imageUrl = `https://tse1.mm.bing.net/th?q=${searchTerms}&w=800&h=1000&c=7&rs=1`; // If the AI corrected a typo, use it. Otherwise use the original front. const finalFront = parsed.correctedWord ? parsed.correctedWord : card.front; db.editFlashcard(card.id, finalFront, finalBack, imageUrl); console.log(`Enriched card: ${word}`); } } catch (e) { console.warn("JSON parse failed for enrichment", jsonStr); } // Small pause between requests to avoid rate limits await new Promise(r => setTimeout(r, 500)); } // Dispatch event ONCE after all retroactive enrichment is done, to prevent UI scrolling spam window.dispatchEvent(new CustomEvent('flashcards-updated')); if (document.visibilityState === 'visible') { const toast = document.createElement('div'); toast.style = "position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: rgba(52, 199, 89, 0.95); color: white; padding: 12px 24px; border-radius: 30px; font-weight: 600; font-size: 15px; z-index: 99999; box-shadow: 0 8px 24px rgba(0,0,0,0.3); animation: slide-down 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);"; toast.innerHTML = `✨ Vokabel im Hintergrund geprüft und vervollständigt!`; document.body.appendChild(toast); setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.4s ease'; setTimeout(() => toast.remove(), 400); }, 3000); } } catch (e) { console.error("Enrichment queue failed", e); } finally { window.isEnriching = false; } } }; // Run on startup processOfflineVocabularyQueue(); processEnrichmentQueue(); // Check if we were launched with a native Intent (non-overlay) if (isNative) { const { QuickSettings } = window.Capacitor.Plugins; if (QuickSettings) { const intentResult = await QuickSettings.getPendingIntentAction(); if (intentResult && intentResult.action === 'add_vocabulary') { showVocabularyModal(); } } } // Run whenever the app resumes (comes to foreground) document.addEventListener("visibilitychange", async () => { if (document.visibilityState === 'visible') { processOfflineVocabularyQueue(); processEnrichmentQueue(); if (isNative) { const { QuickSettings } = window.Capacitor.Plugins; if (QuickSettings) { const intentResult = await QuickSettings.getPendingIntentAction(); if (intentResult && intentResult.overlay_mode === true) { document.body.style.background = 'transparent'; document.body.style.backgroundColor = 'transparent'; const appElement = document.getElementById('app'); if (appElement) appElement.style.display = 'none'; window.isOverlayMode = true; showVocabularyModal(); } else if (intentResult && intentResult.action === 'add_vocabulary') { showVocabularyModal(); } } } } }); // Scale up UI on web (HuggingFace) to match Capacitor native scale const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent); if (!isNative && isMobile) { document.documentElement.style.zoom = '1.15'; } console.log('SchoolMind AI initialized'); const appContainer = document.getElementById('app'); // Basic skeleton for the layout appContainer.innerHTML = `
`; // View Instances const chatView = new ChatView('router-view'); try { await chatView.init(); } catch (err) { console.error('Failed to initialize ChatView:', err); // Continue execution so tabs still work even if chat fails } window.chatView = chatView; // Export globally for IServ View to trigger PDF modal window.openPdfModal = chatView.openPdfModal ? chatView.openPdfModal.bind(chatView) : null; window.openArticleModal = chatView.openArticleModal ? chatView.openArticleModal.bind(chatView) : null; // We lazily import or instantiate SettingsView when needed, or just import it at top // To keep it simple, we'll instantiate it directly here but handle rendering in tab clicks. // --- TAB NAVIGATION LOGIC --- const tabItems = document.querySelectorAll('.tab-item'); const inputCapsule = document.querySelector('.input-capsule-container'); const routerView = document.getElementById('router-view'); let activeView = null; // Track the currently active view to destroy it when switching tabItems.forEach(tab => { tab.addEventListener('click', async () => { const tabName = tab.getAttribute('data-tab'); // Remove active class from all tabItems.forEach(t => t.classList.remove('active')); // Add active class to clicked tab.classList.add('active'); await window.openView(tabName); }); }); const handleImportError = (e) => { if (e.message && e.message.includes('Failed to fetch dynamically imported module')) { // The app was updated and the old chunks are gone from the server. // Force a reload to fetch the new index.html and its new chunk map. routerView.innerHTML = `
🔄
App wurde aktualisiert
Die neuste Version wird geladen...
`; setTimeout(() => { window.location.reload(true); }, 1000); } else { routerView.innerHTML = `
Error: ${e.message}
`; } }; let currentOpenViewCounter = 0; window.openView = async (viewName, isSubView = false) => { currentOpenViewCounter++; const myCounter = currentOpenViewCounter; // Cleanup the previous view if (activeView && typeof activeView.destroy === 'function') { activeView.destroy(); } // Safety fallback: always ensure chat is destroyed if we navigate away if (viewName !== 'Chat' && window.chatView) { window.chatView.destroy(); } activeView = null; document.body.classList.toggle('in-chat-view', viewName === 'Chat'); document.body.classList.toggle('in-hub-view', viewName === 'Hub'); document.body.classList.toggle('in-news-view', viewName === 'News'); document.body.classList.toggle('in-vault-view', viewName === 'Vault'); routerView.classList.remove('view-enter-anim'); routerView.classList.add('view-exit-anim'); await new Promise(resolve => setTimeout(resolve, 150)); // Abort if another view was opened while we were waiting if (currentOpenViewCounter !== myCounter) return; routerView.innerHTML = ''; // Reset scroll position when switching main tabs if (!isSubView) { routerView.scrollTop = 0; } if (viewName === 'Chat') { inputCapsule.style.display = 'block'; try { chatView.render(); chatView.loadMessages(); } catch(e) { handleImportError(e); } activeView = chatView; } else if (viewName === 'Settings') { inputCapsule.style.display = 'none'; try { const { SettingsView } = await import('./views/settings/settings-view.js'); const settingsView = new SettingsView('router-view'); settingsView.init(); activeView = settingsView; } catch (e) { handleImportError(e); } } else if (viewName === 'Vault') { inputCapsule.style.display = 'none'; try { const { DocumentsView } = await import('./views/documents/documents-view.js'); const docsView = new DocumentsView('router-view'); await docsView.init(); activeView = docsView; } catch (e) { handleImportError(e); } } else if (viewName === 'Hub') { inputCapsule.style.display = 'none'; try { const { HubView } = await import('./views/hub/hub-view.js'); const hubView = new HubView('router-view'); await hubView.init(); activeView = hubView; } catch (e) { handleImportError(e); } } else if (viewName === 'News') { inputCapsule.style.display = 'none'; try { const { NewsView } = await import('./views/news/news-view.js'); const newsView = new NewsView('router-view'); await newsView.init(); activeView = newsView; } catch (e) { handleImportError(e); } } // Sub-views that can be opened from the Hub else if (viewName === 'Lernen') { inputCapsule.style.display = 'none'; try { const { LearnView } = await import('./views/learn/learn-view.js'); const learnView = new LearnView('router-view'); await learnView.init(); learnView.render(); window.learnView = learnView; activeView = learnView; } catch (e) { handleImportError(e); } } else if (viewName === 'Scan') { inputCapsule.style.display = 'none'; try { const { ScanView } = await import('./views/scan/scan-view.js'); const scanView = new ScanView('router-view'); await scanView.init(); scanView.render(); activeView = scanView; } catch (e) { handleImportError(e); } } else if (viewName === 'Kalender') { inputCapsule.style.display = 'none'; try { const { CalendarView } = await import('./views/calendar/calendar-view.js'); const calView = new CalendarView('router-view'); await calView.init(); activeView = calView; } catch (e) { handleImportError(e); } } else if (viewName === 'IServ') { inputCapsule.style.display = 'none'; try { const { IServView } = await import('./views/iserv/iserv-view.js'); const iservView = new IServView('router-view'); await iservView.init(); activeView = iservView; } catch (e) { handleImportError(e); } } routerView.classList.remove('view-exit-anim'); routerView.classList.add('view-enter-anim'); }; // Helper for Hub to open subviews without changing the active tab highlight window.openHubSubView = (viewName) => { window.openView(viewName, true); }; // --- CHAT LOGIC --- const textarea = document.getElementById('chat-input'); textarea.addEventListener('input', function() { this.style.height = 'auto'; this.style.height = (this.scrollHeight < 120 ? this.scrollHeight : 120) + 'px'; }); // --- PLUS MENU & IMAGE UPLOAD LOGIC --- const plusMenuBtn = document.getElementById('plus-menu-btn'); const plusPopoverMenu = document.getElementById('plus-popover-menu'); const menuAttachBtn = document.getElementById('menu-attach-image-btn'); const fileInput = document.getElementById('image-upload-input'); const previewContainer = document.getElementById('image-preview-container'); window.currentAttachments = []; // Max 20 function renderAttachments() { previewContainer.innerHTML = ''; if (window.currentAttachments.length === 0) { previewContainer.style.display = 'none'; return; } previewContainer.style.display = 'flex'; window.currentAttachments.forEach((att, index) => { const itemWrapper = document.createElement('div'); itemWrapper.className = 'gpu-accelerated'; itemWrapper.style = 'position: relative; display: inline-flex; align-items: center; justify-content: center; padding: 6px; background: rgba(255,255,255,0.03); border-radius: 14px; border: 1px solid rgba(255,255,255,0.08); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); box-shadow: 0 8px 32px rgba(0,0,0,0.2); width: 80px; height: 80px; flex-shrink: 0;'; if (att.mimeType === 'application/pdf') { itemWrapper.innerHTML = `
${att.name}
`; } else { itemWrapper.innerHTML = ` `; } const delBtn = document.createElement('button'); delBtn.style = 'position: absolute; top: -6px; right: -6px; background: rgba(40,40,45,0.9); color: #fff; border: 1px solid rgba(255,255,255,0.15); border-radius: 50%; width: 22px; height: 22px; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 10px; padding: 0; box-shadow: 0 4px 12px rgba(0,0,0,0.4); z-index: 2;'; delBtn.innerHTML = '✕'; delBtn.onclick = () => { window.currentAttachments.splice(index, 1); renderAttachments(); }; itemWrapper.appendChild(delBtn); previewContainer.appendChild(itemWrapper); }); } // Toggle plus menu if (plusMenuBtn && plusPopoverMenu) { plusMenuBtn.addEventListener('click', (e) => { e.stopPropagation(); const isVisible = plusPopoverMenu.style.display === 'flex'; plusPopoverMenu.style.display = isVisible ? 'none' : 'flex'; }); // Close when clicking outside document.addEventListener('click', (e) => { if (!plusPopoverMenu.contains(e.target) && !plusMenuBtn.contains(e.target)) { plusPopoverMenu.style.display = 'none'; } }); document.body.addEventListener('change', (e) => { if (e.target.id === 'deep-research-toggle') { const container = document.getElementById('deep-research-time-container'); if(container) container.style.display = e.target.checked ? 'block' : 'none'; const detectiveContainer = document.getElementById('detective-board-container'); if(detectiveContainer) detectiveContainer.style.display = e.target.checked ? 'flex' : 'none'; } }); } if (menuAttachBtn) { menuAttachBtn.addEventListener('click', () => { if (plusPopoverMenu) plusPopoverMenu.style.display = 'none'; fileInput.click(); }); } function handleImageFile(file) { if (!file || !file.type.startsWith('image/')) return; if (window.currentAttachments.length >= 20) { alert("Maximal 20 Anhänge erlaubt."); return; } const reader = new FileReader(); reader.onload = (event) => { const img = new Image(); img.onload = () => { const canvas = document.createElement('canvas'); const MAX_DIM = 800; let width = img.width; let height = img.height; if (width > height && width > MAX_DIM) { height *= MAX_DIM / width; width = MAX_DIM; } else if (height > MAX_DIM) { width *= MAX_DIM / height; height = MAX_DIM; } canvas.width = width; canvas.height = height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, width, height); const dataUrl = canvas.toDataURL('image/jpeg', 0.7); window.currentAttachments.push({ mimeType: 'image/jpeg', data: dataUrl, name: file.name }); renderAttachments(); }; img.src = event.target.result; }; reader.readAsDataURL(file); } async function handlePdfFile(file) { if (window.currentAttachments.length >= 20) { alert("Maximal 20 Anhänge erlaubt."); return; } const reader = new FileReader(); reader.onload = (event) => { window.currentAttachments.push({ mimeType: 'application/pdf', data: event.target.result, name: file.name }); renderAttachments(); }; reader.readAsDataURL(file); } function clearImage() { window.currentAttachments = []; renderAttachments(); fileInput.value = ''; window.updateChatPlaceholder(); } // Handle global errors gracefully window.addEventListener('unhandledrejection', event => { console.error('Unhandled promise rejection:', event.reason); }); // --- File Permission UI Logic --- let activePermissionResolve = null; const permPopup = document.getElementById('file-permission-popup'); const permText = document.getElementById('file-permission-text'); const permAllow = document.getElementById('file-permission-allow'); const permDeny = document.getElementById('file-permission-deny'); window.addEventListener('request-file-permission', (e) => { const detail = e.detail; activePermissionResolve = detail.resolve; let actionText = 'lesen'; if (detail.action === 'write') actionText = 'erstellen/überschreiben'; if (detail.action === 'delete') actionText = 'löschen'; permText.innerText = `Die KI möchte die Datei "${detail.path}" ${actionText}.`; permPopup.style.display = 'flex'; // Haptic feedback to alert user if (window.navigator && window.navigator.vibrate) { window.navigator.vibrate(50); } }); const closePermissionPopup = (allowed) => { permPopup.style.display = 'none'; if (activePermissionResolve) { activePermissionResolve(allowed); activePermissionResolve = null; } }; permAllow.addEventListener('click', () => closePermissionPopup(true)); permDeny.addEventListener('click', () => closePermissionPopup(false)); fileInput.addEventListener('change', (e) => { const files = Array.from(e.target.files); if (!files.length) return; files.forEach(file => { if (file.type === 'application/pdf') { handlePdfFile(file); } else { handleImageFile(file); } }); // Clear the input so selecting the same files again works fileInput.value = ''; }); // Global Paste Event Listener for Images document.addEventListener('paste', (e) => { const items = (e.clipboardData || e.originalEvent.clipboardData).items; for (let index in items) { const item = items[index]; if (item.kind === 'file') { const file = item.getAsFile(); if (file) { if (file.type === 'application/pdf') { e.preventDefault(); handlePdfFile(file); break; } else if (file.type.includes('image')) { e.preventDefault(); handleImageFile(file); break; } } } } }); // Handle Sending const sendBtn = document.getElementById('send-btn'); const handleSend = async () => { if (chatView && chatView.isGenerating) { if (chatView.currentAbortController) { chatView.currentAbortController.abort(); } return; } const text = textarea.value; const hasAttachments = window.currentAttachments && window.currentAttachments.length > 0; if (text.trim() || hasAttachments) { // Send button spin animation sendBtn.classList.add('sending'); setTimeout(() => sendBtn.classList.remove('sending'), 600); textarea.value = ''; textarea.style.height = 'auto'; let finalMessage = text.trim(); if (hasAttachments) { let attachStr = ''; window.currentAttachments.forEach(att => { attachStr += `![${att.name}](${att.data})\n`; }); finalMessage = `${attachStr}\n${finalMessage}`; clearImage(); } // Check for API Key if using cloud models const currentModel = db.getSetting('model') || 'gemini-1.5-flash'; if (currentModel.startsWith('gemini') && !db.getSetting('gemini_api_key')) { const key = await window.appPrompt("Bitte gib deinen Gemini API Key ein (wird lokal gespeichert):"); if (key) db.setSetting('gemini_api_key', key.trim()); else return; } else if (currentModel.startsWith('groq') && !db.getSetting('groq_api_key')) { const key = await window.appPrompt("Bitte gib deinen Groq API Key ein (wird lokal gespeichert):"); if (key) db.setSetting('groq_api_key', key.trim()); else return; } else if (currentModel.startsWith('openrouter') && !db.getSetting('openrouter_api_key')) { const key = await window.appPrompt("Bitte gib deinen OpenRouter API Key ein (wird lokal gespeichert):"); if (key) db.setSetting('openrouter_api_key', key.trim()); else return; } else if (currentModel.startsWith('deepseek') && !db.getSetting('deepseek_api_key')) { const key = await window.appPrompt("Bitte gib deinen DeepSeek API Key ein (wird lokal gespeichert):"); if (key) db.setSetting('deepseek_api_key', key.trim()); else return; } chatView.handleSend(finalMessage); // Auto-collapse in PDF mode after sending if (document.body.classList.contains('pdf-reading-mode')) { document.body.classList.add('pdf-input-collapsed'); } } }; sendBtn.addEventListener('click', handleSend); textarea.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); handleSend(); } }); window.updateChatPlaceholder = function() { try { const model = db.getSetting('model') || 'gemini-1.5-flash'; let aiName = "SchoolMind AI"; let isLocal = false; if (model.includes('gemini') || model.includes('Gemini')) aiName = "Gemini"; else if (model.includes('claude') || model.includes('Claude')) aiName = "Claude"; else if (model.includes('qwen') || model.includes('Qwen')) aiName = "Qwen"; else if (model.includes('llama') || model.includes('Llama')) aiName = "Llama"; else if (model.includes('lyria') || model.includes('Lyria')) aiName = "Lyria"; else if (model.includes('gemma') || model.includes('Gemma')) aiName = "Gemma"; else if (model.includes('deepseek') || model.includes('DeepSeek')) aiName = "DeepSeek"; else if (model.includes('mistral') || model.includes('codestral')) aiName = "Mistral"; if (model.startsWith('ollama-') || model.includes('nano-')) isLocal = true; let userName = ""; const useProfileStr = db.getSetting('use_profile'); const useProfile = useProfileStr === null ? true : useProfileStr === 'true'; if (useProfile) { try { const activeProfileRes = db.getActiveProfile(); if (activeProfileRes && activeProfileRes.length > 0 && activeProfileRes[0].values.length > 0) { const row = activeProfileRes[0].values[0]; const nameIndex = activeProfileRes[0].columns.indexOf('name'); if (nameIndex !== -1 && row[nameIndex]) { userName = row[nameIndex]; } } } catch (profileErr) { console.warn("Profile fetch error:", profileErr); } } let placeholder = `Nachricht an ${aiName}...`; if (userName) { placeholder = `Als ${userName} an ${aiName}...`; } if (isLocal) { placeholder = `(Lokal) ` + placeholder; } const chatInput = document.getElementById('chat-input'); if (chatInput) { chatInput.placeholder = placeholder; } } catch (e) { const chatInput = document.getElementById('chat-input'); if (chatInput) { if (e.message.includes('not ready')) { chatInput.placeholder = "Warte auf Datenbank..."; } else { chatInput.placeholder = "ERROR: " + e.message; } } } }; // Wait for DB to be ready before first update db.initPromise.then(() => window.updateChatPlaceholder()); // --- Scroll to Bottom Button Logic --- const routerViewEl = document.getElementById('router-view'); const scrollBtn = document.getElementById('scroll-to-bottom-btn'); routerViewEl.addEventListener('scroll', (e) => { // Only show in chat view if (document.body.classList.contains('in-chat-view')) { const scrollContainer = document.getElementById('chat-scroll-area') || routerViewEl; if (e.target !== scrollContainer && e.target !== routerViewEl) return; const scrollHeight = scrollContainer.scrollHeight; const scrollTop = scrollContainer.scrollTop; const clientHeight = scrollContainer.clientHeight; // If user scrolled up by more than 80 lines (ca. 1000px) if (scrollHeight - scrollTop - clientHeight > 1000) { scrollBtn.style.display = 'flex'; setTimeout(() => scrollBtn.style.opacity = '1', 10); } else { scrollBtn.style.opacity = '0'; setTimeout(() => { if (scrollBtn.style.opacity === '0') scrollBtn.style.display = 'none'; }, 200); } } else { scrollBtn.style.display = 'none'; } }, true); scrollBtn.addEventListener('click', () => { const scrollContainer = document.getElementById('chat-scroll-area') || routerViewEl; scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior: 'smooth' }); }); window.setGeneratingState = (isGen) => { const icon = document.getElementById('scroll-arrow-icon'); const ind = document.getElementById('scroll-typing-indicator'); if (icon && ind) { if (isGen) { icon.style.display = 'none'; ind.style.display = 'flex'; } else { icon.style.display = 'block'; ind.style.display = 'none'; } } }; // Extract and Wrap Words Helper for TTS window.extractAndWrapText = (element) => { // If already wrapped, just return the text if (element.hasAttribute('data-words-wrapped')) { return element.getAttribute('data-words-wrapped-text'); } const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false); const nodes = []; while (walker.nextNode()) nodes.push(walker.currentNode); let wordIndex = 0; let fullTextParts = []; nodes.forEach(node => { if (node.nodeValue.trim() === '') { fullTextParts.push(node.nodeValue); return; } const parts = node.nodeValue.split(/(\s+)/); const fragment = document.createDocumentFragment(); parts.forEach(part => { if (part.trim().length > 0) { const span = document.createElement('span'); span.className = 'tts-word'; span.dataset.ttsIndex = wordIndex++; span.textContent = part; fragment.appendChild(span); fullTextParts.push(part); } else { fragment.appendChild(document.createTextNode(part)); fullTextParts.push(part); } }); node.parentNode.replaceChild(fragment, node); }); const finalString = fullTextParts.join(''); element.setAttribute('data-words-wrapped', wordIndex); element.setAttribute('data-words-wrapped-text', finalString); return finalString; }; // Play TTS Message from a DOM Element window.playTTSMessage = (btn, rawText) => { // The button is inside .ai-msg-actions, which is a sibling of .chat-bubble-ai const actionsDiv = btn.closest('.ai-msg-actions'); const wrapper = actionsDiv ? actionsDiv.parentElement : null; const container = wrapper ? wrapper.querySelector('.chat-bubble-ai') : null; if (container) { const textToPlay = window.extractAndWrapText(container); window.ttsService.play(textToPlay, true); } else { window.ttsService.play(rawText, false); } }; // --- TTS Player Logic --- const ttsPlayer = document.getElementById('tts-player-container'); const ttsPlayBtn = document.getElementById('tts-play-btn'); const ttsPlayIcon = document.getElementById('tts-play-icon'); const ttsPrevBtn = document.getElementById('tts-prev-btn'); const ttsNextBtn = document.getElementById('tts-next-btn'); const ttsRateBtn = document.getElementById('tts-rate-btn'); const ttsCcBtn = document.getElementById('tts-cc-btn'); let ttsCcEnabled = true; if (ttsPlayer) { // CC Button logic ttsCcBtn.addEventListener('click', () => { ttsCcEnabled = !ttsCcEnabled; if (ttsCcEnabled) { ttsCcBtn.classList.add('active'); ttsCcBtn.style.color = 'var(--primary)'; } else { ttsCcBtn.classList.remove('active'); ttsCcBtn.style.color = 'var(--text-secondary)'; // Remove active highlights document.querySelectorAll('.tts-word.active').forEach(el => { el.classList.remove('active'); el.style.background = 'transparent'; el.style.color = 'inherit'; }); } }); ttsService.onStateChange = (state) => { const scrollBtn = document.getElementById('scroll-to-bottom-btn'); // Update word highlights based on progress if (ttsCcEnabled && state.currentWordIndex !== undefined) { document.querySelectorAll('.tts-word.active').forEach(el => el.classList.remove('active')); const activeWord = document.querySelector(`.tts-word[data-tts-index="${state.currentWordIndex}"]`); if (activeWord) { activeWord.classList.add('active'); if (!window.ttsScrollTimeout) { window.ttsScrollTimeout = setTimeout(() => { const scrollContainer = activeWord.closest('#chat-scroll-area') || activeWord.closest('.view-container'); if (scrollContainer) { const containerRect = scrollContainer.getBoundingClientRect(); const wordRect = activeWord.getBoundingClientRect(); const isOutsideMiddle = wordRect.top < containerRect.top + containerRect.height * 0.3 || wordRect.bottom > containerRect.bottom - containerRect.height * 0.3; if (isOutsideMiddle) { const scrollOffset = wordRect.top - containerRect.top + scrollContainer.scrollTop - (containerRect.height / 2); scrollContainer.scrollTo({ top: scrollOffset, behavior: 'smooth' }); } } window.ttsScrollTimeout = null; }, 300); // Small debounce to prevent jitter } } } if (state.hasActiveSession) { ttsPlayer.classList.remove('collapsed'); if (scrollBtn) scrollBtn.style.top = '-130px'; } else { ttsPlayer.classList.add('collapsed'); if (scrollBtn) scrollBtn.style.top = '-46px'; } if (state.isLoading) { ttsPlayer.classList.add('playing'); ttsPlayIcon.innerHTML = ''; ttsPlayBtn.style.opacity = '0.5'; } else if (state.isPlaying) { ttsPlayer.classList.add('playing'); ttsPlayIcon.innerHTML = ''; ttsPlayBtn.style.opacity = '1'; } else { ttsPlayer.classList.remove('playing'); ttsPlayIcon.innerHTML = ''; ttsPlayBtn.style.opacity = '1'; } ttsRateBtn.innerText = state.rate + 'x'; }; ttsPlayBtn.addEventListener('click', () => ttsService.togglePlayPause()); ttsPrevBtn.addEventListener('click', () => ttsService.prev()); ttsNextBtn.addEventListener('click', () => ttsService.next()); ttsRateBtn.addEventListener('click', () => ttsService.cycleRate()); // Swipe down to close let touchStartY = 0; let touchEndY = 0; ttsPlayer.addEventListener('touchstart', (e) => { touchStartY = e.touches[0].clientY; touchEndY = touchStartY; ttsPlayer.style.transition = 'none'; // Instant drag }); ttsPlayer.addEventListener('touchmove', (e) => { touchEndY = e.touches[0].clientY; const deltaY = touchEndY - touchStartY; if (deltaY > 0) { ttsPlayer.style.transform = `translateY(${deltaY}px)`; // Smoothly fade out as it reaches the 70px threshold const dragOpacity = Math.max(0, 1 - (deltaY / 70)); ttsPlayer.style.opacity = dragOpacity; } }); ttsPlayer.addEventListener('touchend', () => { ttsPlayer.style.transition = ''; // Restore CSS transition ttsPlayer.style.transform = ''; // Restore CSS transform ttsPlayer.style.opacity = ''; // Restore CSS opacity if (touchEndY > touchStartY + 70) { // Swiped down deliberately ttsService.stop(); } }); } }; document.addEventListener('DOMContentLoaded', () => { initApp().catch(err => { console.error("Critical app initialization error:", err); if (err && err.message && err.message.includes('no such table')) { alert("Die lokale Datenbank ist beschädigt. Sie wird nun zurückgesetzt, um die App wiederherzustellen."); localStorage.removeItem('schoolmind_db'); window.location.reload(); } }); // Also catch if it was launched directly and stored in window if (window.pendingAppShortcut === 'add_vocabulary') { showVocabularyModal(); window.pendingAppShortcut = null; } });