(function () {
const API = location.origin;
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
const FREE_KINDS = ['line', 'text', 'number', 'date'];
const state = {
quiz: null,
questions: [],
quizAssets: [],
attempt: null,
selection: new Map(),
texts: new Map(),
timer: null,
done: false,
};
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 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 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 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 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 ? `${esc2(o.description)}
` : ''}${assetsHtml(o.assets)} `;
}).join('');
body = `${items}
`;
}
return `
${index + 1} ${esc2(q.text)}
${q.description ? `${esc2(q.description)}
` : ''}
${assetsHtml(q.assets)}
${body}
`;
}
function introHtml() {
const q = state.quiz;
const isTest = q.kind === 'test';
return `
${q.cover_path ? `
` : ''}
${esc2(q.title || (isTest ? 'Тест' : 'Опрос'))}
Вопросов: ${state.questions.length} ${q.time_limit_min ? `Время: ${q.time_limit_min} мин ` : ''}${isTest ? `${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'} ` : ''}
${q.description ? `
${renderMd(q.description)}
` : ''}
${assetsHtml(state.quizAssets)}
Начать
${isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.'}
`;
}
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) {
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);
}
}
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 btn = document.querySelector('[data-act="start"]');
if (btn) btn.disabled = true;
try {
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
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 = 'Ответы сохранены. Автор скрыл разбор ответов.';
}
document.getElementById('qpBody').innerHTML = `
${isTest && result && result.passed === false ? '•' : '✓'}
${isTest ? 'Тест завершён' : 'Спасибо!'}
${isTest && score ? `
${esc2(score)} ${passText ? ` · ${esc2(passText)}` : ''}
` : ''}
${gradeHtml}
${esc2(hint)}
${details}
Пройти ещё раз
`;
}
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) {
toast(`Вопрос ${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/public-quizzes/' + quizId + '/attempts/' + state.attempt.id, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: state.attempt.anon_token, answers }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
stopTimer();
state.done = true;
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 => {
if (e.target.dataset.qtext) {
state.texts.set(Number(e.target.dataset.qtext), e.target.value);
updateProgress();
}
});
document.addEventListener('click', e => {
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();
})();