Download static/js/app.js from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 20.4 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/app.js
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/static/js/app.js
-
curl -L -o app.js https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/app.js
20.4 kB
| // ===== Main SPA Router ===== | |
| const App = { | |
| topicsCache: null, | |
| _hashListenerAttached: false, | |
| async init(skipValidation) { | |
| if (!Auth.getToken()) { | |
| this.showLogin(); | |
| return; | |
| } | |
| // Skip server validation when called right after login (token is fresh) | |
| if (!skipValidation) { | |
| try { | |
| const res = await fetch('/api/auth/me', { headers: Auth.headers() }); | |
| if (!res.ok) throw new Error('Token invalid'); | |
| } catch (e) { | |
| Auth.clearSession(); | |
| this.showLogin(); | |
| return; | |
| } | |
| } | |
| // Protection.init() must never break the app | |
| try { Protection.init(); } catch(e) { console.warn('[App] Protection.init error:', e); } | |
| try { Heartbeat.init(); } catch(e) { console.warn('[App] Heartbeat.init error:', e); } | |
| this.renderHeader(); | |
| this.handleRoute(); | |
| if (!this._hashListenerAttached) { | |
| this._hashListenerAttached = true; | |
| window.addEventListener('hashchange', () => this.handleRoute()); | |
| } | |
| }, | |
| showLogin() { | |
| document.getElementById('app').innerHTML = ` | |
| <div class="login-container"> | |
| <div class="login-card"> | |
| <h1>MedMembers OFT 2026</h1> | |
| <p class="subtitle">Banco de Questoes - Acesso Restrito</p> | |
| <div class="login-error" id="login-error"></div> | |
| <form onsubmit="App.handleLogin(event)"> | |
| <div class="form-group"> | |
| <label>Email</label> | |
| <input type="email" id="login-email" required autocomplete="email" placeholder="seu@email.com"> | |
| </div> | |
| <div class="form-group"> | |
| <label>Senha</label> | |
| <input type="password" id="login-password" required autocomplete="current-password" placeholder="Sua senha"> | |
| </div> | |
| <button type="submit" class="btn btn-primary" id="login-btn">Entrar</button> | |
| </form> | |
| <a class="back-to-login" style="margin-top:16px;color:var(--primary);cursor:pointer;" onclick="App.showForgotPassword()">Esqueci minha senha</a> | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| async handleLogin(e) { | |
| e.preventDefault(); | |
| const email = document.getElementById('login-email').value; | |
| const password = document.getElementById('login-password').value; | |
| const btn = document.getElementById('login-btn'); | |
| const errorEl = document.getElementById('login-error'); | |
| btn.disabled = true; | |
| btn.textContent = 'Entrando...'; | |
| errorEl.style.display = 'none'; | |
| try { | |
| await Auth.login(email, password); | |
| // Use replaceState to avoid hashchange firing | |
| history.replaceState(null, '', '#/'); | |
| await this.init(true); // skip re-validation, token is fresh | |
| } catch (err) { | |
| errorEl.textContent = err.message; | |
| errorEl.style.display = 'block'; | |
| btn.disabled = false; | |
| btn.textContent = 'Entrar'; | |
| } | |
| }, | |
| renderHeader() { | |
| const user = Auth.getUser(); | |
| const header = document.getElementById('app-header'); | |
| if (!header) { | |
| const h = document.createElement('header'); | |
| h.className = 'app-header'; | |
| h.id = 'app-header'; | |
| h.innerHTML = ` | |
| <span class="logo" onclick="App.navigate('/')"><span class="brand-text">MedMembers OFT 2026</span></span> | |
| <div class="user-menu"> | |
| <button class="btn btn-secondary btn-sm" onclick="App.navigate('/')" title="Banco de Questoes">📝 Questoes</button> | |
| <button class="btn btn-secondary btn-sm" onclick="App.navigate('/simulado')" title="Simulado">🎯 Simulado</button> | |
| <button class="btn btn-secondary btn-sm" onclick="App.navigate('/stats')" title="Estatisticas">📊 Estatisticas</button> | |
| ${user.role === 'admin' ? '<button class="btn btn-secondary btn-sm" onclick="App.navigate(\'/admin\')">Admin</button>' : ''} | |
| <span class="user-email">${this.escapeHtml(user.email)}</span> | |
| <button class="btn btn-sm" style="background:#f0f0f0" onclick="Auth.logout()">Sair</button> | |
| </div> | |
| `; | |
| document.body.insertBefore(h, document.getElementById('app')); | |
| } | |
| }, | |
| async handleRoute() { | |
| const hash = window.location.hash.slice(1) || '/'; | |
| const app = document.getElementById('app'); | |
| app.innerHTML = '<div class="loading"><div class="spinner"></div>Carregando...</div>'; | |
| try { | |
| // Clean up simulado timer when navigating away | |
| if (!hash.startsWith('/simulado')) { | |
| Simulado.cleanup(); | |
| } | |
| if (hash === '/' || hash === '') { | |
| await this.showTopics(); | |
| } else if (hash.startsWith('/topic/')) { | |
| const parts = hash.split('?'); | |
| const slug = parts[0].replace('/topic/', ''); | |
| const params = new URLSearchParams(parts[1] || ''); | |
| const page = parseInt(params.get('page')) || 1; | |
| const year = params.get('year') || ''; | |
| await this.showQuestions(slug, page, year); | |
| } else if (hash === '/simulado') { | |
| await this.showSimuladoConfig(); | |
| } else if (hash === '/simulado/exam') { | |
| this.showSimuladoExam(); | |
| } else if (hash === '/stats') { | |
| await this.showStats(); | |
| } else if (hash === '/admin') { | |
| await this.showAdmin(); | |
| } else { | |
| app.innerHTML = '<div class="container"><h2>Pagina nao encontrada</h2></div>'; | |
| } | |
| } catch (e) { | |
| console.error('[App] handleRoute error:', e); | |
| // Only clear session on explicit 401 HTTP status, not on generic errors | |
| if (e.message === 'HTTP 401') { | |
| Auth.clearSession(); | |
| this.showLogin(); | |
| return; | |
| } | |
| app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`; | |
| } | |
| try { Protection.updateWatermark(); } catch(e) {} | |
| window.scrollTo(0, 0); | |
| }, | |
| async showTopics() { | |
| if (!this.topicsCache) { | |
| this.topicsCache = await Questions.loadTopics(); | |
| } | |
| document.getElementById('app').innerHTML = Questions.renderTopicsPage(this.topicsCache); | |
| }, | |
| async showQuestions(slug, page, year) { | |
| if (!this.topicsCache) { | |
| this.topicsCache = await Questions.loadTopics(); | |
| } | |
| const topic = this.topicsCache.find(t => t.slug === slug); | |
| const topicName = topic ? topic.name : slug; | |
| const [data, years] = await Promise.all([ | |
| Questions.loadQuestions(slug, page, year), | |
| Questions.loadYears() | |
| ]); | |
| document.getElementById('app').innerHTML = Questions.renderQuestionsPage(data, topicName, slug, year, years); | |
| }, | |
| async showSimuladoConfig() { | |
| document.getElementById('app').innerHTML = await Simulado.renderConfig(); | |
| }, | |
| showSimuladoExam() { | |
| document.getElementById('app').innerHTML = Simulado.renderExam(); | |
| }, | |
| async showAdmin() { | |
| document.getElementById('app').innerHTML = await Admin.render(); | |
| }, | |
| async showStats() { | |
| const app = document.getElementById('app'); | |
| try { | |
| const [statsRes, historyRes] = await Promise.all([ | |
| fetch('/api/user/stats', { headers: Auth.headers() }), | |
| fetch('/api/user/history?page=1&per_page=15', { headers: Auth.headers() }) | |
| ]); | |
| if (!statsRes.ok || !historyRes.ok) throw new Error('Erro ao carregar estatisticas'); | |
| const stats = await statsRes.json(); | |
| const history = await historyRes.json(); | |
| let html = ` | |
| <div class="container protected-content"> | |
| <div class="question-nav"> | |
| <a class="back-btn" onclick="App.navigate('/')">← Voltar</a> | |
| <h2>Suas Estatisticas</h2> | |
| </div> | |
| <div class="stats-overview"> | |
| <div class="stats-big-card"> | |
| <div class="stats-big-number ${stats.accuracy >= 70 ? 'stats-good' : stats.accuracy >= 50 ? 'stats-ok' : 'stats-low'}">${stats.accuracy}%</div> | |
| <div class="stats-big-label">Aproveitamento Geral</div> | |
| </div> | |
| <div class="stats-summary-cards"> | |
| <div class="stat-card"> | |
| <div class="stat-value">${stats.total_answered}</div> | |
| <div class="stat-label">Respondidas</div> | |
| </div> | |
| <div class="stat-card"> | |
| <div class="stat-value" style="color:var(--correct)">${stats.total_correct}</div> | |
| <div class="stat-label">Corretas</div> | |
| </div> | |
| <div class="stat-card"> | |
| <div class="stat-value" style="color:var(--wrong)">${stats.total_answered - stats.total_correct}</div> | |
| <div class="stat-label">Erradas</div> | |
| </div> | |
| </div> | |
| </div> | |
| `; | |
| // Per-track bar chart | |
| if (stats.tracks && stats.tracks.length > 0) { | |
| html += '<h3 class="stats-section-title">Desempenho por Topico</h3>'; | |
| html += '<div class="stats-tracks">'; | |
| for (const t of stats.tracks) { | |
| const barColor = t.percentage >= 70 ? 'var(--correct)' : t.percentage >= 50 ? 'var(--accent)' : 'var(--wrong)'; | |
| html += ` | |
| <div class="stats-track-row"> | |
| <div class="stats-track-name">${this.escapeHtml(t.track)}</div> | |
| <div class="stats-track-bar-wrap"> | |
| <div class="stats-track-bar" style="width:${Math.max(t.percentage, 2)}%;background:${barColor}"></div> | |
| </div> | |
| <div class="stats-track-pct">${t.percentage}%</div> | |
| <div class="stats-track-count">${t.correct}/${t.total}</div> | |
| </div> | |
| `; | |
| } | |
| html += '</div>'; | |
| } | |
| // Recent history | |
| if (history.history && history.history.length > 0) { | |
| html += '<h3 class="stats-section-title">Historico Recente</h3>'; | |
| html += '<div class="stats-history">'; | |
| for (const h of history.history) { | |
| const icon = h.is_correct | |
| ? '<span class="answer-badge answer-badge-correct">✓</span>' | |
| : '<span class="answer-badge answer-badge-wrong">✗</span>'; | |
| const date = h.answered_at ? new Date(h.answered_at + 'Z').toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' }) : ''; | |
| html += ` | |
| <div class="stats-history-item" onclick="App.navigate('/topic/${this.escapeHtml(h.track_slug)}')"> | |
| ${icon} | |
| <div class="stats-history-info"> | |
| <div class="stats-history-track">${this.escapeHtml(h.track)} - Q${h.numero}</div> | |
| <div class="stats-history-snippet">${this.escapeHtml(h.snippet)}</div> | |
| </div> | |
| <div class="stats-history-meta"> | |
| <span class="stats-history-answer">Resp: ${h.selected_answer} | Gab: ${h.correct_answer}</span> | |
| <span class="stats-history-date">${date}</span> | |
| </div> | |
| </div> | |
| `; | |
| } | |
| html += '</div>'; | |
| } else { | |
| html += '<p class="page-subtitle" style="margin-top:24px">Nenhuma questao respondida ainda. Comece respondendo questoes para ver suas estatisticas!</p>'; | |
| } | |
| html += '</div>'; | |
| app.innerHTML = html; | |
| } catch (e) { | |
| app.innerHTML = `<div class="container"><h2>Erro</h2><p>${this.escapeHtml(e.message)}</p></div>`; | |
| } | |
| }, | |
| navigate(path) { | |
| window.location.hash = '#' + path; | |
| }, | |
| escapeHtml(str) { | |
| if (!str) return ''; | |
| const div = document.createElement('div'); | |
| div.textContent = str; | |
| return div.innerHTML; | |
| }, | |
| // ===== Forgot Password Flow ===== | |
| _forgotEmail: '', | |
| showForgotPassword() { | |
| document.getElementById('app').innerHTML = ` | |
| <div class="forgot-container"> | |
| <div class="forgot-card"> | |
| <h1>Recuperar Senha</h1> | |
| <div class="step-indicator"> | |
| <div class="step-dot active" id="dot-1"></div> | |
| <div class="step-dot" id="dot-2"></div> | |
| <div class="step-dot" id="dot-3"></div> | |
| </div> | |
| <div class="forgot-error" id="forgot-error"></div> | |
| <div class="forgot-success" id="forgot-success"></div> | |
| <div class="forgot-step active" id="forgot-step-1"> | |
| <p class="subtitle">Informe seu email para receber o codigo de verificacao.</p> | |
| <form onsubmit="App.forgotSendCode(event)"> | |
| <div class="form-group"><label>Email</label><input type="email" id="forgot-email" required autocomplete="email" placeholder="seu@email.com"></div> | |
| <button type="submit" class="btn btn-primary" id="forgot-send-btn">Enviar codigo</button> | |
| </form> | |
| </div> | |
| <div class="forgot-step" id="forgot-step-2"> | |
| <p class="subtitle">Digite o codigo de 6 digitos enviado para seu email.</p> | |
| <form onsubmit="App.forgotVerifyCode(event)"> | |
| <div class="form-group"><label>Codigo de verificacao</label><input type="text" id="forgot-code" required maxlength="6" pattern="[0-9]{6}" placeholder="000000" class="code-input" autocomplete="one-time-code"></div> | |
| <button type="submit" class="btn btn-primary" id="forgot-verify-btn">Verificar</button> | |
| </form> | |
| </div> | |
| <div class="forgot-step" id="forgot-step-3"> | |
| <p class="subtitle">Escolha sua nova senha.</p> | |
| <form onsubmit="App.forgotResetPassword(event)"> | |
| <div class="form-group"><label>Nova senha</label><input type="password" id="forgot-new-pass" required minlength="6" placeholder="Minimo 6 caracteres" autocomplete="new-password"></div> | |
| <div class="form-group"><label>Confirmar nova senha</label><input type="password" id="forgot-confirm-pass" required minlength="6" placeholder="Repita a nova senha" autocomplete="new-password"></div> | |
| <button type="submit" class="btn btn-primary" id="forgot-reset-btn">Redefinir senha</button> | |
| </form> | |
| </div> | |
| <a class="back-to-login" onclick="App.showLogin()">Voltar ao login</a> | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| _forgotShowError(msg) { | |
| const el = document.getElementById('forgot-error'); | |
| el.textContent = msg; el.style.display = 'block'; | |
| const s = document.getElementById('forgot-success'); | |
| if (s) s.style.display = 'none'; | |
| }, | |
| _forgotShowSuccess(msg) { | |
| const el = document.getElementById('forgot-success'); | |
| el.textContent = msg; el.style.display = 'block'; | |
| const e = document.getElementById('forgot-error'); | |
| if (e) e.style.display = 'none'; | |
| }, | |
| _forgotGoToStep(step) { | |
| document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active')); | |
| document.getElementById(`forgot-step-${step}`).classList.add('active'); | |
| for (let i = 1; i <= 3; i++) { | |
| const dot = document.getElementById(`dot-${i}`); | |
| dot.classList.remove('active', 'done'); | |
| if (i < step) dot.classList.add('done'); | |
| else if (i === step) dot.classList.add('active'); | |
| } | |
| const err = document.getElementById('forgot-error'); | |
| const suc = document.getElementById('forgot-success'); | |
| if (err) err.style.display = 'none'; | |
| if (suc) suc.style.display = 'none'; | |
| }, | |
| async forgotSendCode(e) { | |
| e.preventDefault(); | |
| const email = document.getElementById('forgot-email').value.trim(); | |
| const btn = document.getElementById('forgot-send-btn'); | |
| btn.disabled = true; btn.textContent = 'Enviando...'; | |
| try { | |
| const res = await fetch('/api/auth/forgot-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email }) }); | |
| const data = await res.json(); | |
| if (!res.ok) { this._forgotShowError(data.error || 'Erro ao enviar codigo'); btn.disabled = false; btn.textContent = 'Enviar codigo'; return; } | |
| this._forgotEmail = email; | |
| this._forgotGoToStep(2); | |
| this._forgotShowSuccess('Se o email estiver cadastrado, voce recebera um codigo de verificacao.'); | |
| } catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Enviar codigo'; } | |
| }, | |
| async forgotVerifyCode(e) { | |
| e.preventDefault(); | |
| const code = document.getElementById('forgot-code').value.trim(); | |
| if (code.length !== 6 || !/^\d{6}$/.test(code)) { this._forgotShowError('O codigo deve ter 6 digitos numericos.'); return; } | |
| this._forgotCode = code; | |
| this._forgotGoToStep(3); | |
| }, | |
| async forgotResetPassword(e) { | |
| e.preventDefault(); | |
| const newPass = document.getElementById('forgot-new-pass').value; | |
| const confirmPass = document.getElementById('forgot-confirm-pass').value; | |
| const btn = document.getElementById('forgot-reset-btn'); | |
| if (newPass !== confirmPass) { this._forgotShowError('As senhas nao coincidem.'); return; } | |
| if (newPass.length < 6) { this._forgotShowError('A senha deve ter no minimo 6 caracteres.'); return; } | |
| btn.disabled = true; btn.textContent = 'Redefinindo...'; | |
| try { | |
| const res = await fetch('/api/auth/reset-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: this._forgotEmail, code: this._forgotCode, new_password: newPass }) }); | |
| const data = await res.json(); | |
| if (!res.ok) { this._forgotShowError(data.error || 'Erro ao redefinir senha'); btn.disabled = false; btn.textContent = 'Redefinir senha'; return; } | |
| document.querySelectorAll('.forgot-step').forEach(el => el.classList.remove('active')); | |
| for (let i = 1; i <= 3; i++) { document.getElementById(`dot-${i}`).classList.remove('active'); document.getElementById(`dot-${i}`).classList.add('done'); } | |
| this._forgotShowSuccess('Senha redefinida com sucesso! Redirecionando para o login...'); | |
| setTimeout(() => this.showLogin(), 2500); | |
| } catch (err) { this._forgotShowError('Erro de conexao.'); btn.disabled = false; btn.textContent = 'Redefinir senha'; } | |
| } | |
| }; | |
| // Boot | |
| document.addEventListener('DOMContentLoaded', () => App.init()); | |