Spaces:
Sleeping
Sleeping
Download frontend/app.js from hamba-ho/Assistant-Web-Educatif: direct link, hf CLI and curl.
- Browser
- Download file 22 kB
-
https://huggingface.co/spaces/hamba-ho/Assistant-Web-Educatif/resolve/main/frontend/app.js
- Command line
-
hf download hf://spaces/hamba-ho/Assistant-Web-Educatif/frontend/app.js
-
curl -L -o app.js https://huggingface.co/spaces/hamba-ho/Assistant-Web-Educatif/resolve/main/frontend/app.js
22 kB
| // ============================================= | |
| // Assistant Éducatif | |
| // app.js — Logique SPA | |
| // ============================================= | |
| const API_BASE = "/api/v1"; | |
| // ===== STATE ===== | |
| let currentSession = ""; | |
| let selectedFile = null; | |
| let sessionDocs = []; | |
| // ===== NAVIGATION ===== | |
| function showTeacherLogin() { | |
| document.getElementById("role-selection").classList.add("hidden"); | |
| document.getElementById("teacher-login").classList.remove("hidden"); | |
| } | |
| function showStudentLogin() { | |
| document.getElementById("role-selection").classList.add("hidden"); | |
| document.getElementById("student-login").classList.remove("hidden"); | |
| } | |
| function cancelLogin() { | |
| document.getElementById("teacher-login").classList.add("hidden"); | |
| document.getElementById("student-login").classList.add("hidden"); | |
| document.getElementById("role-selection").classList.remove("hidden"); | |
| } | |
| function selectRole(role) { | |
| let inputId = role === "teacher" ? "teacher-session-input" : "student-session-input"; | |
| const rawInput = document.getElementById(inputId).value.trim(); | |
| if (!rawInput) { | |
| alert("Veuillez entrer ou générer un code de session avant de continuer."); | |
| document.getElementById(inputId).focus(); | |
| return; | |
| } | |
| currentSession = rawInput.toUpperCase().replace(/\s+/g, "-"); | |
| if (role === "teacher") { | |
| document.getElementById("teacher-session-badge").textContent = `Session : ${currentSession}`; | |
| showPage("teacher-view"); | |
| loadDocs(); | |
| loadStats(); | |
| // Save socratic mode config | |
| const isSocratic = document.getElementById("socratic-mode-checkbox").checked; | |
| fetch(`${API_BASE}/sessions/${currentSession}/config`, { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ socratic_mode: isSocratic }) | |
| }).catch(e => console.error("Erreur config", e)); | |
| } else { | |
| document.getElementById("student-session-badge").textContent = `Session : ${currentSession}`; | |
| showPage("student-view"); | |
| } | |
| } | |
| function showPage(id) { | |
| document.querySelectorAll(".page").forEach(p => p.classList.remove("active")); | |
| document.getElementById(id).classList.add("active"); | |
| window.scrollTo(0, 0); | |
| } | |
| function goHome() { | |
| showPage("landing"); | |
| selectedFile = null; | |
| document.getElementById("file-preview").classList.add("hidden"); | |
| document.getElementById("upload-result").classList.add("hidden"); | |
| document.getElementById("upload-form").reset(); | |
| cancelLogin(); // Remettre l'écran de sélection de rôle | |
| } | |
| function generateSession(inputId) { | |
| const adjectives = ["ORANGE", "BLEU", "ROUGE", "VERT", "BLANC", "SOLEIL", "LUNE", "ETOILE"]; | |
| const nouns = ["PHYS", "MATH", "BIO", "CHIMIE", "INFO", "DROIT", "ECO", "HIST"]; | |
| const num = Math.floor(Math.random() * 900) + 100; | |
| const adj = adjectives[Math.floor(Math.random() * adjectives.length)]; | |
| const noun = nouns[Math.floor(Math.random() * nouns.length)]; | |
| document.getElementById(inputId).value = `${noun}-${adj}-${num}`; | |
| } | |
| // ===== UPLOAD ===== | |
| function handleDrop(event) { | |
| event.preventDefault(); | |
| document.getElementById("upload-zone").classList.remove("drag-over"); | |
| const file = event.dataTransfer.files[0]; | |
| if (file) processFile(file); | |
| } | |
| function handleFileSelect(event) { | |
| const file = event.target.files[0]; | |
| if (file) processFile(file); | |
| } | |
| function processFile(file) { | |
| if (!file.name.toLowerCase().endsWith(".pdf")) { | |
| alert("Seuls les fichiers PDF sont acceptés."); | |
| return; | |
| } | |
| selectedFile = file; | |
| const preview = document.getElementById("file-preview"); | |
| preview.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} Ko)`; | |
| preview.classList.remove("hidden"); | |
| } | |
| document.getElementById("upload-form").addEventListener("submit", async function(e) { | |
| e.preventDefault(); | |
| if (!selectedFile) { | |
| alert("Veuillez sélectionner un fichier PDF."); | |
| return; | |
| } | |
| const subject = document.getElementById("subject").value.trim(); | |
| const level = document.getElementById("level").value.trim(); | |
| if (!subject || !level) { | |
| alert("Remplissez la matière et le niveau."); | |
| return; | |
| } | |
| const btn = document.getElementById("upload-btn"); | |
| const btnText = document.getElementById("upload-btn-text"); | |
| const spinner = document.getElementById("upload-spinner"); | |
| btn.disabled = true; | |
| btnText.textContent = "Traitement en cours…"; | |
| spinner.classList.remove("hidden"); | |
| const formData = new FormData(); | |
| formData.append("file", selectedFile); | |
| formData.append("subject", subject); | |
| formData.append("level", level); | |
| formData.append("session_id", currentSession); | |
| const result = document.getElementById("upload-result"); | |
| result.classList.add("hidden"); | |
| result.classList.remove("error"); | |
| try { | |
| const resp = await fetch(`${API_BASE}/documents`, { method: "POST", body: formData }); | |
| const data = await resp.json(); | |
| if (resp.ok) { | |
| result.innerHTML = `<strong>${data.document.file_name}</strong> indexé avec succès !<br/> | |
| ${data.document.chunks_added} passages indexés • ${subject} • ${level}`; | |
| if (data.warning_ocr) { | |
| result.innerHTML += `<div style="margin-top: 10px; padding: 10px; background: rgba(255,165,0,0.2); color: orange; border-radius: 4px; font-size: 0.9rem;">${data.warning_ocr}</div>`; | |
| } | |
| result.classList.remove("hidden"); | |
| selectedFile = null; | |
| document.getElementById("file-preview").classList.add("hidden"); | |
| document.getElementById("upload-form").reset(); | |
| sessionDocs.push(data.document); | |
| renderDocs(); | |
| } else { | |
| result.innerHTML = `Erreur : ${data.detail || "Erreur inconnue"}`; | |
| result.classList.add("error"); | |
| result.classList.remove("hidden"); | |
| } | |
| } catch (err) { | |
| result.innerHTML = `Impossible de joindre le serveur.<br/><small>Vérifiez que le backend tourne sur localhost:8000</small>`; | |
| result.classList.add("error"); | |
| result.classList.remove("hidden"); | |
| } finally { | |
| btn.disabled = false; | |
| btnText.textContent = "Indexer le document"; | |
| spinner.classList.add("hidden"); | |
| } | |
| }); | |
| async function loadDocs() { | |
| try { | |
| const resp = await fetch(`${API_BASE}/documents/${currentSession}`); | |
| if (resp.ok) { | |
| const docs = await resp.json(); | |
| sessionDocs = docs; | |
| renderDocs(); | |
| } | |
| } catch {} | |
| } | |
| function renderDocs() { | |
| const list = document.getElementById("docs-list"); | |
| if (sessionDocs.length === 0) { | |
| list.innerHTML = `<p class="empty-state">Aucun document chargé pour l'instant.</p>`; | |
| return; | |
| } | |
| list.innerHTML = sessionDocs.map(doc => ` | |
| <div class="doc-item" style="display: flex; justify-content: space-between; align-items: center;"> | |
| <div> | |
| <div class="doc-name">${doc.file_name}</div> | |
| <div class="doc-meta">${doc.subject || ''} • ${doc.level || ''}</div> | |
| </div> | |
| <div style="display: flex; gap: 10px; align-items: center;"> | |
| <span class="doc-status">Prêt</span> | |
| <button onclick="deleteDocument(${doc.id})" class="btn-danger" style="padding: 5px 10px; min-width: auto; font-size: 0.85rem;">Supprimer</button> | |
| </div> | |
| </div> | |
| `).join(""); | |
| } | |
| async function clearSession() { | |
| if (!confirm(`Supprimer tous les documents de la session "${currentSession}" ?`)) return; | |
| try { | |
| await fetch(`${API_BASE}/documents/session/${currentSession}`, { method: "DELETE" }); | |
| sessionDocs = []; | |
| renderDocs(); | |
| document.getElementById("upload-result").classList.add("hidden"); | |
| } catch { | |
| alert("Erreur lors de la suppression."); | |
| } | |
| } | |
| async function deleteDocument(docId) { | |
| if (!confirm("Supprimer ce document de la session ?")) return; | |
| try { | |
| const resp = await fetch(`${API_BASE}/documents/${currentSession}/${docId}`, { method: "DELETE" }); | |
| if (resp.ok) { | |
| loadDocs(); | |
| } else { | |
| alert("Erreur lors de la suppression du document."); | |
| } | |
| } catch { | |
| alert("Impossible de joindre le serveur."); | |
| } | |
| } | |
| async function loadStats() { | |
| try { | |
| const resp = await fetch(`${API_BASE}/stats/${currentSession}`); | |
| if (resp.ok) { | |
| const data = await resp.json(); | |
| document.getElementById("stats-questions-count").textContent = data.total_questions; | |
| document.getElementById("stats-dashboard").style.display = "block"; | |
| } | |
| } catch { | |
| console.error("Erreur chargement stats"); | |
| } | |
| } | |
| // ===== CHAT ===== | |
| async function sendQuestion(e) { | |
| e.preventDefault(); | |
| const input = document.getElementById("question-input"); | |
| const question = input.value.trim(); | |
| if (!question) return; | |
| appendMessage(question, "user"); | |
| input.value = ""; | |
| input.style.height = "auto"; | |
| const typingId = appendTyping(); | |
| const sendBtn = document.getElementById("send-btn"); | |
| sendBtn.disabled = true; | |
| document.getElementById("chat-status").textContent = "En train de répondre…"; | |
| try { | |
| const resp = await fetch(`${API_BASE}/ask`, { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ question, session_id: currentSession }) | |
| }); | |
| const data = await resp.json(); | |
| removeTyping(typingId); | |
| if (resp.ok) { | |
| appendBotMessage(data.answer, data.sources || []); | |
| } else { | |
| appendBotMessage(`Erreur : ${data.detail || "Erreur du serveur."}`, []); | |
| } | |
| } catch (err) { | |
| removeTyping(typingId); | |
| appendBotMessage("Impossible de joindre le serveur. Vérifiez que le backend est lancé.", []); | |
| } finally { | |
| sendBtn.disabled = false; | |
| document.getElementById("chat-status").textContent = "Prêt à répondre"; | |
| } | |
| } | |
| function appendMessage(text, role) { | |
| const area = document.getElementById("messages-area"); | |
| const div = document.createElement("div"); | |
| div.className = `message ${role === "user" ? "user-message" : "bot-message"}`; | |
| div.innerHTML = `<div class="message-bubble">${escapeHtml(text).replace(/\n/g, "<br/>")}</div>`; | |
| area.appendChild(div); | |
| area.scrollTop = area.scrollHeight; | |
| } | |
| function appendBotMessage(text, sources) { | |
| const area = document.getElementById("messages-area"); | |
| const div = document.createElement("div"); | |
| div.className = "message bot-message"; | |
| // Dédoublonnage des sources | |
| const uniqueSources = []; | |
| const seen = new Set(); | |
| for (const s of sources) { | |
| const key = `${s.document}-${s.page}`; | |
| if (!seen.has(key)) { seen.add(key); uniqueSources.push(s); } | |
| } | |
| const sourcesHtml = uniqueSources.length > 0 | |
| ? `<div style="margin-top: 15px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.1);"> | |
| <span style="font-size: 0.8rem; color: var(--text-muted); text-transform: uppercase; letter-spacing: 1px;">Références</span> | |
| <div class="sources-list" style="margin-top: 5px;"> | |
| ${uniqueSources.map(s => ` | |
| <div style="display: flex; flex-direction: column; background: rgba(255,255,255,0.05); padding: 8px; border-radius: 6px; margin-bottom: 5px;"> | |
| <span style="font-size: 0.85rem;">${escapeHtml(s.document)} — p.${s.page || '?'}</span> | |
| ${s.doc_id ? `<button onclick="viewPage('${s.doc_id}', '${s.page}')" class="btn-secondary" style="font-size: 0.75rem; padding: 4px 8px; margin-top: 5px; width: fit-content; border-color: rgba(255,255,255,0.1);">Voir la page</button>` : ''} | |
| </div> | |
| `).join("")} | |
| </div> | |
| </div>` | |
| : ""; | |
| div.innerHTML = ` | |
| <div class="message-bubble" style="width: 100%;"> | |
| <div class="ai-text">${escapeHtml(text).replace(/\n/g, "<br/>")}</div> | |
| <button onclick="readOutLoud(this.getAttribute('data-text'))" data-text="${escapeHtml(text)}" class="btn-icon" style="background: none; border: none; cursor: pointer; margin-top: 10px; margin-bottom: 5px; color: var(--accent-3); display: flex; align-items: center; gap: 5px; font-size: 0.8rem;"> | |
| <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg> | |
| Écouter | |
| </button> | |
| ${sourcesHtml} | |
| </div>`; | |
| area.appendChild(div); | |
| // Rendu Mathématique KaTeX | |
| if (window.katexLoaded && window.renderMathInElement) { | |
| try { | |
| window.renderMathInElement(div.querySelector('.ai-text'), { | |
| delimiters: [ | |
| {left: '$$', right: '$$', display: true}, | |
| {left: '$', right: '$', display: false}, | |
| {left: '\\(', right: '\\)', display: false}, | |
| {left: '\\[', right: '\\]', display: true} | |
| ], | |
| throwOnError: false | |
| }); | |
| } catch(e) {} | |
| } | |
| area.scrollTop = area.scrollHeight; | |
| } | |
| function appendTyping() { | |
| const area = document.getElementById("messages-area"); | |
| const id = "typing-" + Date.now(); | |
| const div = document.createElement("div"); | |
| div.id = id; | |
| div.className = "message bot-message typing-indicator"; | |
| div.innerHTML = `<div class="message-bubble"><span class="typing-dot"></span><span class="typing-dot"></span><span class="typing-dot"></span></div>`; | |
| area.appendChild(div); | |
| area.scrollTop = area.scrollHeight; | |
| return id; | |
| } | |
| function removeTyping(id) { | |
| const el = document.getElementById(id); | |
| if (el) el.remove(); | |
| } | |
| // ===== UTILS ===== | |
| function handleEnter(e) { | |
| if (e.key === "Enter" && !e.shiftKey) { | |
| e.preventDefault(); | |
| document.getElementById("chat-form").dispatchEvent(new Event("submit")); | |
| } | |
| } | |
| function autoResize(el) { | |
| el.style.height = "auto"; | |
| el.style.height = Math.min(el.scrollHeight, 140) + "px"; | |
| } | |
| function escapeHtml(str) { | |
| return String(str) | |
| .replace(/&/g, "&") | |
| .replace(/</g, "<") | |
| .replace(/>/g, ">") | |
| .replace(/"/g, """); | |
| } | |
| function viewPage(docId, pageStr) { | |
| if (!docId || !pageStr) return; | |
| const pageMatch = pageStr.match(/\d+/); | |
| if (!pageMatch) return; | |
| const pageNum = parseInt(pageMatch[0], 10); | |
| const img = document.getElementById("pdf-page-img"); | |
| img.src = `${API_BASE}/documents/${currentSession}/${docId}/page/${pageNum}`; | |
| const modal = document.getElementById("pdf-modal"); | |
| modal.style.display = "flex"; | |
| } | |
| function closePdfModal() { | |
| document.getElementById("pdf-modal").style.display = "none"; | |
| document.getElementById("pdf-page-img").src = ""; | |
| } | |
| function animateValue(id, start, end, duration) { | |
| if (start === end) return; | |
| const obj = document.getElementById(id); | |
| let startTimestamp = null; | |
| const step = (timestamp) => { | |
| if (!startTimestamp) startTimestamp = timestamp; | |
| const progress = Math.min((timestamp - startTimestamp) / duration, 1); | |
| obj.innerHTML = Math.floor(progress * (end - start) + start); | |
| if (progress < 1) { | |
| window.requestAnimationFrame(step); | |
| } | |
| }; | |
| window.requestAnimationFrame(step); | |
| } | |
| async function loadGlobalStats() { | |
| try { | |
| const resp = await fetch(`${API_BASE}/stats/global`); | |
| if (resp.ok) { | |
| const data = await resp.json(); | |
| document.getElementById("global-stats").classList.remove("hidden"); | |
| animateValue("stat-sessions", 0, data.total_sessions, 1500); | |
| animateValue("stat-docs", 0, data.total_documents, 1500); | |
| animateValue("stat-questions", 0, data.total_questions, 1500); | |
| } | |
| } catch (e) { | |
| console.error("Erreur stats globales", e); | |
| } | |
| } | |
| // Initialisation au démarrage | |
| document.addEventListener("DOMContentLoaded", () => { | |
| loadGlobalStats(); | |
| }); | |
| // ===== VOICE (WHISPER API) ===== | |
| let mediaRecorder = null; | |
| let audioChunks = []; | |
| let isRecording = false; | |
| async function toggleVoiceRecording() { | |
| if (isRecording) { | |
| stopRecording(); | |
| return; | |
| } | |
| try { | |
| const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); | |
| mediaRecorder = new MediaRecorder(stream); | |
| audioChunks = []; | |
| mediaRecorder.ondataavailable = event => { | |
| if (event.data.size > 0) audioChunks.push(event.data); | |
| }; | |
| mediaRecorder.onstop = async () => { | |
| const audioBlob = new Blob(audioChunks, { type: 'audio/webm' }); | |
| stream.getTracks().forEach(track => track.stop()); | |
| await sendAudioToWhisper(audioBlob); | |
| }; | |
| mediaRecorder.start(); | |
| isRecording = true; | |
| document.getElementById("mic-btn").style.stroke = "var(--danger)"; | |
| document.getElementById("question-input").placeholder = "Enregistrement... Cliquez pour arrêter."; | |
| } catch (err) { | |
| console.error(err); | |
| alert("Impossible d'accéder au microphone."); | |
| } | |
| } | |
| function stopRecording() { | |
| if (mediaRecorder && isRecording) { | |
| mediaRecorder.stop(); | |
| isRecording = false; | |
| document.getElementById("mic-btn").style.stroke = "var(--text-muted)"; | |
| document.getElementById("question-input").placeholder = "Traduction et transcription en cours..."; | |
| } | |
| } | |
| async function sendAudioToWhisper(blob) { | |
| const formData = new FormData(); | |
| formData.append("file", blob, "voice.webm"); | |
| try { | |
| const resp = await fetch(`${API_BASE}/transcribe`, { | |
| method: "POST", | |
| body: formData | |
| }); | |
| if (resp.ok) { | |
| const data = await resp.json(); | |
| document.getElementById("question-input").value = data.text; | |
| autoResize(document.getElementById("question-input")); | |
| } else { | |
| alert("Erreur lors de la transcription."); | |
| } | |
| } catch (e) { | |
| alert("Impossible de contacter le serveur vocal."); | |
| } finally { | |
| document.getElementById("question-input").placeholder = "Posez votre question ou utilisez le micro..."; | |
| } | |
| } | |
| function readOutLoud(text) { | |
| if (!('speechSynthesis' in window)) { | |
| alert("Votre navigateur ne supporte pas la synthèse vocale."); | |
| return; | |
| } | |
| window.speechSynthesis.cancel(); | |
| const utterance = new SpeechSynthesisUtterance(text); | |
| utterance.lang = 'fr-FR'; | |
| utterance.rate = 1.0; | |
| window.speechSynthesis.speak(utterance); | |
| } | |
| // ===== QUIZ ===== | |
| async function generateQuiz() { | |
| const btn = document.getElementById("btn-quiz"); | |
| btn.disabled = true; | |
| btn.innerHTML = `<span class="spinner" style="width:14px;height:14px;margin-right:8px;"></span> Création du Test...`; | |
| try { | |
| const resp = await fetch(`${API_BASE}/quiz/${currentSession}`); | |
| if (resp.ok) { | |
| const data = await resp.json(); | |
| renderQuiz(data.quiz); | |
| } else { | |
| alert("Erreur lors de la génération du test."); | |
| } | |
| } catch (e) { | |
| alert("Impossible de joindre le serveur."); | |
| } finally { | |
| btn.disabled = false; | |
| btn.innerHTML = `<svg style="width:16px; height:16px; margin-right:4px;" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"></path></svg> Générer un Test`; | |
| } | |
| } | |
| function renderQuiz(quizJson) { | |
| let quizData; | |
| try { | |
| quizData = typeof quizJson === 'string' ? JSON.parse(quizJson) : quizJson; | |
| } catch(e) { | |
| console.error(e); | |
| appendBotMessage("Désolé, je n'ai pas pu générer un test valide. Veuillez réessayer.", []); | |
| return; | |
| } | |
| if (!quizData || !quizData.questions) { | |
| appendBotMessage("Le test généré est vide.", []); | |
| return; | |
| } | |
| let html = `<div style="background: rgba(108,99,255,0.05); border: 1px solid rgba(108,99,255,0.2); padding: 15px; border-radius: 10px; margin-top: 10px; width: 100%;">`; | |
| html += `<h3 style="margin-bottom: 15px; color: var(--accent-2);">Test Express</h3>`; | |
| quizData.questions.forEach((q, qIndex) => { | |
| html += `<div style="margin-bottom: 20px;">`; | |
| html += `<p style="font-weight: 600; margin-bottom: 10px;">${qIndex + 1}. ${escapeHtml(q.question)}</p>`; | |
| q.options.forEach((opt, oIndex) => { | |
| html += `<div style="margin-bottom: 8px;"> | |
| <label style="cursor: pointer; display: flex; align-items: center; gap: 8px;"> | |
| <input type="radio" name="q${qIndex}" value="${oIndex}" data-correct="${q.correct_index}"> | |
| ${escapeHtml(opt)} | |
| </label> | |
| </div>`; | |
| }); | |
| html += `<div id="feedback-q${qIndex}" style="font-size: 0.85rem; margin-top: 5px; display: none;"></div>`; | |
| html += `</div>`; | |
| }); | |
| html += `<button onclick="window.checkQuiz(this)" class="btn-primary" style="padding: 8px 16px; font-size: 0.9rem;">Valider mes réponses</button>`; | |
| html += `</div>`; | |
| const area = document.getElementById("messages-area"); | |
| const div = document.createElement("div"); | |
| div.className = "message bot-message"; | |
| div.innerHTML = `<div class="message-bubble" style="max-width: 100%; width: 90%;">${html}</div>`; | |
| area.appendChild(div); | |
| area.scrollTop = area.scrollHeight; | |
| } | |
| window.checkQuiz = function(btn) { | |
| const container = btn.parentElement; | |
| const questions = container.querySelectorAll('div[style*="margin-bottom: 20px"]'); | |
| let score = 0; | |
| questions.forEach((qDiv, qIndex) => { | |
| const selected = qDiv.querySelector(`input[name="q${qIndex}"]:checked`); | |
| const feedback = qDiv.querySelector(`#feedback-q${qIndex}`); | |
| feedback.style.display = 'block'; | |
| const correctRadio = qDiv.querySelector(`input[data-correct]:first-of-type`); | |
| const correctIndex = correctRadio ? correctRadio.getAttribute('data-correct') : null; | |
| let correctText = ""; | |
| if (correctIndex !== null) { | |
| const correctLabel = qDiv.querySelector(`input[name="q${qIndex}"][value="${correctIndex}"]`).parentElement; | |
| correctText = correctLabel.textContent.trim(); | |
| } | |
| if (!selected) { | |
| feedback.innerHTML = `<span style="color: var(--danger)">Veuillez sélectionner une réponse. La bonne réponse était : <strong style="color: var(--success);">${correctText}</strong></span>`; | |
| return; | |
| } | |
| if (selected.value === correctIndex) { | |
| score++; | |
| feedback.innerHTML = `<span style="color: var(--success)">Correct !</span>`; | |
| } else { | |
| feedback.innerHTML = `<span style="color: var(--danger)">Incorrect. La bonne réponse était : <strong style="color: var(--success);">${correctText}</strong></span>`; | |
| } | |
| }); | |
| btn.textContent = `Score : ${score} / ${questions.length}`; | |
| btn.disabled = true; | |
| }; | |