${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 = `
`
: '';
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 = '