(function () {
const FREE_KINDS = ['line', 'text', 'number', 'date'];
const params = new URLSearchParams(location.search);
const quizId = parseInt(params.get('id'), 10);
const state = {
quiz: null,
questions: [],
quizAssets: [],
attempt: null,
selection: new Map(),
texts: new Map(),
timer: null,
result: null,
revealed: false,
tab: params.get('tab') === 'stats' ? 'stats' : params.get('tab') === 'attempts' ? 'attempts' : 'take',
};
function at(s) {
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
}
function fileUrl(asset) {
const name = String(asset.path || '').split('/').pop();
const play = asset.kind === 'audio' || asset.kind === 'video' ? '&play=1' : '';
return API + '/api/quizzes/files/' + encodeURIComponent(name) + '?token=' + encodeURIComponent(token || '') + play;
}
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 = ` ${esc(a.original_name || 'Файл')}`;
}
return `
${inner}${a.caption ? `
${esc(a.caption)}
` : ''}
`;
});
return `${cards.join('')}
`;
}
function shuffle(list) {
const arr = list.slice();
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
return arr;
}
function kindLabel(kind) {
return kind === 'survey' ? 'Опрос' : 'Тест';
}
function renderMd(text) {
if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.render === 'function') {
return WhatIDoMD.render(String(text || ''));
}
return esc(text);
}
function renderHead() {
const q = state.quiz;
const parts = [
``,
q.cover_path
? `
)})
`
: '',
`
`,
`
${esc(q.title || 'Без названия')}
`,
`
`,
`${kindLabel(q.kind)}`,
`Вопросов: ${state.questions.length}`,
q.author_name ? `Автор: ${esc(q.author_name)}` : '',
q.max_attempts != null ? `Попыток: ${q.max_attempts}` : '',
q.time_limit_min ? `Время: ${q.time_limit_min} мин` : '',
q.kind === 'test' ? `Порог: ${q.pass_percent}%` : '',
`
`,
`
`,
`${q.is_published ? 'Опубликован' : 'Черновик'}`,
state.quiz.can_edit ? 'Редактирование доступно' : '',
`
`,
q.description ? `
${renderMd(q.description)}
` : '',
`
`,
`
`,
];
if (state.quizAssets.length) {
parts.push(`Материалы
${assetsHtml(state.quizAssets)}
`);
}
const head = document.getElementById('qzHead');
head.innerHTML = parts.filter(Boolean).join('');
renderIcons();
}
function renderTabs() {
const wrap = document.getElementById('qzTabs');
wrap.hidden = false;
document.getElementById('qzStatsTab').hidden = !state.quiz.can_edit;
wrap.querySelectorAll('.qz-tab').forEach(btn => {
btn.classList.toggle('on', btn.dataset.tab === state.tab);
});
}
function takeIntroHtml() {
const q = state.quiz;
if (!q.can_take && state.quiz.attempts_left === 0) {
return ``;
}
if (!q.is_published) {
return 'Тест не опубликован. Пройти его может только автор после публикации.
';
}
return `
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
${q.time_limit_min ? ` На прохождение отводится ${q.time_limit_min} мин.` : ''}
`;
}
function isFree(kind) {
return FREE_KINDS.includes(kind);
}
function freeAnswerHtml(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}`;
}
function questionTakeHtml(q, index) {
const opts = q.options || [];
const chosen = state.selection.get(q.id) || new Set();
let body;
if (isFree(q.kind)) {
body = freeAnswerHtml(q);
} else if (q.kind === 'select') {
body = `${opts.map(o => o.description ? `${esc(o.text)} — ${esc(o.description)}
` : '').join('')}`;
} else {
const items = opts.map(o => {
const checked = chosen.has(Number(o.id)) ? ' checked' : '';
const input = q.kind === 'multiple'
? ``
: ``;
return ``;
}).join('');
body = `${items}
`;
}
return `
${index + 1}
${esc(q.text)}
${q.description ? `${esc(q.description)}
` : ''}
${assetsHtml(q.assets)}
${body}
`;
}
function renderTake() {
const body = document.getElementById('qzBody');
if (!state.attempt) {
body.innerHTML = takeIntroHtml();
renderIcons();
return;
}
const list = state.questions.map(questionTakeHtml).join('');
const deadline = state.quiz.time_limit_min > 0
? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000
: 0;
body.innerHTML = `
—
Отвечено: 0 из ${state.questions.length}
${list}
`;
renderIcons();
updateProgress();
startTimer(deadline);
}
function updateProgress() {
const el = document.getElementById('qzProgress');
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;
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;
}
function renderResult() {
const body = document.getElementById('qzBody');
const attempt = state.attempt;
if (!attempt) return;
const pct = Number(attempt.percent || 0);
const head = `
${kindLabel(state.quiz.kind)} · ${fmtDateTime(attempt.finished_at || attempt.started_at)}
${state.quiz.kind === 'test'
? `
${Number(attempt.score || 0).toFixed(2)} из ${Number(attempt.max_score || 0).toFixed(2)} · ${pct.toFixed(1)}%
${attempt.passed ? 'Сдано' : 'Не сдано'}
`
: '
Ответы сохранены. Опрос не оценивается.
'}
`;
let details = '';
if (state.result && Array.isArray(state.result.questions)) {
details = state.result.questions.map((r, i) => {
const mark = r.is_correct === null ? '' : r.is_correct
? 'верно'
: 'неверно';
const local = state.questions.find(q => Number(q.id) === Number(r.question_id));
const picked = (r.option_ids || [])
.map(id => (local && local.options || []).find(o => Number(o.id) === Number(id)))
.filter(Boolean)
.map(o => o.text);
const pickedHtml = picked.length ? `Ответ: ${esc(picked.join(', '))}
` : '';
return `
${i + 1}${esc(r.text || '')}
${mark}
${state.quiz.kind === 'test' && r.max_score ? `${Number(r.score).toFixed(2)} / ${Number(r.max_score).toFixed(2)}` : ''}
${pickedHtml}
${r.text_answer ? `Ответ: ${esc(r.text_answer)}
` : ''}
`;
}).join('');
} else if (state.quiz.kind === 'test') {
details = 'Автор теста скрыл разбор ответов.
';
}
body.innerHTML = head + details;
renderIcons();
}
function renderAttemptDetail() {
const body = document.getElementById('qzBody');
const data = state.attemptDetail;
if (!data) return;
const a = data.attempt;
const pct = Number(a.percent || 0);
const head = `
${esc(a.user_name || '')} · ${fmtDateTime(a.finished_at || a.started_at)}
${state.quiz.kind === 'test'
? `
${Number(a.score).toFixed(2)} из ${Number(a.max_score).toFixed(2)} · ${pct.toFixed(1)}%
`
: '
Опрос не оценивается.
'}
`;
const rows = (data.answers || []).map((row, i) => {
const q = row.question;
const selected = new Set((row.option_ids || []).map(Number));
const opts = q && q.options
? q.options.map(o => {
const okClass = data.revealed ? (o.is_correct ? ' ok' : selected.has(Number(o.id)) ? ' bad' : '') : (selected.has(Number(o.id)) ? ' ok' : '');
const tag = data.revealed && o.is_correct ? ' ✓' : '';
return `${esc(o.text)}${tag}${data.revealed && o.weight ? `вес ${o.weight}` : ''}
`;
}).join('')
: '';
return `
${i + 1}${esc(row.question_text || '')}
${data.revealed && row.is_correct !== null ? `${row.is_correct ? 'верно' : 'неверно'}` : ''}
${data.revealed && state.quiz.kind === 'test' ? `${Number(row.score).toFixed(2)} / ${Number(row.max_score).toFixed(2)}` : ''}
${row.text_answer ? `Ответ: ${esc(row.text_answer)}
` : ''}
${opts}
`;
}).join('');
body.innerHTML = head + (rows || '')
+ '';
renderIcons();
}
async function renderAttempts() {
const body = document.getElementById('qzBody');
body.innerHTML = '';
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts?limit=200', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить попытки');
const items = data.items || [];
if (!items.length) {
body.innerHTML = 'Попыток пока нет
';
return;
}
const rows = items.map(a => `
| ${esc(a.user_name || '—')} |
${fmtDateTime(a.finished_at || a.started_at)} |
${state.quiz.kind === 'test' ? `${Number(a.score).toFixed(2)} / ${Number(a.max_score).toFixed(2)} |
${Number(a.percent).toFixed(1)}% |
${a.passed ? 'сдано' : 'не сдано'} | ` : '— | '}
|
`).join('');
body.innerHTML = `
| Пользователь | Дата | ${state.quiz.kind === 'test' ? 'Баллы | Процент | Итог | ' : 'Оценка | '} |
${rows}
Всего попыток: ${data.total}
`;
} catch (e) {
body.innerHTML = `${esc(e.message)}
`;
}
}
async function renderStats() {
const body = document.getElementById('qzBody');
body.innerHTML = '';
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/stats', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить статистику');
const t = data.totals || {};
const totalAttempts = Number(t.attempts || 0);
const head = `
Попыток: ${totalAttempts}
Участников: ${Number(t.users || 0)}
${state.quiz.kind === 'test' ? `Средний результат: ${Number(t.avg_percent || 0).toFixed(1)}%
Сдали: ${Number(t.passed || 0)}` : ''}
`;
const questions = (data.questions || []).map((q, i) => {
const opts = (q.options || []).map(o => {
const share = totalAttempts ? (o.count / totalAttempts) * 100 : 0;
return `
${esc(o.text)}${o.is_correct ? ' ✓' : ''}${o.count} · ${share.toFixed(0)}%
`;
}).join('');
const texts = (q.texts || []).length
? `Текстовые ответы (${q.texts.length}): ${q.texts.slice(0, 20).map(x => `«${esc(x)}»`).join(', ')}${q.texts.length > 20 ? ' …' : ''}
`
: '';
return `
${i + 1}${esc(q.text)}
${opts}${texts}
`;
}).join('');
body.innerHTML = head + (questions || 'Вопросов нет
');
renderIcons();
} catch (e) {
body.innerHTML = `${esc(e.message)}
`;
}
}
function renderTab() {
renderTabs();
if (state.tab === 'attempts') { renderAttempts(); return; }
if (state.tab === 'stats') { renderStats(); return; }
if (state.attemptDetail) { renderAttemptDetail(); return; }
if (state.result) { renderResult(); return; }
renderTake();
}
async function start() {
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts', { method: 'POST', headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
state.attempt = data.attempt;
if (data.quiz) {
state.quiz.can_take = data.quiz.can_take;
state.questions = data.quiz.questions || state.questions;
}
state.selection = new Map();
state.texts = new Map();
state.result = null;
state.attemptDetail = null;
renderTake();
} catch (e) {
showToast(e.message, true);
}
}
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 (!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) {
showToast(`Вопрос ${i + 1}: минимум ${q.min_length} символов`, true);
return;
}
}
const missing = state.questions.filter(q => {
if (q.required === false) return false;
return isFree(q.kind)
? !String(state.texts.get(q.id) || '').trim()
: !(state.selection.get(q.id) || new Set()).size;
}).length;
if (missing && !confirm(`Без ответа осталось вопросов: ${missing}. Отправить?`)) 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) || '') : '',
}));
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/' + state.attempt.id, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ answers }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
stopTimer();
state.attempt = data.attempt;
state.result = data.result;
state.revealed = data.revealed;
state.tab = 'take';
renderTab();
await loadQuiz(true);
showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены');
} catch (e) {
showToast(e.message, true);
if (btn) btn.disabled = false;
}
}
async function restart() {
if (!confirm('Начать попытку заново? Текущие ответы не сохранятся.')) return;
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/restart', {
method: 'POST',
headers: hdr(),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось начать заново');
stopTimer();
state.attempt = data.attempt;
state.result = null;
state.attemptDetail = null;
state.selection = new Map();
state.texts = new Map();
renderTake();
} catch (e) {
showToast(e.message, true);
}
}
async function openAttempt(id) {
try {
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/' + id, { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить попытку');
state.attemptDetail = data;
state.tab = 'take';
renderTab();
} catch (e) {
showToast(e.message, true);
}
}
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) {
state.texts.set(Number(el.dataset.qtext), el.value);
updateProgress();
}
});
document.addEventListener('click', e => {
const tabBtn = e.target.closest('[data-act="tab"]');
if (tabBtn) {
e.preventDefault();
state.tab = tabBtn.dataset.tab || 'take';
state.attemptDetail = null;
renderTab();
return;
}
const startBtn = e.target.closest('[data-act="start"]');
if (startBtn) { e.preventDefault(); start(); return; }
const subBtn = e.target.closest('[data-act="submit"]');
if (subBtn) { e.preventDefault(); submit(false); return; }
const restartBtn = e.target.closest('[data-act="restart"]');
if (restartBtn) { e.preventDefault(); restart(); return; }
const open = e.target.closest('[data-act="open-attempt"]');
if (open) { e.preventDefault(); openAttempt(open.dataset.attempt); return; }
const tab = e.target.closest('.qz-tab');
if (tab) {
state.tab = tab.dataset.tab;
state.attemptDetail = null;
renderTab();
}
});
window.addEventListener('beforeunload', e => {
if (!state.attempt || state.result) return;
e.preventDefault();
e.returnValue = '';
});
}
async function loadQuiz(keepResult) {
const res = await fetch(API + '/api/quizzes/' + quizId, { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тест');
const prevResult = keepResult ? state.result : null;
const prevAttempt = keepResult ? state.attempt : null;
state.quiz = data.quiz;
state.quiz.can_edit = data.can_edit;
state.quiz.can_take = data.can_take;
state.quiz.attempts_left = data.attempts_left;
state.quiz.my_attempts = data.my_attempts || [];
state.quizAssets = data.quiz_assets || [];
state.questions = (data.questions || []).map(q => ({ ...q }));
if (state.quiz.shuffle_questions && !prevAttempt) state.questions = shuffle(state.questions);
if (state.quiz.shuffle_options) {
state.questions = state.questions.map(q => ({ ...q, options: shuffle(q.options || []) }));
}
if (!keepResult) {
state.attempt = data.current_attempt || null;
state.result = null;
state.revealed = false;
state.selection = new Map();
state.texts = new Map();
} else {
state.attempt = prevAttempt;
state.result = prevResult;
}
if (!state.quiz.can_edit && state.tab === 'stats') state.tab = 'take';
}
async function init() {
if (!Number.isInteger(quizId) || quizId < 1) {
document.getElementById('qzHead').innerHTML = 'Неверный адрес теста
';
return;
}
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
bind();
try {
await loadQuiz(false);
renderHead();
renderTab();
} catch (e) {
document.getElementById('qzHead').innerHTML = `${esc(e.message)}
`;
}
}
init();
})();