(function () {
const API = location.origin;
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
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_' + (Number.isInteger(quizId) ? quizId : '');
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 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 = ` `;
} 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/' + quizId + '/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 => `${esc2(it.name)} ${it.sub ? `${esc2(it.sub)} ` : ''} `).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 = `
— выберите —
${(q.options || []).map(o => `${esc2(o.text)} `).join('')}
`;
} else {
const items = (q.options || []).map(o => {
const checked = chosen.has(Number(o.id)) ? ' checked' : '';
const input = q.kind === 'multiple'
? ` `
: ` `;
return `${input}${esc2(o.text)}${o.description ? `${renderMdInline(o.description)}
` : ''}${assetsHtml(o.assets)} `;
}).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/' + quizId + '/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;
state.questions = data.quiz.questions || 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 renderDone(data) {
const isTest = state.quiz && state.quiz.kind === 'test';
const result = data && data.result ? data.result : null;
const score = result ? `${result.score} / ${result.max_score} (${result.percent}%)` : '';
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 details = result && Array.isArray(result.questions) && result.questions.length
? `${result.questions.map(q => {
const ok = q.is_correct === true;
const bad = q.is_correct === false;
return `
${esc2(q.text || '')}
${ok ? 'Верно' : (bad ? 'Неверно' : 'Ответ сохранён')}${q.max_score ? ` · ${q.score} / ${q.max_score}` : ''}
`;
}).join('')}
`
: '';
let hint = 'Ответы сохранены.';
if (isTest) {
if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.';
else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.';
}
const until = retryUntil();
document.getElementById('qpBody').innerHTML = `
${isTest && result && result.passed === false ? '•' : '✓'}
${isTest ? 'Тест завершён' : 'Спасибо!'}
${isTest && score ? `
${esc2(score)} ${passText ? ` · ${esc2(passText)}` : ''}
` : ''}
${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/' + quizId + '/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 (!Number.isInteger(quizId) || quizId < 1) {
document.getElementById('qpBody').innerHTML = 'Неверная ссылка
';
return;
}
bind();
try {
const res = await fetch(API + '/api/public-quizzes/' + quizId);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Тест не найден');
state.quiz = data.quiz;
state.questions = 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();
})();