- quizzes.public_token (VARCHAR 32, уникальный индекс) вместо числового id в публичных роутах /api/public-quizzes/:token - бэкилл токенов для существующих строк в db/migration.sql + ensureQuizTables - quiz_questions.no_shuffle — вопрос исключён из перемешивания - POST /api/quizzes/:id/public-token/rotate — сброс утёкшей ссылки (автор/админ) - restore: no_shuffle в INSERT quiz_questions, backup.selftest обновлён - документация AGENTS.md + handoff
581 lines
24 KiB
JavaScript
581 lines
24 KiB
JavaScript
(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, '>')
|
|
.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 = `<img src="${at(thumb(a.path))}" data-img="${at(API + a.path)}" alt="${at(a.original_name || '')}">`;
|
|
} else if (a.kind === 'audio') {
|
|
inner = `<audio controls preload="none" src="${at(fileUrl(a))}"></audio>`;
|
|
} else if (a.kind === 'video') {
|
|
inner = `<video controls preload="metadata" src="${at(fileUrl(a))}"></video>`;
|
|
} else {
|
|
inner = `<a href="${at(fileUrl(a))}" target="_blank" rel="noopener noreferrer">${esc2(a.original_name || 'Файл')}</a>`;
|
|
}
|
|
return `<div class="qz-asset">${inner}${a.caption ? `<div class="qz-asset-cap">${esc2(a.caption)}</div>` : ''}</div>`;
|
|
});
|
|
return `<div class="qz-assets">${cards.join('')}</div>`;
|
|
}
|
|
|
|
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 `<div class="qz-suggest-wrap">
|
|
<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" data-qsys="${q.kind}" placeholder="Начните вводить название ${label}" autocomplete="off" maxlength="200" value="${esc2(value)}">
|
|
<input type="hidden" data-qsysid="${q.id}" value="${picked}">
|
|
<div class="qz-suggest" data-sug="${q.id}" hidden></div>
|
|
</div>`;
|
|
}
|
|
|
|
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
|
|
? `<div class="qp-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
|
: '';
|
|
if (q.kind === 'text') {
|
|
return `<textarea class="settings-input qz-answer" rows="3" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000">${esc2(value)}</textarea>${hint}`;
|
|
}
|
|
if (q.kind === 'number') {
|
|
return `<input type="number" step="any" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Число" value="${esc2(value)}">`;
|
|
}
|
|
if (q.kind === 'date') {
|
|
return `<input type="date" class="settings-input qz-answer" data-qtext="${q.id}" value="${esc2(value)}">`;
|
|
}
|
|
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc2(value)}">${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 => `<button type="button" class="qz-sug-item" data-sug-q="${qid}" data-sug-id="${it.id}" data-sug-name="${esc2(it.name)}"><span>${esc2(it.name)}</span>${it.sub ? `<small>${esc2(it.sub)}</small>` : ''}</button>`).join('')
|
|
: '<div class="qz-sug-empty">Ничего не найдено</div>';
|
|
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 = `<select class="settings-input qz-answer" data-q="${q.id}">
|
|
<option value="">— выберите —</option>
|
|
${(q.options || []).map(o => `<option value="${o.id}"${chosen.has(Number(o.id)) ? ' selected' : ''}>${esc2(o.text)}</option>`).join('')}
|
|
</select>`;
|
|
} else {
|
|
const items = (q.options || []).map(o => {
|
|
const checked = chosen.has(Number(o.id)) ? ' checked' : '';
|
|
const input = q.kind === 'multiple'
|
|
? `<input type="checkbox" data-q="${q.id}" data-opt="${o.id}"${checked}>`
|
|
: `<input type="radio" name="q${q.id}" data-q="${q.id}" data-opt="${o.id}"${checked}>`;
|
|
return `<label class="qz-opt">${input}<span class="qz-opt-text">${esc2(o.text)}${o.description ? `<div class="qz-opt-desc">${renderMdInline(o.description)}</div>` : ''}${assetsHtml(o.assets)}</span></label>`;
|
|
}).join('');
|
|
body = `<div class="qz-opts${q.options_inline ? ' inline' : ''}">${items}</div>`;
|
|
}
|
|
return `<section class="qz-q">
|
|
<div class="qz-q-head"><span class="qz-q-num">${index + 1}</span><span class="qz-q-text">${esc2(q.text)}</span></div>
|
|
${q.description ? `<div class="qz-q-desc">${renderMd(q.description)}</div>` : ''}
|
|
${assetsHtml(q.assets)}
|
|
<div style="margin-top:8px">${body}</div>
|
|
</section>`;
|
|
}
|
|
|
|
function introHtml() {
|
|
const q = state.quiz;
|
|
const isTest = q.kind === 'test';
|
|
const until = retryUntil();
|
|
return `<div class="qp-card">
|
|
${q.cover_path ? `<img class="qp-cover" src="${at(thumb(q.cover_path))}" data-img="${at(API + q.cover_path)}" alt="Обложка">` : ''}
|
|
<div class="qp-title">${esc2(q.title || (isTest ? 'Тест' : 'Опрос'))}</div>
|
|
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}${q.retry_cooldown_min ? `<span>Повтор: через ${q.retry_cooldown_min} мин</span>` : ''}${isTest ? `<span>${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}</span>` : ''}</div>
|
|
${q.description ? `<div class="qp-desc">${renderMd(q.description)}</div>` : ''}
|
|
${assetsHtml(state.quizAssets)}
|
|
${q.requires_code ? `<div class="settings-field" style="margin-top:14px">
|
|
<label for="qpAccessCode">Код доступа</label>
|
|
<input class="settings-input" id="qpAccessCode" maxlength="64" autocomplete="off" placeholder="Введите код">
|
|
<div class="qp-hint">Код выдает тьютор.</div>
|
|
</div>` : ''}
|
|
<div class="qp-actions">
|
|
${until ? '' : '<button type="button" class="btn-primary" data-act="start">Начать</button>'}
|
|
<span class="qp-hint">${until ? `Вы уже прошли ${isTest ? 'этот тест' : 'этот опрос'} в этом браузере.` : (isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.')}</span>
|
|
</div>
|
|
${until ? `<div class="qp-hint" id="qpRetryTimer" style="margin-top:8px">${esc2(retryLeftText(until))}</div>` : ''}
|
|
</div>`;
|
|
}
|
|
|
|
function renderQuestions() {
|
|
return `<div class="qp-card">
|
|
<div class="qp-title">${esc2(state.quiz.title || 'Опрос')}</div>
|
|
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span></div>
|
|
<div class="qp-actions">
|
|
<span class="qz-timer" id="qzTimer" hidden>—</span>
|
|
<span class="qp-hint">Отвечено: <b id="qpProgress">0</b> из ${state.questions.length}</span>
|
|
</div>
|
|
${state.questions.map(questionHtml).join('')}
|
|
<div class="qp-actions">
|
|
<button type="button" class="btn-primary" data-act="submit">Отправить ответы</button>
|
|
</div>
|
|
</div>`;
|
|
}
|
|
|
|
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 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
|
|
? `<div class="qp-grade">${grade.image_path ? `<img src="${at(thumb(grade.image_path))}" data-img="${at(API + grade.image_path)}" alt="">` : ''}<div class="qp-grade-label">${esc2(grade.label || '')}</div></div>`
|
|
: '';
|
|
const hiddenAnswers = !!(result && result.answers_hidden);
|
|
const details = result && Array.isArray(result.questions) && result.questions.length
|
|
? `<div class="qp-result">${result.questions.map(q => {
|
|
const ok = q.is_correct === true;
|
|
const bad = q.is_correct === false;
|
|
return `<div class="qp-result-item ${ok ? 'ok' : (bad ? 'bad' : '')}">
|
|
<div class="qp-result-q">${esc2(q.text || '')}</div>
|
|
<div class="qp-result-a">${ok ? 'Верно' : (bad ? 'Неверно' : 'Ответ сохранён')}${q.max_score ? ` · ${q.score} / ${q.max_score}` : ''}</div>
|
|
</div>`;
|
|
}).join('')}</div>`
|
|
: '';
|
|
let hint = 'Ответы сохранены.';
|
|
if (isTest) {
|
|
if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.';
|
|
else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.';
|
|
}
|
|
const until = retryUntil();
|
|
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
|
|
<div class="qp-done-ic">${isTest && result && result.passed === false ? '•' : '✓'}</div>
|
|
<div class="qp-title">${isTest ? 'Тест завершён' : 'Спасибо!'}</div>
|
|
${isTest && score ? `<p style="margin-top:8px;font-size:1rem"><b>${esc2(score)}</b>${passText ? ` · ${esc2(passText)}` : ''}</p>` : ''}
|
|
${gradeHtml}
|
|
<p class="qp-hint" style="margin-top:8px">${esc2(hint)}</p>
|
|
${details}
|
|
<div class="qp-actions" style="justify-content:center">
|
|
${until
|
|
? `<span class="qp-hint">${esc2(retryLeftText(until))}</span>`
|
|
: '<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>'}
|
|
</div>
|
|
</div>`;
|
|
}
|
|
|
|
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 = '<div class="qp-error">Неверная ссылка</div>';
|
|
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 = `<div class="qp-error">${esc2(e.message)}</div>`;
|
|
}
|
|
}
|
|
|
|
init();
|
|
})();
|