(function () { const API = location.origin; const quizToken = (new URLSearchParams(location.search).get('t') || '').trim(); const SYSTEM_KINDS = ['student', 'group', 'branch', 'module']; const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS]; const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' }; const state = { quiz: null, questions: [], quizAssets: [], attempt: null, selection: new Map(), texts: new Map(), systemIds: new Map(), sugTimers: new Map(), code: '', timer: null, done: false, }; const RETRY_KEY = 'whatido_quiz_retry_' + quizToken; let retryTimer = null; function esc2(v) { return String(v == null ? '' : v) .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function at(v) { return esc2(v); } function thumb(p) { const path = String(p || ''); if (path.startsWith('/uploads/')) return '/uploads/thumb/' + path.slice('/uploads/'.length); return path; } function renderMd(text) { if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.render === 'function') { return WhatIDoMD.render(String(text || '')); } return esc2(text); } function renderMdInline(text) { if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.inline === 'function') { return WhatIDoMD.inline(String(text || '')); } return esc2(text); } function fileUrl(asset) { const name = String(asset.path || '').split('/').pop(); const play = asset.kind === 'audio' || asset.kind === 'video' ? '&play=1' : ''; return API + '/api/public-quizzes/files/' + encodeURIComponent(name) + '?x=1' + play; } function shuffleList(list) { const arr = Array.isArray(list) ? list.slice() : []; for (let i = arr.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [arr[i], arr[j]] = [arr[j], arr[i]]; } return arr; } function prepareQuestions(list) { const quiz = state.quiz || {}; let items = Array.isArray(list) ? list.slice() : []; if (quiz.shuffle_questions) { const pinned = items.filter(q => q.no_shuffle); const rest = items.filter(q => !q.no_shuffle); items = pinned.concat(shuffleList(rest)); } if (quiz.shuffle_options) { items = items.map(q => ({ ...q, options: shuffleList(q.options || []) })); } return items; } function toast(message, isError) { const el = document.getElementById('toast'); if (!el) return; el.textContent = message; el.className = 'toast show' + (isError ? ' error' : ''); clearTimeout(toast.t); toast.t = setTimeout(() => { el.className = 'toast'; }, 3200); } function retryUntil() { const min = Number(state.quiz && state.quiz.retry_cooldown_min) || 0; if (min <= 0) return 0; let raw = null; try { raw = localStorage.getItem(RETRY_KEY); } catch (e) { raw = null; } const at = parseInt(raw, 10); if (!Number.isFinite(at)) return 0; const until = at + min * 60000; if (Date.now() >= until) { try { localStorage.removeItem(RETRY_KEY); } catch (e) { /* ignore */ } return 0; } return until; } function markRetry() { if (!(Number(state.quiz && state.quiz.retry_cooldown_min) > 0)) return; try { localStorage.setItem(RETRY_KEY, String(Date.now())); } catch (e) { /* ignore */ } } function retryLeftText(until) { const left = Math.max(0, until - Date.now()); const min = Math.floor(left / 60000); const sec = Math.floor((left % 60000) / 1000); return `Повторно пройти можно через ${min} мин ${sec} сек`; } function stopRetryTimer() { if (retryTimer) clearInterval(retryTimer); retryTimer = null; } function startRetryTimer(until) { stopRetryTimer(); const tick = () => { const el = document.getElementById('qpRetryTimer'); if (!el) { stopRetryTimer(); return; } if (Date.now() >= until) { stopRetryTimer(); render(); return; } el.textContent = retryLeftText(until); }; tick(); retryTimer = setInterval(tick, 1000); } function assetsHtml(list) { if (!Array.isArray(list) || !list.length) return ''; const cards = list.map(a => { let inner; if (a.kind === 'image') { inner = `${at(a.original_name || '')}`; } else if (a.kind === 'audio') { inner = ``; } else if (a.kind === 'video') { inner = ``; } else { inner = `${esc2(a.original_name || 'Файл')}`; } return `
${inner}${a.caption ? `
${esc2(a.caption)}
` : ''}
`; }); return `
${cards.join('')}
`; } function isFree(kind) { return FREE_KINDS.includes(kind); } function isSystemKind(kind) { return SYSTEM_KINDS.includes(kind); } function systemAnswerHtml(q) { const value = state.texts.get(q.id) || ''; const picked = state.systemIds.get(q.id) || ''; const label = SYSTEM_LABELS[q.kind] || 'названия'; return `
`; } function freeAnswerHtml(q) { if (isSystemKind(q.kind)) return systemAnswerHtml(q); const value = state.texts.get(q.id) || ''; const hint = q.required !== false && q.min_length > 0 ? `
Минимум ${q.min_length} символов
` : ''; if (q.kind === 'text') { return `${hint}`; } if (q.kind === 'number') { return ``; } if (q.kind === 'date') { return ``; } return `${hint}`; } async function systemLookup(qid, kind, term) { const box = document.querySelector('[data-sug="' + qid + '"]'); if (!box) return; const text = String(term || '').trim(); if (!text) { box.hidden = true; box.innerHTML = ''; return; } try { const url = API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/options?field=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(text) + '&code=' + encodeURIComponent(state.code || ''); const res = await fetch(url); const data = await res.json().catch(() => ({})); if (!res.ok) { box.hidden = true; return; } const items = Array.isArray(data.items) ? data.items : []; box.innerHTML = items.length ? items.map(it => ``).join('') : '
Ничего не найдено
'; box.hidden = false; } catch (e) { box.hidden = true; } } function questionHtml(q, index) { const chosen = state.selection.get(q.id) || new Set(); let body; if (isFree(q.kind)) { body = freeAnswerHtml(q); } else if (q.kind === 'select') { body = ``; } else { const items = (q.options || []).map(o => { const checked = chosen.has(Number(o.id)) ? ' checked' : ''; const input = q.kind === 'multiple' ? `` : ``; return ``; }).join(''); body = `
${items}
`; } return `
${index + 1}${esc2(q.text)}
${q.description ? `
${renderMd(q.description)}
` : ''} ${assetsHtml(q.assets)}
${body}
`; } function introHtml() { const q = state.quiz; const isTest = q.kind === 'test'; const until = retryUntil(); return `
${q.cover_path ? `Обложка` : ''}
${esc2(q.title || (isTest ? 'Тест' : 'Опрос'))}
Вопросов: ${state.questions.length}${q.time_limit_min ? `Время: ${q.time_limit_min} мин` : ''}${q.retry_cooldown_min ? `Повтор: через ${q.retry_cooldown_min} мин` : ''}${isTest ? `${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}` : ''}
${q.description ? `
${renderMd(q.description)}
` : ''} ${assetsHtml(state.quizAssets)} ${q.requires_code ? `
Код выдает тьютор.
` : ''}
${until ? '' : ''} ${until ? `Вы уже прошли ${isTest ? 'этот тест' : 'этот опрос'} в этом браузере.` : (isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.')}
${until ? `
${esc2(retryLeftText(until))}
` : ''}
`; } function renderQuestions() { return `
${esc2(state.quiz.title || 'Опрос')}
Вопросов: ${state.questions.length}
Отвечено: 0 из ${state.questions.length}
${state.questions.map(questionHtml).join('')}
`; } function render() { const body = document.getElementById('qpBody'); if (!state.quiz) return; body.innerHTML = state.attempt ? renderQuestions() : introHtml(); if (state.attempt) { stopRetryTimer(); updateProgress(); const deadline = state.quiz.time_limit_min > 0 ? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000 : 0; startTimer(deadline); } else { const until = retryUntil(); if (until) startRetryTimer(until); else stopRetryTimer(); } } function updateProgress() { const el = document.getElementById('qpProgress'); if (!el) return; let done = 0; for (const q of state.questions) { if (isFree(q.kind)) { if (String(state.texts.get(q.id) || '').trim()) done++; } else if ((state.selection.get(q.id) || new Set()).size) { done++; } } el.textContent = String(done); } function startTimer(deadline) { stopTimer(); const el = document.getElementById('qzTimer'); if (!el || !deadline) return; el.hidden = false; const tick = () => { const left = Math.max(0, deadline - Date.now()); const min = Math.floor(left / 60000); const sec = Math.floor((left % 60000) / 1000); el.textContent = `Осталось: ${min}:${String(sec).padStart(2, '0')}`; el.classList.toggle('low', left < 60000); if (left <= 0) { stopTimer(); submit(true); } }; tick(); state.timer = setInterval(tick, 1000); } function stopTimer() { if (state.timer) clearInterval(state.timer); state.timer = null; } async function start() { const until = retryUntil(); if (until) { toast(retryLeftText(until), true); return; } const btn = document.querySelector('[data-act="start"]'); if (btn) btn.disabled = true; const codeInput = document.getElementById('qpAccessCode'); const code = codeInput ? codeInput.value.trim() : ''; try { const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/attempts', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось начать'); state.code = code; state.attempt = { id: data.attempt.id, started_at: data.attempt.started_at, anon_token: data.attempt.anon_token, }; if (data.quiz) { state.quiz = data.quiz.quiz || state.quiz; const fresh = data.quiz.questions; state.questions = Array.isArray(fresh) && fresh.length ? prepareQuestions(fresh) : state.questions; state.quizAssets = data.quiz.quiz_assets || state.quizAssets; } render(); window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (e) { toast(e.message, true); if (btn) btn.disabled = false; } } function fmtPts(v) { const n = Math.round(Number(v) * 100) / 100; return Number.isFinite(n) ? String(n) : '0'; } function resultItemHtml(r, num, isTest) { const local = state.questions.find(q => Number(q.id) === Number(r.question_id)); const kind = r.kind || (local && local.kind) || ''; const opts = !isFree(kind) && local && Array.isArray(local.options) ? local.options : []; const picked = new Set((r.option_ids || []).map(Number)); const right = new Set((r.correct_option_ids || []).map(Number)); const ok = r.is_correct === true; const bad = r.is_correct === false; const answer = r.text_answer ? String(r.text_answer) : ''; const max = Number(r.max_score) || 0; const markCls = ['qp-result-mark', ok ? 'ok' : (bad ? 'bad' : '')].filter(Boolean).join(' '); const mark = isTest ? `${ok ? 'Верно' : (bad ? 'Неверно' : 'Без оценки')}` : ''; const pts = isTest && max > 0 ? `${esc2(fmtPts(r.score))} / ${esc2(fmtPts(max))}` : ''; let body = ''; if (opts.length) { body = `
${opts.map(o => { const id = Number(o.id); const isPicked = picked.has(id); const isRight = right.has(id); const cls = !isTest ? (isPicked ? 'picked' : '') : (isRight ? 'ok' : (isPicked ? 'bad' : '')); const ic = !isTest ? (isPicked ? '•' : '') : (isRight ? '✓' : (isPicked ? '✕' : '')); const desc = o.description ? `
${renderMdInline(o.description)}
` : ''; const tag = isPicked ? 'ваш ответ' : ''; return `
${ic}${esc2(o.text || '')}${desc}${tag}
`; }).join('')}
`; } if (isFree(kind) || (!opts.length && answer)) { body += answer ? `
Ваш ответ: ${esc2(answer)}
` : '
Ответ не дан
'; } if (!body) body = '
Ответ не дан
'; return `
${num}${esc2(r.text || '')}${pts}${mark}
${body}
`; } function questionsWord(n) { const mod10 = n % 10; const mod100 = n % 100; if (mod10 === 1 && mod100 !== 11) return 'вопрос'; if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return 'вопроса'; return 'вопросов'; } function resultListHtml(result, isTest) { const list = Array.isArray(result.questions) ? result.questions : []; if (!list.length) return ''; const order = new Map(); state.questions.forEach((q, i) => order.set(Number(q.id), i)); const sorted = list .map((r, i) => ({ r, at: order.has(Number(r.question_id)) ? order.get(Number(r.question_id)) : list.length + i })) .sort((a, b) => a.at - b.at); const okCount = list.filter(r => r.is_correct === true).length; const badCount = list.filter(r => r.is_correct === false).length; const summary = isTest ? `${okCount ? `${okCount} верно` : ''}${badCount ? `${badCount} неверно` : ''}${list.length} ${questionsWord(list.length)}` : ''; return `
${isTest ? 'Разбор ответов' : 'Ваши ответы'}${summary}
${sorted.map((item, i) => resultItemHtml(item.r, i + 1, isTest)).join('')}
`; } function renderDone(data) { const isTest = state.quiz && state.quiz.kind === 'test'; const result = data && data.result ? data.result : null; const passText = result && result.passed === true ? 'Тест сдан' : (result && result.passed === false ? 'Тест не сдан' : ''); const grade = result && result.grade ? result.grade : null; const gradeHtml = grade ? `
${grade.image_path ? `` : ''}
${esc2(grade.label || '')}
` : ''; const hiddenAnswers = !!(result && result.answers_hidden); const hasMax = result && Number(result.max_score) > 0; const scoreHtml = isTest && result && hasMax ? `
${esc2(fmtPts(result.score))}/ ${esc2(fmtPts(result.max_score))} ${result.percent != null ? `${esc2(fmtPts(result.percent))}%` : ''} ${passText ? `${esc2(passText)}` : ''}
` : ''; const details = result ? resultListHtml(result, isTest) : ''; let hint = 'Ответы сохранены.'; if (isTest) { if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.'; else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.'; } const until = retryUntil(); const failed = !!(isTest && result && result.passed === false); document.getElementById('qpBody').innerHTML = `
${failed ? '✕' : '✓'}
${isTest ? 'Тест завершён' : 'Спасибо!'}
${scoreHtml} ${gradeHtml}

${esc2(hint)}

${details}
${until ? `${esc2(retryLeftText(until))}` : ''}
`; } async function submit(auto) { if (!state.attempt) return; if (!auto) { for (let i = 0; i < state.questions.length; i++) { const q = state.questions[i]; if (q.required === false) continue; const answered = isFree(q.kind) ? !!String(state.texts.get(q.id) || '').trim() : !!(state.selection.get(q.id) || new Set()).size; if (!answered) { toast(`Вопрос ${i + 1}: ответ обязателен`, true); const qEl = document.querySelectorAll('.qz-q')[i]; if (qEl) qEl.scrollIntoView({ behavior: 'smooth', block: 'center' }); return; } } for (let i = 0; i < state.questions.length; i++) { const q = state.questions[i]; if (!isFree(q.kind) || q.required === false || !(q.min_length > 0)) continue; const value = String(state.texts.get(q.id) || '').trim(); if (value.length < q.min_length) { toast(`Вопрос ${i + 1}: минимум ${q.min_length} символов`, true); return; } } } const btn = document.querySelector('[data-act="submit"]'); if (btn) btn.disabled = true; const answers = state.questions.map(q => ({ question_id: q.id, option_ids: isFree(q.kind) ? [] : [...(state.selection.get(q.id) || new Set())], text: isFree(q.kind) ? (state.texts.get(q.id) || '') : '', answer_id: isSystemKind(q.kind) ? (state.systemIds.get(q.id) || null) : null, })); try { const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken) + '/attempts/' + state.attempt.id, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: state.attempt.anon_token, answers, time_up: auto === true }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы'); stopTimer(); state.done = true; markRetry(); renderDone(data); } catch (e) { toast(e.message, true); if (btn) btn.disabled = false; } } function bind() { document.addEventListener('change', e => { const el = e.target; if (el.tagName === 'SELECT' && el.dataset.q) { const qid = Number(el.dataset.q); const oid = Number(el.value); state.selection.set(qid, oid ? new Set([oid]) : new Set()); updateProgress(); return; } if (el.dataset.q && el.dataset.opt) { const qid = Number(el.dataset.q); const oid = Number(el.dataset.opt); let set = state.selection.get(qid); if (!set) { set = new Set(); state.selection.set(qid, set); } if (el.type === 'radio') { set.clear(); set.add(oid); } else if (el.checked) set.add(oid); else set.delete(oid); updateProgress(); } }); document.addEventListener('input', e => { const el = e.target; if (el.dataset.qtext) { const qid = Number(el.dataset.qtext); state.texts.set(qid, el.value); updateProgress(); if (el.dataset.qsys) { state.systemIds.delete(qid); const kind = el.dataset.qsys; clearTimeout(state.sugTimers.get(qid)); state.sugTimers.set(qid, setTimeout(() => systemLookup(qid, kind, el.value), 250)); } } }); document.addEventListener('click', e => { const sug = e.target.closest('[data-sug-id]'); if (sug) { e.preventDefault(); const qid = Number(sug.dataset.sugQ); const name = sug.dataset.sugName || ''; state.systemIds.set(qid, Number(sug.dataset.sugId)); state.texts.set(qid, name); const input = document.querySelector('[data-qsys][data-qtext="' + qid + '"]'); if (input) input.value = name; const box = document.querySelector('[data-sug="' + qid + '"]'); if (box) { box.hidden = true; box.innerHTML = ''; } updateProgress(); return; } if (!e.target.closest('.qz-suggest-wrap')) { document.querySelectorAll('.qz-suggest').forEach(box => { box.hidden = true; }); } const act = e.target.closest('[data-act]'); if (act) { if (act.dataset.act === 'start') { e.preventDefault(); start(); return; } if (act.dataset.act === 'submit') { e.preventDefault(); submit(false); return; } if (act.dataset.act === 'again') { e.preventDefault(); location.reload(); return; } } const themeBtn = e.target.closest('[data-theme-toggle]'); if (themeBtn) { e.preventDefault(); if (window.WhatIDoTheme) WhatIDoTheme.next(); return; } const img = e.target.closest('[data-img]'); if (img) { e.preventDefault(); const modal = document.getElementById('imgModal'); document.getElementById('imgModalSrc').src = img.dataset.img; modal.classList.add('open'); } }); document.getElementById('imgModal').addEventListener('click', e => { if (e.target.id !== 'imgModalSrc') e.target.classList.remove('open'); }); window.addEventListener('beforeunload', e => { if (!state.attempt || state.done) return; e.preventDefault(); e.returnValue = ''; }); } async function init() { if (!/^[a-f0-9]{32}$/i.test(quizToken)) { document.getElementById('qpBody').innerHTML = '
Неверная ссылка
'; return; } bind(); try { const res = await fetch(API + '/api/public-quizzes/' + encodeURIComponent(quizToken)); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Тест не найден'); state.quiz = data.quiz; state.questions = prepareQuestions(data.questions || []); state.quizAssets = data.quiz_assets || []; const kindLabel = state.quiz.kind === 'survey' ? 'Опрос' : 'Тест'; document.title = (state.quiz.title || kindLabel) + ' — ' + kindLabel.toLowerCase(); const brand = document.getElementById('qpBrand'); if (brand) brand.textContent = kindLabel; render(); } catch (e) { document.getElementById('qpBody').innerHTML = `
${esc2(e.message)}
`; } } init(); })();