Spaces:
Sleeping

arkanum / frontend /index.html
benny4982's picture
Claude Opus 4.6
Auto-set version from git commit hash on each deploy
3e2ead7
Raw History Blame
63 kB
<!DOCTYPE html> <html lang="de"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="mobile-web-app-capable" content="yes"> <title>Arkanum – Regelexperte</title> <link rel="manifest" href="manifest.json"> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"> <meta name="theme-color" content="#1a1a2e"> <style> :root { --bg: #1a1a2e; --surface: #16213e; --primary: #e94560; --accent: #f5a623; --text: #eee; --text-muted: #999; --border: #333; --success: #4caf50; } * { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg); color: var(--text); min-height: 100dvh; display: flex; flex-direction: column; padding-left: env(safe-area-inset-left); padding-right: env(safe-area-inset-right); } header { background: var(--surface); padding: 1rem; padding-top: max(1rem, env(safe-area-inset-top)); text-align: center; border-bottom: 2px solid var(--primary); } header h1 { font-size: 1.4rem; letter-spacing: 2px; } header h1 span { color: var(--primary); } header p { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.25rem; } /* Mode Toggle */ .mode-toggle { display: flex; justify-content: center; gap: 0; margin-top: 0.5rem; } .mode-toggle button { background: transparent; border: 1px solid var(--border); color: var(--text-muted); padding: 0.6rem 1rem; min-height: 44px; font-size: 0.75rem; cursor: pointer; transition: all 0.2s; } .mode-toggle button:first-child { border-radius: 6px 0 0 6px; } .mode-toggle button:last-child { border-radius: 0 6px 6px 0; } .mode-toggle button.active { background: var(--primary); border-color: var(--primary); color: white; } .app-version { font-size: 0.65rem; color: var(--text-muted); margin-top: 0.25rem; opacity: 0.6; } main { flex: 1; padding: 1rem; max-width: 700px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; gap: 1rem; } /* ---- Chat Mode ---- */ .chat-area { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 0.75rem; padding-bottom: 1rem; } .message { padding: 0.75rem 1rem; border-radius: 12px; max-width: 90%; line-height: 1.5; font-size: 0.95rem; } .message.user { background: var(--primary); align-self: flex-end; border-bottom-right-radius: 4px; } .message.assistant { background: var(--surface); align-self: flex-start; border-bottom-left-radius: 4px; border: 1px solid var(--border); } .message.assistant h2 { font-size: 1rem; color: var(--accent); margin: 0.5rem 0 0.25rem; } .message.assistant h2:first-child { margin-top: 0; } .message.assistant p { margin: 0.25rem 0; } .message.assistant ul, .message.assistant ol { margin: 0.25rem 0 0.25rem 1.25rem; } .message.assistant strong { color: var(--accent); } .message .image-preview { max-width: 200px; max-height: 150px; border-radius: 8px; margin-bottom: 0.5rem; display: block; } .message .sources { margin-top: 0.5rem; padding-top: 0.5rem; border-top: 1px solid var(--border); font-size: 0.8rem; color: var(--text-muted); } .message .situation { font-style: italic; color: var(--text-muted); margin-bottom: 0.5rem; font-size: 0.85rem; } .input-area { background: var(--surface); border-radius: 16px; padding: 0.75rem; padding-bottom: max(0.75rem, env(safe-area-inset-bottom)); border: 1px solid var(--border); } .image-preview-bar { display: none; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; padding-bottom: 0.5rem; border-bottom: 1px solid var(--border); } .image-preview-bar.active { display: flex; } .image-preview-bar img { width: 48px; height: 48px; object-fit: cover; border-radius: 8px; } .image-preview-bar .remove { background: none; border: none; color: var(--primary); font-size: 1.2rem; cursor: pointer; margin-left: auto; min-width: 44px; min-height: 44px; display: flex; align-items: center; justify-content: center; } .input-row { display: flex; gap: 0.5rem; align-items: flex-end; } .input-row textarea { flex: 1; background: transparent; border: none; color: var(--text); font-size: 1rem; font-family: inherit; resize: none; outline: none; max-height: 120px; line-height: 1.4; } .btn { width: 44px; height: 44px; border-radius: 50%; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; font-size: 1.2rem; } .btn-camera { background: var(--surface); border: 1px solid var(--border); color: var(--text); } .btn-send { background: var(--primary); color: white; } .btn:disabled { opacity: 0.4; cursor: not-allowed; } .loading { display: inline-flex; gap: 4px; padding: 0.5rem 0; } .loading span { width: 8px; height: 8px; background: var(--accent); border-radius: 50%; animation: bounce 1.2s infinite ease-in-out; } .loading span:nth-child(2) { animation-delay: 0.2s; } .loading span:nth-child(3) { animation-delay: 0.4s; } @keyframes bounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } } .welcome { text-align: center; color: var(--text-muted); margin-top: 2rem; } .welcome h2 { color: var(--accent); font-size: 1.1rem; margin-bottom: 0.5rem; } .examples { display: flex; flex-direction: column; gap: 0.5rem; margin-top: 1rem; } .example-btn { background: var(--surface); border: 1px solid var(--border); color: var(--text); padding: 0.75rem 1rem; border-radius: 10px; cursor: pointer; font-size: 0.85rem; text-align: left; min-height: 44px; } .example-btn:hover { border-color: var(--primary); } input[type="file"] { display: none; } /* Login Screen */ .login-overlay { position: fixed; inset: 0; background: var(--bg); display: flex; align-items: center; justify-content: center; z-index: 100; } .login-overlay.hidden { display: none; } .login-box { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 2rem; text-align: center; max-width: 320px; width: 90%; } .login-box h2 { color: var(--primary); font-size: 1.4rem; letter-spacing: 2px; margin-bottom: 0.5rem; } .login-box p { color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.5rem; } .login-box input { width: 100%; padding: 0.75rem 1rem; background: var(--bg); border: 1px solid var(--border); border-radius: 10px; color: var(--text); font-size: 1rem; outline: none; margin-bottom: 1rem; } .login-box input:focus { border-color: var(--primary); } .login-box button { width: 100%; padding: 0.75rem; background: var(--primary); color: white; border: none; border-radius: 10px; font-size: 1rem; cursor: pointer; } .login-error { color: var(--primary); font-size: 0.85rem; margin-top: 0.5rem; display: none; } /* ---- Voice Guide Mode ---- */ .voice-guide { display: none; flex-direction: column; flex: 1; gap: 1rem; } .voice-guide.active { display: flex; } .chat-mode.hidden { display: none; } /* Mode Selection */ .mode-select { display: flex; flex-direction: column; align-items: center; gap: 1rem; margin-top: 2rem; text-align: center; } .mode-select h2 { color: var(--accent); font-size: 1.1rem; } .mode-select p { color: var(--text-muted); font-size: 0.85rem; } .mode-select-buttons { display: flex; gap: 0.75rem; flex-wrap: wrap; justify-content: center; } .mode-select-btn { background: var(--surface); border: 2px solid var(--border); color: var(--text); padding: 1rem 1.5rem; border-radius: 12px; cursor: pointer; font-size: 0.95rem; min-width: 160px; transition: border-color 0.2s; } .mode-select-btn:hover { border-color: var(--primary); } .mode-select-btn strong { display: block; color: var(--accent); margin-bottom: 0.25rem; } .mode-select-btn span { font-size: 0.8rem; color: var(--text-muted); } /* Progress Bar */ .vg-progress { background: var(--surface); border-radius: 12px; padding: 0.75rem 1rem; border: 1px solid var(--border); } .vg-progress-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; } .vg-progress-title { font-size: 0.85rem; color: var(--accent); font-weight: 600; } .vg-progress-count { font-size: 0.75rem; color: var(--text-muted); } .vg-progress-bar { height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; } .vg-progress-fill { height: 100%; background: var(--accent); border-radius: 2px; transition: width 0.3s ease; } .vg-phase-dots { display: flex; gap: 0.5rem; margin-top: 0.5rem; justify-content: center; } .vg-phase-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--border); transition: background 0.2s; } .vg-phase-dot.done { background: var(--success); } .vg-phase-dot.current { background: var(--accent); } /* Step Card */ .vg-step-card { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 1.25rem; flex: 1; overflow-y: auto; -webkit-overflow-scrolling: touch; line-height: 1.6; font-size: 0.95rem; } .vg-step-card .vg-step-text { white-space: pre-wrap; } .vg-step-card .sources { margin-top: 0.75rem; padding-top: 0.5rem; border-top: 1px solid var(--border); font-size: 0.8rem; color: var(--text-muted); } /* Voice Controls */ /* Audio controls: rewind, play/pause, mic */ .vg-audio-controls { display: flex; gap: 0.75rem; align-items: center; justify-content: center; } .vg-audio-btn { width: 48px; height: 48px; border-radius: 50%; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-size: 1.3rem; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.2s; padding: 0; } .vg-audio-btn:hover { border-color: var(--primary); } .vg-audio-btn:disabled { opacity: 0.4; cursor: not-allowed; } .vg-audio-btn.play-pause { width: 56px; height: 56px; font-size: 1.5rem; background: var(--primary); border-color: var(--primary); color: white; } .vg-audio-btn.play-pause:hover { background: #d63a52; } .vg-audio-btn.mic.listening { background: var(--primary); border-color: var(--primary); color: white; animation: pulse 1.5s infinite; } /* Navigation controls with inline input */ .vg-nav-controls { display: flex; gap: 0.5rem; align-items: center; } .vg-btn { padding: 0.6rem 1.2rem; border-radius: 10px; border: 1px solid var(--border); background: var(--surface); color: var(--text); font-size: 0.9rem; cursor: pointer; display: flex; align-items: center; gap: 0.4rem; transition: all 0.2s; } .vg-btn:hover { border-color: var(--primary); } .vg-btn:disabled { opacity: 0.4; cursor: not-allowed; } .vg-btn.primary { background: var(--primary); border-color: var(--primary); color: white; } .vg-btn.primary:hover { background: #d63a52; } @keyframes pulse { 0%, 100% { box-shadow: 0 0 0 0 rgba(233, 69, 96, 0.4); } 50% { box-shadow: 0 0 0 12px rgba(233, 69, 96, 0); } } .vg-status { text-align: center; font-size: 0.8rem; color: var(--text-muted); min-height: 1.2rem; } /* Question input modal */ .vg-question-modal { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.7); display: flex; align-items: flex-start; justify-content: center; z-index: 80; padding: 1rem; padding-top: max(4rem, env(safe-area-inset-top)); } .vg-question-modal.hidden { display: none; } .vg-question-modal-content { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 1rem; max-width: 500px; width: 100%; } .vg-question-modal-content .vg-question-input-row { display: flex; gap: 0.5rem; align-items: center; } .vg-question-modal-content input { flex: 1; background: var(--bg); border: 1px solid var(--border); border-radius: 10px; color: var(--text); font-size: 1rem; outline: none; padding: 0.75rem; } .vg-question-modal-content input:focus { border-color: var(--primary); } /* Voice Guide Question Modal */ .vg-modal { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.7); display: flex; align-items: center; justify-content: center; z-index: 90; padding: 1rem; padding-top: max(1rem, env(safe-area-inset-top)); padding-bottom: max(1rem, env(safe-area-inset-bottom)); } .vg-modal.hidden { display: none; } .vg-modal-content { background: var(--surface); border: 1px solid var(--border); border-radius: 16px; padding: 1.25rem; max-width: 600px; width: 100%; max-height: 80vh; display: flex; flex-direction: column; line-height: 1.6; font-size: 0.95rem; } .vg-modal-content #vgModalBody { overflow-y: auto; -webkit-overflow-scrolling: touch; flex: 1; min-height: 0; } .vg-modal-content .vg-modal-question { color: var(--primary); font-size: 0.85rem; margin-bottom: 0.75rem; font-weight: 600; } .vg-modal-content .vg-modal-answer { white-space: pre-wrap; } .vg-modal-content .sources { margin-top: 0.75rem; padding-top: 0.5rem; border-top: 1px solid var(--border); font-size: 0.8rem; color: var(--text-muted); } .vg-modal-content .vg-modal-actions { display: flex; align-items: center; gap: 0.75rem; padding-bottom: 0.75rem; margin-bottom: 0.75rem; border-bottom: 1px solid var(--border); flex-shrink: 0; } .vg-modal-play { width: 48px; height: 48px; border-radius: 50%; background: var(--primary); border: none; color: white; font-size: 1.3rem; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; transition: all 0.2s; vertical-align: middle; } .vg-modal-play:hover { background: #d63a52; } .vg-modal-play:disabled { opacity: 0.4; cursor: not-allowed; } .vg-modal-play.hidden { display: none; } .vg-modal-play-status { font-size: 0.8rem; color: var(--text-muted); margin-top: 0.4rem; } </style> </head> <body> <!-- Login Screen --> <div class="login-overlay" id="loginOverlay"> <div class="login-box"> <h2>ARKANUM</h2> <p>Passwort eingeben um fortzufahren</p> <input type="password" id="passwordInput" placeholder="Passwort" onkeydown="if(event.key==='Enter') login()"> <button onclick="login()">Eintreten</button> <div class="login-error" id="loginError">Falsches Passwort</div> </div> </div> <header> <h1><span>ARKANUM</span></h1> <p>S.T.A.L.K.E.R. The Board Game – Regelexperte</p> <div class="mode-toggle"> <button class="active" id="btnModeChat" onclick="switchMode('chat')">Chat</button> <button id="btnModeVoice" onclick="switchMode('voice')">Voice Guide</button> </div> <div class="app-version" id="appVersion">v0.2.0</div> </header> <main> <!-- Chat Mode --> <div class="chat-mode" id="chatMode"> <div class="chat-area" id="chatArea"> <div class="welcome"> <h2>Willkommen, Stalker.</h2> <p>Stell eine Regelfrage oder fotografiere eine Karte/Spielsituation.</p> <div class="examples"> <button class="example-btn" onclick="askExample(this)">Wie funktioniert Aufmerksamkeit (Attention)?</button> <button class="example-btn" onclick="askExample(this)">Wie viele Aktionen hat ein Stalker pro Zug?</button> <button class="example-btn" onclick="askExample(this)">Was passiert bei einer Emission?</button> </div> </div> </div> <div class="input-area"> <div class="image-preview-bar" id="imagePreview"> <img id="previewImg" src="" alt="Preview"> <span id="previewName">bild.jpg</span> <button class="remove" onclick="removeImage()">&times;</button> </div> <div class="input-row"> <button class="btn btn-camera" onclick="captureImage()" title="Foto aufnehmen"> &#128247; </button> <textarea id="questionInput" rows="1" placeholder="Regelfrage eingeben..." onkeydown="handleKey(event)" oninput="autoGrow(this)"></textarea> <button class="btn btn-send" id="sendBtn" onclick="send()" title="Absenden"> &#10148; </button> </div> </div> </div> <!-- Voice Guide Mode --> <div class="voice-guide" id="voiceGuide"> <!-- Step 1: Mode selection --> <div id="vgModeSelect" class="mode-select"> <h2>Voice Guide starten</h2> <p>Welchen Modus wollt ihr spielen?</p> <div class="mode-select-buttons"> <button class="mode-select-btn" onclick="vgStart('campaign')"> <strong>Campaign</strong> <span>Vollständige Kampagne mit Story-Missionen</span> </button> <button class="mode-select-btn" onclick="vgStart('zone_survival')"> <strong>Zone Survival</strong> <span>Einzelne Session, schnellerer Einstieg</span> </button> </div> </div> <!-- Step 2: Active walkthrough --> <div id="vgActive" style="display:none; flex-direction:column; flex:1; gap:0.75rem;"> <!-- Progress --> <div class="vg-progress"> <div class="vg-progress-header"> <span class="vg-progress-title" id="vgPhaseTitle">Spielübersicht</span> <span class="vg-progress-count" id="vgStepCount">Schritt 1/2</span> </div> <div class="vg-progress-bar"> <div class="vg-progress-fill" id="vgProgressFill" style="width: 0%"></div> </div> <div class="vg-phase-dots" id="vgPhaseDots"></div> </div> <!-- All controls at the top --> <div class="vg-audio-controls"> <button class="vg-audio-btn" id="vgBtnReplay" onclick="vgReplay()" title="Nochmal">&#8634;</button> <button class="vg-audio-btn play-pause" id="vgBtnPause" onclick="vgTogglePause()" title="Pause">&#9646;&#9646;</button> <button class="vg-audio-btn mic" id="vgBtnMic" onclick="vgToggleMic()" title="Mikrofon">&#127908;</button> <button class="vg-audio-btn" id="vgBtnKeyboard" onclick="vgOpenQuestionInput()" title="Regelfrage tippen" style="font-size:1.5rem;">?</button> </div> <div class="vg-nav-controls"> <button class="vg-btn" id="vgBtnBack" onclick="vgBack()" disabled>Zurück</button> <button class="vg-btn primary" id="vgBtnNext" onclick="vgNext()">Weiter</button> <button class="vg-btn" id="vgBtnStop" onclick="vgStop()">Beenden</button> </div> <!-- Status --> <div class="vg-status" id="vgStatus"></div> <!-- Step Content (scrolls below) --> <div class="vg-step-card" id="vgStepCard"> <div class="loading"><span></span><span></span><span></span></div> </div> </div> </div> </main> <!-- Question Input Modal --> <div id="vgQuestionInputModal" class="vg-question-modal hidden" onclick="if(event.target===this) vgCloseQuestionInput()"> <div class="vg-question-modal-content"> <div class="vg-question-input-row"> <input type="text" id="vgQuestionInput" placeholder="Regelfrage eingeben..." onkeydown="if(event.key==='Enter') vgAskQuestion()"> <button class="btn btn-send" onclick="vgAskQuestion()">&#10148;</button> </div> </div> </div> <!-- Answer Modal (outside main/flex containers for reliable iOS positioning) --> <div id="vgQuestionModal" class="vg-modal hidden"> <div class="vg-modal-content"> <div class="vg-modal-actions"> <button class="vg-modal-play hidden" id="vgModalPlayBtn" onclick="vgPlayAnswerAudio(vg._lastAnswerText)" title="Antwort vorlesen">&#9654;</button> <div class="vg-modal-play-status" id="vgModalPlayStatus"></div> <div style="flex:1"></div> <button class="vg-btn" onclick="vgCloseModal()">Zurück</button> </div> <div id="vgModalBody"> <div class="loading"><span></span><span></span><span></span></div> </div> </div> </div> <input type="file" id="imageInput" accept="image/*" capture="environment" onchange="handleImage(event)"> <script> // ===================== SHARED ===================== const API_BASE = window.location.hostname.includes('github.io') ? 'https://FC-Bit-arkanum.hf.space' : window.location.origin; // Load version from server fetch(`${API_BASE}/api/version`).then(r => r.json()).then(d => { document.getElementById('appVersion').textContent = d.version; }).catch(() => {}); let selectedImage = null; let selectedImageType = 'image/jpeg'; function escapeHtml(str) { return str .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;'); } function getPassword() { return localStorage.getItem('arkanum_pw') || ''; } function setPassword(pw) { localStorage.setItem('arkanum_pw', pw); } function handleAuthError(data) { if (data && data.detail === 'Falsches Passwort') { localStorage.removeItem('arkanum_pw'); document.getElementById('loginOverlay').classList.remove('hidden'); return true; } return false; } async function login() { const pw = document.getElementById('passwordInput').value; try { const resp = await fetch(`${API_BASE}/api/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': pw }, body: JSON.stringify({ question: 'test', game: 'stalker' }), }); if (resp.status === 401) { document.getElementById('loginError').style.display = 'block'; return; } setPassword(pw); document.getElementById('loginOverlay').classList.add('hidden'); } catch (e) { document.getElementById('loginError').style.display = 'block'; document.getElementById('loginError').textContent = 'Server nicht erreichbar'; } } if (getPassword()) { document.getElementById('loginOverlay').classList.add('hidden'); } function switchMode(mode) { // Stop voice guide resources when switching to chat if (mode === 'chat' && document.getElementById('vgActive').style.display !== 'none') { vgStop(); } document.getElementById('btnModeChat').classList.toggle('active', mode === 'chat'); document.getElementById('btnModeVoice').classList.toggle('active', mode === 'voice'); document.getElementById('chatMode').classList.toggle('hidden', mode !== 'chat'); document.getElementById('voiceGuide').classList.toggle('active', mode === 'voice'); } // ===================== CHAT MODE ===================== function captureImage() { document.getElementById('imageInput').click(); } function handleImage(event) { const file = event.target.files[0]; if (!file) return; selectedImageType = file.type || 'image/jpeg'; const reader = new FileReader(); reader.onload = (e) => { selectedImage = file; document.getElementById('previewImg').src = e.target.result; document.getElementById('previewName').textContent = file.name; document.getElementById('imagePreview').classList.add('active'); }; reader.readAsDataURL(file); event.target.value = ''; } function removeImage() { selectedImage = null; document.getElementById('imagePreview').classList.remove('active'); } function handleKey(event) { if (event.key === 'Enter' && !event.shiftKey) { event.preventDefault(); send(); } } function autoGrow(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 120) + 'px'; } function askExample(btn) { document.getElementById('questionInput').value = btn.textContent; send(); } function addMessage(role, html) { const chatArea = document.getElementById('chatArea'); const welcome = chatArea.querySelector('.welcome'); if (welcome) welcome.remove(); const msg = document.createElement('div'); msg.className = `message ${role}`; msg.innerHTML = html; chatArea.appendChild(msg); chatArea.scrollTop = chatArea.scrollHeight; return msg; } function addLoading() { return addMessage('assistant', '<div class="loading"><span></span><span></span><span></span></div>'); } function renderMarkdown(text) { let html = escapeHtml(text) .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') .replace(/^### (.+)$/gm, '<h3>$1</h3>') .replace(/^## (.+)$/gm, '<h2>$1</h2>') .replace(/^[\-\*] (.+)$/gm, '<li>$1</li>'); // Wrap consecutive <li> runs in <ul> html = html.replace(/((?:<li>.*<\/li>\n?)+)/g, '<ul>$1</ul>'); html = html.replace(/\n\n/g, '</p><p>'); return '<p>' + html + '</p>'; } async function send() { const sendBtn = document.getElementById('sendBtn'); if (sendBtn.disabled) return; const input = document.getElementById('questionInput'); const question = input.value.trim(); if (!question) return; let userHtml = ''; if (selectedImage) { const imgSrc = document.getElementById('previewImg').src; userHtml += `<img class="image-preview" src="${escapeHtml(imgSrc)}" alt="Foto">`; } userHtml += escapeHtml(question); addMessage('user', userHtml); input.value = ''; input.style.height = 'auto'; sendBtn.disabled = true; const loadingMsg = addLoading(); try { let resp, data; if (selectedImage) { const formData = new FormData(); formData.append('question', question); formData.append('game', 'stalker'); formData.append('image', selectedImage); resp = await fetch(`${API_BASE}/api/ask/vision`, { method: 'POST', headers: { 'X-Password': getPassword() }, body: formData, }); } else { resp = await fetch(`${API_BASE}/api/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ question, game: 'stalker' }), }); } if (!resp.ok) { data = await resp.json().catch(() => ({})); if (handleAuthError(data)) { loadingMsg.innerHTML = '<p style="color: var(--primary)">Sitzung abgelaufen. Bitte erneut einloggen.</p>'; sendBtn.disabled = false; return; } throw new Error(`Server-Fehler (${resp.status})`); } data = await resp.json(); let html = ''; if (data.situation) { html += `<div class="situation">${escapeHtml(data.situation)}</div>`; } html += renderMarkdown(data.answer); if (data.sources && data.sources.length > 0) { html += `<div class="sources">Quellen: ${data.sources.map(escapeHtml).join(', ')}</div>`; } loadingMsg.innerHTML = html; if (selectedImage) removeImage(); } catch (err) { loadingMsg.innerHTML = `<p style="color: var(--primary)">Fehler: ${escapeHtml(err.message)}</p>`; } sendBtn.disabled = false; document.getElementById('chatArea').scrollTop = document.getElementById('chatArea').scrollHeight; } // ===================== VOICE GUIDE ===================== let vg = { walkthrough: null, mode: null, // 'campaign' | 'zone_survival' phaseIdx: 0, stepIdx: 0, phases: [], audio: null, answerAudio: null, isPlaying: false, isLoading: false, prefetchedNext: null, // { key, text, sources, audio } recognition: null, isListening: false, _listenTimeout: null, _lastAnswerText: null, }; async function vgFetchAudio(data) { if (data.audio_url) { const audioResp = await fetch(`${API_BASE}${data.audio_url}`, { headers: { 'X-Password': getPassword() }, }); if (!audioResp.ok) throw new Error('Audio fetch failed'); const audioBlob = await audioResp.blob(); return URL.createObjectURL(audioBlob); } else { const audioResp = await fetch(`${API_BASE}/api/tts`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ text: data.text }), }); if (!audioResp.ok) throw new Error('TTS fetch failed'); const audioBlob = await audioResp.blob(); return URL.createObjectURL(audioBlob); } } function vgRevokePrefetched() { if (vg.prefetchedNext && vg.prefetchedNext.audio) { URL.revokeObjectURL(vg.prefetchedNext.audio); } vg.prefetchedNext = null; } async function vgStart(mode) { vg.mode = mode; document.getElementById('vgModeSelect').style.display = 'none'; document.getElementById('vgActive').style.display = 'flex'; // vgStart init // Unlock audio on iOS with user gesture (non-blocking) try { const silentAudio = new Audio("data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA="); silentAudio.play().then(() => silentAudio.pause()).catch(() => {}); } catch (e) { /* OK if blocked */ } // Pre-init speech recognition and request mic permission early if (!vg.recognition) { vg.recognition = vgInitSpeechRecognition(); if (vg.recognition) { // Trigger permission dialog by briefly starting recognition. // Let onend/onerror clear the flag (not a timeout, which races with the dialog). vg._permissionPending = true; try { vg.recognition.start(); } catch(e) { vg._permissionPending = false; } } } // Load walkthrough definition try { const resp = await fetch(`${API_BASE}/api/walkthrough/stalker`, { headers: { 'X-Password': getPassword() }, }); if (!resp.ok) throw new Error(`Server-Fehler (${resp.status})`); vg.walkthrough = await resp.json(); } catch (err) { document.getElementById('vgStepCard').innerHTML = `<p style="color: var(--primary)">Fehler beim Laden: ${escapeHtml(err.message)}</p>`; return; } vg.phases = vg.walkthrough.modes[mode].phases; vg.phaseIdx = 0; vg.stepIdx = 0; vgRenderPhaseDots(); vgLoadCurrentStep(); } function vgGetTotalSteps() { return vg.phases.reduce((sum, p) => sum + p.steps.length, 0); } function vgGetGlobalStepIndex() { let idx = 0; for (let i = 0; i < vg.phaseIdx; i++) { idx += vg.phases[i].steps.length; } return idx + vg.stepIdx; } function vgRenderPhaseDots() { const container = document.getElementById('vgPhaseDots'); container.innerHTML = vg.phases.map((p, i) => { const cls = i < vg.phaseIdx ? 'done' : (i === vg.phaseIdx ? 'current' : ''); return `<div class="vg-phase-dot ${cls}" title="${escapeHtml(p.title)}"></div>`; }).join(''); } function vgUpdateProgress() { if (vg.phaseIdx >= vg.phases.length) { // At completion, show final state const total = vgGetTotalSteps(); document.getElementById('vgStepCount').textContent = `Schritt ${total}/${total}`; document.getElementById('vgProgressFill').style.width = '100%'; vgRenderPhaseDots(); return; } const phase = vg.phases[vg.phaseIdx]; document.getElementById('vgPhaseTitle').textContent = phase.title; const globalIdx = vgGetGlobalStepIndex(); const total = vgGetTotalSteps(); document.getElementById('vgStepCount').textContent = `Schritt ${globalIdx + 1}/${total}`; document.getElementById('vgProgressFill').style.width = `${((globalIdx + 1) / total) * 100}%`; vgRenderPhaseDots(); // Back button document.getElementById('vgBtnBack').disabled = (vg.phaseIdx === 0 && vg.stepIdx === 0); } async function vgLoadCurrentStep() { if (vg.isLoading) return; vg.isLoading = true; const phase = vg.phases[vg.phaseIdx]; const step = phase.steps[vg.stepIdx]; vgUpdateProgress(); document.getElementById('vgStepCard').innerHTML = '<div class="loading"><span></span><span></span><span></span></div>'; document.getElementById('vgStatus').textContent = 'Lade Schritt...'; // Check if prefetched const stepKey = `${vg.phaseIdx}_${vg.stepIdx}`; if (vg.prefetchedNext && vg.prefetchedNext.key === stepKey) { vgDisplayStep(vg.prefetchedNext.text, vg.prefetchedNext.sources, vg.prefetchedNext.audio); vg.prefetchedNext = null; vg.isLoading = false; vgPrefetchNext(); return; } try { const resp = await fetch(`${API_BASE}/api/walkthrough/step`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ game: 'stalker', mode: vg.mode, phase_id: phase.id, step_id: step.id, }), }); if (!resp.ok) throw new Error(`Server-Fehler (${resp.status})`); const data = await resp.json(); // Show text immediately even if audio fails let audioUrl = null; try { audioUrl = await vgFetchAudio(data); } catch (e) { console.warn('Audio fetch failed, showing text only:', e); } vgDisplayStep(data.text, data.sources, audioUrl); vgPrefetchNext(); } catch (err) { document.getElementById('vgStepCard').innerHTML = `<p style="color: var(--primary)">Fehler: ${escapeHtml(err.message)}</p>`; document.getElementById('vgStatus').textContent = ''; } vg.isLoading = false; } function vgSetPauseIcon(playing) { const btn = document.getElementById('vgBtnPause'); if (playing) { btn.innerHTML = '&#9646;&#9646;'; // pause icon btn.title = 'Pause'; } else { btn.innerHTML = '&#9654;'; // play icon btn.title = 'Abspielen'; } } function vgTogglePause() { if (!vg.audio) return; if (vg.audio.paused) { vg.audio.play().catch(() => {}); } else { vg.audio.pause(); } } function vgDisplayStep(text, sources, audioUrl) { let html = `<div class="vg-step-text">${escapeHtml(text)}</div>`; if (sources && sources.length > 0) { html += `<div class="sources">Quellen: ${sources.map(escapeHtml).join(', ')}</div>`; } document.getElementById('vgStepCard').innerHTML = html; document.getElementById('vgStatus').textContent = ''; // Play audio if (vg.audio) { vg.audio.pause(); URL.revokeObjectURL(vg.audio.src); } if (!audioUrl) { vg.audio = null; vg.isPlaying = false; vgSetPauseIcon(false); document.getElementById('vgStatus').textContent = 'Sage "Weiter" oder drücke den Button'; return; } vg.audio = new Audio(audioUrl); vg.audio.onended = () => { vg.isPlaying = false; vgSetPauseIcon(false); document.getElementById('vgStatus').textContent = 'Sage "Weiter" oder drücke den Button'; }; vg.audio.onplay = () => { vg.isPlaying = true; vgSetPauseIcon(true); document.getElementById('vgStatus').textContent = 'Spielt ab...'; }; vg.audio.onpause = () => { vg.isPlaying = false; vgSetPauseIcon(false); }; vg.audio.play().catch(() => { vgSetPauseIcon(false); document.getElementById('vgStatus').textContent = 'Tippe auf Play zum Abspielen'; }); } async function vgPrefetchNext() { // Determine next step let nextPhaseIdx = vg.phaseIdx; let nextStepIdx = vg.stepIdx + 1; if (nextStepIdx >= vg.phases[nextPhaseIdx].steps.length) { nextPhaseIdx++; nextStepIdx = 0; } if (nextPhaseIdx >= vg.phases.length) return; // no more steps const phase = vg.phases[nextPhaseIdx]; const step = phase.steps[nextStepIdx]; const key = `${nextPhaseIdx}_${nextStepIdx}`; try { const resp = await fetch(`${API_BASE}/api/walkthrough/step`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ game: 'stalker', mode: vg.mode, phase_id: phase.id, step_id: step.id, }), }); if (!resp.ok) return; const data = await resp.json(); const audioUrl = await vgFetchAudio(data); vg.prefetchedNext = { key, text: data.text, sources: data.sources, audio: audioUrl }; } catch (e) { // Prefetch failed – not critical } } function vgNext() { if (vg.isLoading) return; if (vg.audio) { vg.audio.pause(); } vg.stepIdx++; if (vg.stepIdx >= vg.phases[vg.phaseIdx].steps.length) { vg.phaseIdx++; vg.stepIdx = 0; } if (vg.phaseIdx >= vg.phases.length) { // Walkthrough complete — clean up audio if (vg.audio) { URL.revokeObjectURL(vg.audio.src); vg.audio = null; } vgRevokePrefetched(); document.getElementById('vgStepCard').innerHTML = '<div class="vg-step-text">Geschafft! Ihr kennt jetzt die wichtigsten Regeln. Viel Spaß beim Spielen! Falls ihr eine Frage habt, wechselt einfach in den Chat-Modus.</div>'; document.getElementById('vgBtnNext').disabled = true; document.getElementById('vgStatus').textContent = 'Walkthrough abgeschlossen'; vgUpdateProgress(); return; } vgLoadCurrentStep(); } function vgBack() { if (vg.isLoading) return; if (vg.audio) { vg.audio.pause(); } vg.stepIdx--; if (vg.stepIdx < 0) { vg.phaseIdx--; if (vg.phaseIdx < 0) { vg.phaseIdx = 0; vg.stepIdx = 0; return; } vg.stepIdx = vg.phases[vg.phaseIdx].steps.length - 1; } vgRevokePrefetched(); vgLoadCurrentStep(); } function vgReplay() { if (vg.audio) { vg.audio.currentTime = 0; vg.audio.play().catch(() => {}); } } function vgStop() { if (vg.audio) { vg.audio.pause(); URL.revokeObjectURL(vg.audio.src); vg.audio = null; } vgStopAnswerAudio(); if (vg.isListening) { vgStopListening(); } vgRevokePrefetched(); vgSetPauseIcon(false); vgCloseQuestionInput(); vgCloseModal(); vg.isLoading = false; document.getElementById('vgActive').style.display = 'none'; document.getElementById('vgModeSelect').style.display = 'flex'; document.getElementById('vgBtnNext').disabled = false; } // ---- Speech Recognition ---- function vgInitSpeechRecognition() { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SpeechRecognition) return null; const recog = new SpeechRecognition(); recog.lang = 'de-DE'; recog.continuous = false; recog.interimResults = false; recog.onresult = (event) => { const transcript = event.results[0][0].transcript.toLowerCase().trim(); vgHandleVoiceInput(transcript); }; recog.onend = () => { // Permission pre-check: clear flag, skip UI update if (vg._permissionPending) { vg._permissionPending = false; return; } if (vg._listenTimeout) { clearTimeout(vg._listenTimeout); vg._listenTimeout = null; } vg.isListening = false; document.getElementById('vgBtnMic').classList.remove('listening'); document.getElementById('vgBtnMic').innerHTML = '&#127908;'; }; recog.onerror = (event) => { // Permission pre-check: clear flag, skip UI update if (vg._permissionPending) { vg._permissionPending = false; return; } vg.isListening = false; if (vg._listenTimeout) { clearTimeout(vg._listenTimeout); vg._listenTimeout = null; } document.getElementById('vgBtnMic').classList.remove('listening'); document.getElementById('vgBtnMic').innerHTML = '&#127908;'; if (event.error !== 'no-speech' && event.error !== 'aborted') { document.getElementById('vgStatus').textContent = `Mikrofon-Fehler: ${event.error}`; } }; return recog; } function vgStopListening() { if (vg._listenTimeout) { clearTimeout(vg._listenTimeout); vg._listenTimeout = null; } if (vg.isListening && vg.recognition) { vg.isListening = false; try { vg.recognition.stop(); } catch(e) { /* already stopped */ } } vg.isListening = false; document.getElementById('vgBtnMic').classList.remove('listening'); document.getElementById('vgBtnMic').innerHTML = '&#127908;'; document.getElementById('vgStatus').textContent = ''; } function vgToggleMic() { if (!vg.recognition) { vg.recognition = vgInitSpeechRecognition(); } if (!vg.recognition) { document.getElementById('vgStatus').textContent = 'Spracherkennung nicht verfügbar'; return; } if (vg.isListening) { vgStopListening(); } else { // If pre-init is still running, stop it first if (vg._permissionPending) { vg._permissionPending = false; try { vg.recognition.stop(); } catch(e) {} // Brief delay to let recognition fully stop before restarting setTimeout(() => vgToggleMic(), 150); return; } // Pause audio while listening if (vg.audio && vg.isPlaying) { vg.audio.pause(); } try { vg.recognition.start(); } catch(e) { // Recognition may still be stopping — retry once setTimeout(() => { try { vg.recognition.start(); vg.isListening = true; document.getElementById('vgBtnMic').classList.add('listening'); document.getElementById('vgBtnMic').innerHTML = '&#9632;'; document.getElementById('vgStatus').textContent = 'Höre zu... (Tap zum Stoppen)'; } catch(e2) { document.getElementById('vgStatus').textContent = 'Mikrofon konnte nicht gestartet werden'; } }, 200); return; } vg.isListening = true; document.getElementById('vgBtnMic').classList.add('listening'); document.getElementById('vgBtnMic').innerHTML = '&#9632;'; document.getElementById('vgStatus').textContent = 'Höre zu... (Tap zum Stoppen)'; // Auto-stop nach 15 Sekunden vg._listenTimeout = setTimeout(() => { if (vg.isListening) { vgStopListening(); } }, 15000); } } function vgHandleVoiceInput(text) { // Intent classification const continueWords = ['weiter', 'ja', 'ok', 'okay', 'nächster', 'nächste', 'fertig', 'next', 'yes']; const backWords = ['nochmal', 'zurück', 'wiederhole', 'wiederholen', 'nochmals', 'repeat', 'back']; const pauseWords = ['pause', 'stopp', 'stop', 'halt', 'anhalten']; const playWords = ['weiter abspielen', 'play', 'fortsetzen', 'abspielen']; const words = text.split(/\s+/); const isContinue = continueWords.some(w => words.includes(w)); const isBack = backWords.some(w => words.includes(w)); const isPause = pauseWords.some(w => words.includes(w)); const isPlay = playWords.some(w => text.includes(w)); if (isPlay) { if (vg.audio && vg.audio.paused) { vg.audio.play().catch(() => {}); } } else if (isPause) { if (vg.audio && !vg.audio.paused) { vg.audio.pause(); } } else if (isContinue) { vgNext(); } else if (isBack) { vgReplay(); } else { // It's a question – send to /api/ask vgAskQuestionText(text); } } function vgOpenQuestionInput() { // Pause audio while typing if (vg.audio && !vg.audio.paused) { vg.audio.pause(); } document.getElementById('vgQuestionInputModal').classList.remove('hidden'); document.getElementById('vgQuestionInput').focus(); } function vgCloseQuestionInput() { document.getElementById('vgQuestionInputModal').classList.add('hidden'); document.getElementById('vgQuestionInput').value = ''; } async function vgAskQuestion() { const input = document.getElementById('vgQuestionInput'); const question = input.value.trim(); if (!question) return; input.value = ''; vgCloseQuestionInput(); await vgAskQuestionText(question); } function vgStopAnswerAudio() { if (vg.answerAudio) { vg.answerAudio.pause(); URL.revokeObjectURL(vg.answerAudio.src); vg.answerAudio = null; } } function vgOpenModal() { document.getElementById('vgQuestionModal').classList.remove('hidden'); } function vgCloseModal() { document.getElementById('vgQuestionModal').classList.add('hidden'); vgStopAnswerAudio(); vg._lastAnswerText = null; // Don't update status if walkthrough is not active if (document.getElementById('vgActive').style.display !== 'none') { document.getElementById('vgStatus').textContent = 'Sage "Weiter" oder drücke den Button'; } } async function vgPlayAnswerAudio(text) { const btn = document.getElementById('vgModalPlayBtn'); const status = document.getElementById('vgModalPlayStatus'); if (!btn) return; // If already playing, toggle pause if (vg.answerAudio && vg.answerAudio.src) { if (vg.answerAudio.paused) { vg.answerAudio.play().catch(() => {}); btn.innerHTML = '&#9646;&#9646;'; if (status) status.textContent = 'Spielt ab...'; } else { vg.answerAudio.pause(); btn.innerHTML = '&#9654;'; if (status) status.textContent = ''; } return; } // Pre-create audio in gesture context for iOS vgStopAnswerAudio(); vg.answerAudio = new Audio(); try { await vg.answerAudio.play(); } catch(e) { /* unlock */ } vg.answerAudio.pause(); btn.disabled = true; if (status) status.textContent = 'Audio wird generiert...'; try { const audioResp = await fetch(`${API_BASE}/api/tts`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ text }), }); if (!audioResp.ok) throw new Error('TTS failed'); const audioBlob = await audioResp.blob(); const audioUrl = URL.createObjectURL(audioBlob); vg.answerAudio.src = audioUrl; vg.answerAudio.onended = () => { btn.innerHTML = '&#9654;'; if (status) status.textContent = ''; }; vg.answerAudio.play().catch(() => {}); btn.innerHTML = '&#9646;&#9646;'; btn.disabled = false; if (status) status.textContent = 'Spielt ab...'; } catch (err) { btn.innerHTML = '&#9654;'; btn.disabled = false; if (status) status.textContent = 'Audio fehlgeschlagen'; } } async function vgAskQuestionText(question) { // Stop mic first (fixes iPhone mic indicator staying on) if (vg.isListening) { vgStopListening(); } // Pause current walkthrough audio if (vg.audio && !vg.audio.paused) { vg.audio.pause(); } const escapedQuestion = escapeHtml(question); // Open modal with loading state const modalBody = document.getElementById('vgModalBody'); modalBody.innerHTML = `<div class="vg-modal-question">Frage: ${escapedQuestion}</div> <div class="loading"><span></span><span></span><span></span></div>`; document.getElementById('vgModalPlayBtn').classList.add('hidden'); document.getElementById('vgModalPlayStatus').textContent = ''; vgOpenModal(); document.getElementById('vgStatus').textContent = 'Beantworte Frage...'; try { const resp = await fetch(`${API_BASE}/api/ask`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Password': getPassword() }, body: JSON.stringify({ question, game: 'stalker' }), }); if (!resp.ok) { const errData = await resp.json().catch(() => ({})); if (handleAuthError(errData)) { modalBody.innerHTML = `<div class="vg-modal-question">Frage: ${escapedQuestion}</div> <p style="color: var(--primary)">Sitzung abgelaufen. Bitte erneut einloggen.</p>`; document.getElementById('vgStatus').textContent = ''; return; } throw new Error(`Server-Fehler (${resp.status})`); } const data = await resp.json(); // Show text immediately, TTS only on demand via button vg._lastAnswerText = data.answer; const sourcesHtml = (data.sources && data.sources.length > 0) ? `<div class="sources">Quellen: ${data.sources.map(escapeHtml).join(', ')}</div>` : ''; modalBody.innerHTML = `<div class="vg-modal-question">Frage: ${escapedQuestion}</div> <div class="vg-modal-answer">${escapeHtml(data.answer)}</div> ${sourcesHtml}`; // Show play button in top bar document.getElementById('vgModalPlayBtn').classList.remove('hidden'); document.getElementById('vgStatus').textContent = ''; } catch (err) { modalBody.innerHTML = `<div class="vg-modal-question">Frage: ${escapedQuestion}</div> <p style="color: var(--primary)">Fehler: ${escapeHtml(err.message)}</p>`; document.getElementById('vgStatus').textContent = ''; } } </script> </body> </html>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<title>Arkanum – Regelexperte</title>
<link rel="manifest" href="manifest.json">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="theme-color" content="#1a1a2e">
<style>
:root {
--bg: #1a1a2e;
--surface: #16213e;
--primary: #e94560;
--accent: #f5a623;
--text: #eee;
--text-muted: #999;
--border: #333;
--success: #4caf50;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100dvh;
display: flex;
flex-direction: column;
padding-left: env(safe-area-inset-left);
padding-right: env(safe-area-inset-right);
}
header {
background: var(--surface);
padding: 1rem;
padding-top: max(1rem, env(safe-area-inset-top));
text-align: center;
border-bottom: 2px solid var(--primary);
}
header h1 {
font-size: 1.4rem;
letter-spacing: 2px;
}
header h1 span { color: var(--primary); }
header p {
font-size: 0.8rem;
color: var(--text-muted);
margin-top: 0.25rem;
}
/* Mode Toggle */
.mode-toggle {
display: flex;
justify-content: center;
gap: 0;
margin-top: 0.5rem;
}
.mode-toggle button {
background: transparent;
border: 1px solid var(--border);
color: var(--text-muted);
padding: 0.6rem 1rem;
min-height: 44px;
font-size: 0.75rem;
cursor: pointer;
transition: all 0.2s;
}
.mode-toggle button:first-child { border-radius: 6px 0 0 6px; }
.mode-toggle button:last-child { border-radius: 0 6px 6px 0; }
.mode-toggle button.active {
background: var(--primary);
border-color: var(--primary);
color: white;
}
.app-version {
font-size: 0.65rem;
color: var(--text-muted);
margin-top: 0.25rem;
opacity: 0.6;
}
main {
flex: 1;
padding: 1rem;
max-width: 700px;
width: 100%;
margin: 0 auto;
display: flex;
flex-direction: column;