Download static/js/simulado.js from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/simulado.js
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/static/js/simulado.js
-
curl -L -o simulado.js https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/simulado.js
23 kB
| // ===== Simulado (Simulated Exam) Module ===== | |
| const Simulado = { | |
| // State | |
| simuladoId: null, | |
| questions: [], | |
| answers: {}, // { questionId: 'A' } | |
| currentIndex: 0, | |
| viewMode: 'single', // 'single' or 'all' | |
| timeLimit: 0, // seconds | |
| timeRemaining: 0, // seconds | |
| timerInterval: null, | |
| startTime: null, | |
| submitted: false, | |
| topicsCache: null, | |
| yearsCache: null, | |
| // ===== API ===== | |
| async loadTopics() { | |
| if (this.topicsCache) return this.topicsCache; | |
| const res = await fetch('/api/topics', { headers: Auth.headers() }); | |
| if (!res.ok) throw new Error('Erro ao carregar topicos'); | |
| const data = await res.json(); | |
| this.topicsCache = data.topics; | |
| return this.topicsCache; | |
| }, | |
| async loadYears() { | |
| if (this.yearsCache) return this.yearsCache; | |
| const res = await fetch('/api/years', { headers: Auth.headers() }); | |
| if (!res.ok) throw new Error('Erro ao carregar anos'); | |
| const data = await res.json(); | |
| this.yearsCache = data.years; | |
| return this.yearsCache; | |
| }, | |
| async generateExam(count, tracks, year) { | |
| const params = new URLSearchParams({ count, tracks, year }); | |
| const res = await fetch(`/api/simulado/generate?${params}`, { headers: Auth.headers() }); | |
| if (!res.ok) { | |
| const err = await res.json(); | |
| throw new Error(err.error || 'Erro ao gerar simulado'); | |
| } | |
| return await res.json(); | |
| }, | |
| async submitExam() { | |
| const timeSpent = Math.floor((Date.now() - this.startTime) / 1000); | |
| const res = await fetch('/api/simulado/submit', { | |
| method: 'POST', | |
| headers: Auth.headers(), | |
| body: JSON.stringify({ | |
| simulado_id: this.simuladoId, | |
| answers: this.answers, | |
| time_spent_seconds: timeSpent | |
| }) | |
| }); | |
| if (!res.ok) throw new Error('Erro ao enviar simulado'); | |
| return await res.json(); | |
| }, | |
| // ===== CONFIG SCREEN ===== | |
| async renderConfig() { | |
| const [topics, years] = await Promise.all([this.loadTopics(), this.loadYears()]); | |
| const topicChecks = topics.map(t => ` | |
| <label class="simulado-check"> | |
| <input type="checkbox" value="${t.slug}" checked> | |
| <span>${this.escapeHtml(t.name)} <small>(${t.count})</small></span> | |
| </label> | |
| `).join(''); | |
| const yearOpts = years.map(y => `<option value="${y}">${y}</option>`).join(''); | |
| return ` | |
| <div class="container protected-content"> | |
| <div class="question-nav"> | |
| <a class="back-btn" onclick="App.navigate('/')">← Voltar</a> | |
| <h2>Simulado</h2> | |
| </div> | |
| <div class="simulado-config"> | |
| <div class="simulado-config-section"> | |
| <h3>Numero de questoes</h3> | |
| <div class="simulado-count-options"> | |
| <button class="simulado-count-btn" data-count="10" onclick="Simulado.selectCount(this)">10</button> | |
| <button class="simulado-count-btn" data-count="25" onclick="Simulado.selectCount(this)">25</button> | |
| <button class="simulado-count-btn active" data-count="50" onclick="Simulado.selectCount(this)">50</button> | |
| <button class="simulado-count-btn" data-count="100" onclick="Simulado.selectCount(this)">100</button> | |
| </div> | |
| </div> | |
| <div class="simulado-config-section"> | |
| <h3>Ano (opcional)</h3> | |
| <select id="simulado-year" class="simulado-select"> | |
| <option value="">Todos os anos</option> | |
| ${yearOpts} | |
| </select> | |
| </div> | |
| <div class="simulado-config-section"> | |
| <h3>Topicos</h3> | |
| <div class="simulado-track-actions"> | |
| <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleAllTracks(true)">Selecionar todos</button> | |
| <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleAllTracks(false)">Desmarcar todos</button> | |
| </div> | |
| <div class="simulado-tracks" id="simulado-tracks"> | |
| ${topicChecks} | |
| </div> | |
| </div> | |
| <div class="simulado-config-error" id="simulado-config-error"></div> | |
| <button class="btn btn-primary simulado-start-btn" id="simulado-start-btn" onclick="Simulado.startExam()"> | |
| Iniciar Simulado | |
| </button> | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| selectCount(btn) { | |
| document.querySelectorAll('.simulado-count-btn').forEach(b => b.classList.remove('active')); | |
| btn.classList.add('active'); | |
| }, | |
| toggleAllTracks(checked) { | |
| document.querySelectorAll('#simulado-tracks input[type="checkbox"]').forEach(cb => { | |
| cb.checked = checked; | |
| }); | |
| }, | |
| async startExam() { | |
| const btn = document.getElementById('simulado-start-btn'); | |
| const errorEl = document.getElementById('simulado-config-error'); | |
| errorEl.style.display = 'none'; | |
| const countBtn = document.querySelector('.simulado-count-btn.active'); | |
| const count = countBtn ? parseInt(countBtn.dataset.count) : 50; | |
| const year = document.getElementById('simulado-year').value; | |
| const checkedBoxes = document.querySelectorAll('#simulado-tracks input:checked'); | |
| if (checkedBoxes.length === 0) { | |
| errorEl.textContent = 'Selecione pelo menos um topico.'; | |
| errorEl.style.display = 'block'; | |
| return; | |
| } | |
| const allBoxes = document.querySelectorAll('#simulado-tracks input[type="checkbox"]'); | |
| let tracks = 'all'; | |
| if (checkedBoxes.length < allBoxes.length) { | |
| tracks = Array.from(checkedBoxes).map(cb => cb.value).join(','); | |
| } | |
| btn.disabled = true; | |
| btn.textContent = 'Gerando simulado...'; | |
| try { | |
| const data = await this.generateExam(count, tracks, year); | |
| this.simuladoId = data.simulado_id; | |
| this.questions = data.questions; | |
| this.answers = {}; | |
| this.currentIndex = 0; | |
| this.viewMode = 'single'; | |
| this.timeLimit = data.time_limit_minutes * 60; | |
| this.timeRemaining = this.timeLimit; | |
| this.startTime = Date.now(); | |
| this.submitted = false; | |
| window.location.hash = '#/simulado/exam'; | |
| } catch (e) { | |
| errorEl.textContent = e.message; | |
| errorEl.style.display = 'block'; | |
| btn.disabled = false; | |
| btn.textContent = 'Iniciar Simulado'; | |
| } | |
| }, | |
| // ===== EXAM SCREEN ===== | |
| renderExam() { | |
| if (!this.questions.length) { | |
| return '<div class="container"><p>Nenhum simulado ativo. <a onclick="App.navigate(\'/simulado\')">Configurar novo simulado</a></p></div>'; | |
| } | |
| this.startTimer(); | |
| const navButtons = this.questions.map((q, i) => { | |
| const answered = this.answers[q.id] ? 'answered' : ''; | |
| const current = i === this.currentIndex ? 'current' : ''; | |
| return `<button class="simulado-nav-btn ${answered} ${current}" onclick="Simulado.goToQuestion(${i})">${i + 1}</button>`; | |
| }).join(''); | |
| const answeredCount = Object.keys(this.answers).length; | |
| const totalCount = this.questions.length; | |
| let questionsHtml; | |
| if (this.viewMode === 'single') { | |
| questionsHtml = this.renderSingleQuestion(this.currentIndex); | |
| } else { | |
| questionsHtml = this.questions.map((q, i) => this.renderExamQuestion(q, i)).join(''); | |
| } | |
| return ` | |
| <div class="simulado-timer" id="simulado-timer"> | |
| <div class="simulado-timer-left"> | |
| <span class="simulado-timer-icon">⏰</span> | |
| <span class="simulado-timer-text" id="simulado-timer-text">${this.formatTime(this.timeRemaining)}</span> | |
| </div> | |
| <div class="simulado-timer-center"> | |
| <span>${answeredCount}/${totalCount} respondidas</span> | |
| </div> | |
| <div class="simulado-timer-right"> | |
| <button class="btn btn-sm btn-secondary" onclick="Simulado.toggleViewMode()"> | |
| ${this.viewMode === 'single' ? 'Ver todas' : 'Ver uma'} | |
| </button> | |
| <button class="btn btn-sm btn-primary" onclick="Simulado.confirmFinish()" id="simulado-finish-btn"> | |
| Finalizar | |
| </button> | |
| </div> | |
| </div> | |
| <div class="simulado-body"> | |
| <div class="simulado-nav" id="simulado-nav"> | |
| <div class="simulado-nav-title">Questoes</div> | |
| <div class="simulado-nav-grid"> | |
| ${navButtons} | |
| </div> | |
| <div class="simulado-nav-legend"> | |
| <span class="legend-item"><span class="legend-dot answered"></span> Respondida</span> | |
| <span class="legend-item"><span class="legend-dot current"></span> Atual</span> | |
| <span class="legend-item"><span class="legend-dot"></span> Pendente</span> | |
| </div> | |
| </div> | |
| <div class="simulado-content" id="simulado-content"> | |
| ${questionsHtml} | |
| ${this.viewMode === 'single' ? this.renderNavArrows() : ''} | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| renderSingleQuestion(index) { | |
| const q = this.questions[index]; | |
| if (!q) return ''; | |
| return this.renderExamQuestion(q, index); | |
| }, | |
| renderExamQuestion(q, index) { | |
| const token = Auth.getToken(); | |
| let enunciadoHtml = q.enunciado || ''; | |
| enunciadoHtml = enunciadoHtml.replace( | |
| /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi, | |
| (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` | |
| ); | |
| enunciadoHtml = enunciadoHtml.replace( | |
| /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi, | |
| (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}` | |
| ); | |
| const selectedAnswer = this.answers[q.id] || null; | |
| const alts = (q.alternativas || []).map(alt => { | |
| let altTexto = alt.texto || ''; | |
| const hasHtml = /<img\s|<br|<p\s|<div\s|<span\s/i.test(altTexto); | |
| if (hasHtml) { | |
| altTexto = altTexto.replace( | |
| /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi, | |
| (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` | |
| ); | |
| altTexto = altTexto.replace( | |
| /https?:\/\/r2\.seudominio\.com\/([^"'?\s]+)/gi, | |
| (match, path) => `/api/images/${encodeURIComponent(path)}?token=${token}` | |
| ); | |
| } else { | |
| altTexto = this.escapeHtml(altTexto); | |
| } | |
| const selected = selectedAnswer === alt.letra ? 'selected' : ''; | |
| return ` | |
| <div class="alternativa ${selected}" data-qid="${q.id}" data-letra="${alt.letra}" | |
| onclick="Simulado.selectAnswer(${q.id}, '${alt.letra}', this)"> | |
| <div class="alt-letter">${alt.letra}</div> | |
| <div class="alt-text">${altTexto}</div> | |
| </div> | |
| `; | |
| }).join(''); | |
| const yearBadge = q.year ? `<span style="font-size:12px;color:var(--text-sec);font-weight:400;"> (${this.escapeHtml(q.year)})</span>` : ''; | |
| const trackBadge = `<span class="simulado-track-badge">${this.escapeHtml(q.track)}</span>`; | |
| return ` | |
| <div class="question-card simulado-question" id="sim-q-${q.id}" data-index="${index}"> | |
| <div class="question-header"> | |
| <div class="question-number">${index + 1}</div> | |
| <h3>Questao ${index + 1} de ${this.questions.length}${yearBadge}</h3> | |
| ${trackBadge} | |
| </div> | |
| <div class="enunciado">${enunciadoHtml}</div> | |
| <div class="alternativas"> | |
| ${alts} | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| renderNavArrows() { | |
| const hasPrev = this.currentIndex > 0; | |
| const hasNext = this.currentIndex < this.questions.length - 1; | |
| return ` | |
| <div class="simulado-arrows"> | |
| <button class="btn btn-secondary" ${hasPrev ? '' : 'disabled'} onclick="Simulado.goToQuestion(${this.currentIndex - 1})"> | |
| ← Anterior | |
| </button> | |
| <button class="btn btn-secondary" ${hasNext ? '' : 'disabled'} onclick="Simulado.goToQuestion(${this.currentIndex + 1})"> | |
| Proxima → | |
| </button> | |
| </div> | |
| `; | |
| }, | |
| selectAnswer(qid, letra, el) { | |
| if (this.submitted) return; | |
| this.answers[qid] = letra; | |
| // Update UI | |
| const container = el.closest('.alternativas'); | |
| container.querySelectorAll('.alternativa').forEach(a => a.classList.remove('selected')); | |
| el.classList.add('selected'); | |
| // Update nav button | |
| this.updateNavButton(qid); | |
| this.updateProgress(); | |
| }, | |
| updateNavButton(qid) { | |
| const idx = this.questions.findIndex(q => q.id === qid); | |
| if (idx === -1) return; | |
| const navBtns = document.querySelectorAll('.simulado-nav-btn'); | |
| if (navBtns[idx]) { | |
| navBtns[idx].classList.add('answered'); | |
| } | |
| }, | |
| updateProgress() { | |
| const answeredCount = Object.keys(this.answers).length; | |
| const totalCount = this.questions.length; | |
| const center = document.querySelector('.simulado-timer-center span'); | |
| if (center) center.textContent = `${answeredCount}/${totalCount} respondidas`; | |
| }, | |
| goToQuestion(index) { | |
| if (index < 0 || index >= this.questions.length) return; | |
| this.currentIndex = index; | |
| if (this.viewMode === 'single') { | |
| const content = document.getElementById('simulado-content'); | |
| if (content) { | |
| content.innerHTML = this.renderSingleQuestion(index) + this.renderNavArrows(); | |
| } | |
| // Update nav highlights | |
| document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => { | |
| btn.classList.toggle('current', i === index); | |
| }); | |
| } else { | |
| // Scroll to question | |
| const el = document.querySelector(`.simulado-question[data-index="${index}"]`); | |
| if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' }); | |
| document.querySelectorAll('.simulado-nav-btn').forEach((btn, i) => { | |
| btn.classList.toggle('current', i === index); | |
| }); | |
| } | |
| }, | |
| toggleViewMode() { | |
| this.viewMode = this.viewMode === 'single' ? 'all' : 'single'; | |
| // Re-render the exam page content | |
| document.getElementById('app').innerHTML = this.renderExam(); | |
| }, | |
| // ===== TIMER ===== | |
| startTimer() { | |
| this.stopTimer(); | |
| this.timerInterval = setInterval(() => { | |
| this.timeRemaining--; | |
| const timerText = document.getElementById('simulado-timer-text'); | |
| if (timerText) { | |
| timerText.textContent = this.formatTime(this.timeRemaining); | |
| } | |
| // Warning colors | |
| const timerBar = document.getElementById('simulado-timer'); | |
| if (timerBar) { | |
| if (this.timeRemaining <= 60) { | |
| timerBar.classList.add('danger'); | |
| timerBar.classList.remove('warning'); | |
| } else if (this.timeRemaining <= 300) { | |
| timerBar.classList.add('warning'); | |
| timerBar.classList.remove('danger'); | |
| } | |
| } | |
| if (this.timeRemaining <= 0) { | |
| this.stopTimer(); | |
| this.finishExam(); | |
| } | |
| }, 1000); | |
| }, | |
| stopTimer() { | |
| if (this.timerInterval) { | |
| clearInterval(this.timerInterval); | |
| this.timerInterval = null; | |
| } | |
| }, | |
| formatTime(seconds) { | |
| if (seconds < 0) seconds = 0; | |
| const h = Math.floor(seconds / 3600); | |
| const m = Math.floor((seconds % 3600) / 60); | |
| const s = seconds % 60; | |
| if (h > 0) { | |
| return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; | |
| } | |
| return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`; | |
| }, | |
| // ===== FINISH ===== | |
| confirmFinish() { | |
| const answered = Object.keys(this.answers).length; | |
| const total = this.questions.length; | |
| const unanswered = total - answered; | |
| let msg = 'Deseja finalizar o simulado?'; | |
| if (unanswered > 0) { | |
| msg = `Voce ainda tem ${unanswered} questao(oes) sem resposta. Deseja finalizar mesmo assim?`; | |
| } | |
| if (confirm(msg)) { | |
| this.finishExam(); | |
| } | |
| }, | |
| async finishExam() { | |
| this.stopTimer(); | |
| this.submitted = true; | |
| const app = document.getElementById('app'); | |
| app.innerHTML = '<div class="loading"><div class="spinner"></div>Calculando resultado...</div>'; | |
| try { | |
| const result = await this.submitExam(); | |
| app.innerHTML = this.renderResults(result); | |
| } catch (e) { | |
| app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`; | |
| } | |
| }, | |
| // ===== RESULTS SCREEN ===== | |
| renderResults(result) { | |
| const { score, total, percentage, time_spent_seconds, details } = result; | |
| let colorClass = 'results-red'; | |
| if (percentage >= 70) colorClass = 'results-green'; | |
| else if (percentage >= 50) colorClass = 'results-yellow'; | |
| const timeStr = this.formatTime(time_spent_seconds); | |
| // Separate wrong answers for review | |
| const wrongAnswers = details.filter(d => !d.is_correct); | |
| let wrongHtml = ''; | |
| if (wrongAnswers.length > 0) { | |
| const wrongCards = wrongAnswers.map(d => { | |
| const q = this.questions.find(q => q.id === d.question_id); | |
| if (!q) return ''; | |
| const token = Auth.getToken(); | |
| let snippet = (q.enunciado || '').replace(/<[^>]+>/g, ''); | |
| snippet = snippet.length > 200 ? snippet.substring(0, 200) + '...' : snippet; | |
| // Process explanation | |
| let explanationHtml = ''; | |
| if (d.explanation && !d.explanation.includes('Carregando gabarito') && d.explanation.trim().length > 20) { | |
| let expText = d.explanation; | |
| expText = expText.replace( | |
| /src=["']https?:\/\/[^"']*\/([^"'\/]+\.(jpg|jpeg|png|gif|webp))[^"']*["']/gi, | |
| (match, filename) => `src="/api/images/${encodeURIComponent(filename)}?token=${token}"` | |
| ); | |
| expText = expText.replace(/color:\s*white/gi, 'color: #1a1a1a'); | |
| expText = expText.replace(/color:\s*#fff(fff)?/gi, 'color: #1a1a1a'); | |
| explanationHtml = `<div class="simulado-review-explanation">${expText}</div>`; | |
| } | |
| return ` | |
| <div class="simulado-review-card"> | |
| <div class="simulado-review-header"> | |
| <span class="simulado-review-track">${this.escapeHtml(q.track)}</span> | |
| </div> | |
| <p class="simulado-review-snippet">${this.escapeHtml(snippet)}</p> | |
| <div class="simulado-review-answers"> | |
| <span class="review-wrong">Sua resposta: ${this.escapeHtml(d.selected)}</span> | |
| <span class="review-correct">Correta: ${this.escapeHtml(d.correct)}</span> | |
| </div> | |
| ${explanationHtml} | |
| </div> | |
| `; | |
| }).join(''); | |
| wrongHtml = ` | |
| <div class="simulado-review-section"> | |
| <h3>Revisao de erros (${wrongAnswers.length})</h3> | |
| ${wrongCards} | |
| </div> | |
| `; | |
| } | |
| return ` | |
| <div class="container protected-content"> | |
| <div class="simulado-results"> | |
| <div class="simulado-results-header"> | |
| <h2>Resultado do Simulado</h2> | |
| </div> | |
| <div class="simulado-score-circle ${colorClass}"> | |
| <div class="score-percentage">${percentage}%</div> | |
| <div class="score-fraction">${score}/${total}</div> | |
| </div> | |
| <div class="simulado-results-stats"> | |
| <div class="results-stat"> | |
| <div class="results-stat-value">${score}</div> | |
| <div class="results-stat-label">Acertos</div> | |
| </div> | |
| <div class="results-stat"> | |
| <div class="results-stat-value">${total - score}</div> | |
| <div class="results-stat-label">Erros</div> | |
| </div> | |
| <div class="results-stat"> | |
| <div class="results-stat-value">${timeStr}</div> | |
| <div class="results-stat-label">Tempo</div> | |
| </div> | |
| </div> | |
| <div class="simulado-results-actions"> | |
| <button class="btn btn-primary" onclick="App.navigate('/simulado')">Novo Simulado</button> | |
| <button class="btn btn-secondary" onclick="App.navigate('/')">Voltar ao inicio</button> | |
| </div> | |
| ${wrongHtml} | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| // ===== CLEANUP ===== | |
| cleanup() { | |
| this.stopTimer(); | |
| }, | |
| escapeHtml(str) { | |
| if (!str) return ''; | |
| const div = document.createElement('div'); | |
| div.textContent = str; | |
| return div.innerHTML; | |
| } | |
| }; | |