Тесты и опросы: модуль тестов, анонимные опросы, страницы и бэкап
- lib/quizzes.js: таблицы quizzes*, CRUD, привязка медиа, подсчёт баллов, попытки, статистика, purge и уборка ассетов - server.js: роуты CRUD/прохождения/статистики, отдача медиа, публичные роуты анонимного опроса, sweep и restore - db/init.sql + db/migration.sql: схема шести таблиц, индексы и идемпотентные ALTER/CHECK - backup-restore.js: нормализация и списки таблиц, покрытие в backup.selftest.js - страницы quizzes/quiz-edit/quiz/quiz-public и публичный опрос без входа, пункт сайдбара «Тесты и опросы» - quiz.selftest.js: юнит-проверки подсчёта баллов и нормализации ответов - AGENTS.md: раздел 3t и File Map
This commit is contained in:
@@ -0,0 +1,833 @@
|
||||
(function () {
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const state = { quiz: null, assets: [], questions: [] };
|
||||
let dirty = false;
|
||||
let saving = false;
|
||||
let dragState = null;
|
||||
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const OPTION_KINDS = ['single', 'multiple', 'select'];
|
||||
|
||||
function isFree(kind) {
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isOptionKind(kind) {
|
||||
return OPTION_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function normalizeKind(kind) {
|
||||
return isFree(kind) || isOptionKind(kind) ? kind : 'single';
|
||||
}
|
||||
|
||||
function at(s) {
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function assetName(a) {
|
||||
return String(a.path || '').split('/').pop();
|
||||
}
|
||||
|
||||
function mediaSrc(a) {
|
||||
const name = assetName(a);
|
||||
const play = a.kind === 'audio' || a.kind === 'video' ? '&play=1' : '';
|
||||
return API + '/api/quizzes/files/' + encodeURIComponent(name) + '?token=' + encodeURIComponent(token || '') + play;
|
||||
}
|
||||
|
||||
function allAssets() {
|
||||
const out = state.assets.slice();
|
||||
for (const q of state.questions) {
|
||||
out.push(...q.assets);
|
||||
for (const o of q.options) out.push(...o.assets);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function findAsset(id) {
|
||||
return allAssets().find(a => Number(a.id) === Number(id)) || null;
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
dirty = true;
|
||||
document.getElementById('qeDirty').hidden = false;
|
||||
}
|
||||
|
||||
function clearDirty() {
|
||||
dirty = false;
|
||||
document.getElementById('qeDirty').hidden = true;
|
||||
}
|
||||
|
||||
function fromServer(data) {
|
||||
const quiz = data.quiz || {};
|
||||
state.quiz = {
|
||||
id: quiz.id,
|
||||
title: quiz.title || '',
|
||||
description: quiz.description || '',
|
||||
kind: quiz.kind === 'survey' ? 'survey' : 'test',
|
||||
is_published: quiz.is_published === true,
|
||||
shuffle_questions: quiz.shuffle_questions === true,
|
||||
shuffle_options: quiz.shuffle_options === true,
|
||||
show_results: quiz.show_results !== false,
|
||||
allow_anonymous: quiz.allow_anonymous === true,
|
||||
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
|
||||
time_limit_min: quiz.time_limit_min || 0,
|
||||
pass_percent: quiz.pass_percent == null ? 60 : quiz.pass_percent,
|
||||
cover_path: quiz.cover_path || null,
|
||||
};
|
||||
state.assets = Array.isArray(data.quiz_assets) ? data.quiz_assets.slice() : [];
|
||||
state.questions = (data.questions || []).map(q => ({
|
||||
id: q.id,
|
||||
kind: normalizeKind(q.kind),
|
||||
text: q.text || '',
|
||||
description: q.description || '',
|
||||
weight: q.weight == null ? 1 : Number(q.weight),
|
||||
partial_credit: q.partial_credit === true,
|
||||
required: q.required !== false,
|
||||
min_length: Number(q.min_length) || 0,
|
||||
options_inline: q.options_inline === true,
|
||||
text_match: q.text_match === 'contains' ? 'contains' : 'exact',
|
||||
accepted_answers: Array.isArray(q.accepted_answers) ? q.accepted_answers.slice() : [],
|
||||
assets: Array.isArray(q.assets) ? q.assets.slice() : [],
|
||||
options: (q.options || []).map(o => ({
|
||||
id: o.id,
|
||||
text: o.text || '',
|
||||
description: o.description || '',
|
||||
is_correct: o.is_correct === true,
|
||||
weight: o.weight == null ? 1 : Number(o.weight),
|
||||
assets: Array.isArray(o.assets) ? o.assets.slice() : [],
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
function payload() {
|
||||
const q = state.quiz;
|
||||
return {
|
||||
title: q.title,
|
||||
description: q.description,
|
||||
kind: q.kind,
|
||||
is_published: q.is_published,
|
||||
shuffle_questions: q.shuffle_questions,
|
||||
shuffle_options: q.shuffle_options,
|
||||
show_results: q.show_results,
|
||||
allow_anonymous: q.allow_anonymous,
|
||||
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
|
||||
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
|
||||
pass_percent: q.pass_percent === '' ? 60 : q.pass_percent,
|
||||
cover_path: q.cover_path,
|
||||
asset_ids: state.assets.map(a => a.id),
|
||||
questions: state.questions.map(qq => ({
|
||||
id: qq.id || null,
|
||||
kind: qq.kind,
|
||||
text: qq.text,
|
||||
description: qq.description,
|
||||
weight: qq.weight,
|
||||
partial_credit: qq.partial_credit,
|
||||
required: qq.required,
|
||||
min_length: qq.min_length,
|
||||
options_inline: qq.options_inline,
|
||||
text_match: qq.text_match,
|
||||
accepted_answers: qq.accepted_answers,
|
||||
asset_ids: qq.assets.map(a => a.id),
|
||||
options: qq.options.map(o => ({
|
||||
id: o.id || null,
|
||||
text: o.text,
|
||||
description: o.description,
|
||||
is_correct: o.is_correct,
|
||||
weight: o.weight,
|
||||
asset_ids: o.assets.map(a => a.id),
|
||||
})),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function assetsHtml(assets, owner) {
|
||||
if (!assets.length) return '';
|
||||
const cards = assets.map(a => {
|
||||
const kind = a.kind || 'file';
|
||||
let inner;
|
||||
if (kind === 'image') {
|
||||
inner = `<img src="${at(thumbSrc(a.path))}" data-img="${at(API + a.path)}" alt="${at(a.original_name || '')}">`;
|
||||
} else if (kind === 'audio') {
|
||||
inner = `<audio controls preload="none" src="${at(mediaSrc(a))}"></audio>`;
|
||||
} else if (kind === 'video') {
|
||||
inner = `<video controls preload="metadata" src="${at(mediaSrc(a))}"></video>`;
|
||||
} else {
|
||||
inner = `<a class="qe-asset-file" href="${at(mediaSrc(a))}" target="_blank" rel="noopener noreferrer"><i data-lucide="file"></i> ${esc(a.original_name || assetName(a))}</a>`;
|
||||
}
|
||||
const caption = `<input class="qe-asset-cap" data-cap-asset="${a.id}" value="${at(a.caption || '')}" placeholder="Подпись к файлу" maxlength="300">`;
|
||||
return `<div class="qe-asset">${inner}<button type="button" class="qe-asset-del" data-act="del-asset" data-owner="${at(owner)}" data-asset="${a.id}" title="Удалить файл"><i data-lucide="x"></i></button>${caption}</div>`;
|
||||
});
|
||||
return cards.join('');
|
||||
}
|
||||
|
||||
function optionHtml(o, qi, oi, isTest) {
|
||||
const owner = `o:${qi}:${oi}`;
|
||||
return `<div class="qe-opt" data-oi="${oi}">
|
||||
<div class="qe-opt-row">
|
||||
<span class="qe-opt-drag" draggable="true" title="Перетащить вариант">⠿</span>
|
||||
<input type="text" class="settings-input qe-opt-text" data-oi="${oi}" data-field="text" value="${at(o.text)}" placeholder="Текст варианта">
|
||||
${isTest ? `<label class="qe-correct"><input type="checkbox" data-oi="${oi}" data-field="is_correct"${o.is_correct ? ' checked' : ''}> верный</label>
|
||||
<input type="number" class="settings-input qe-opt-weight" data-oi="${oi}" data-field="weight" min="0" max="100" step="0.5" value="${at(o.weight)}" title="Вес варианта">` : ''}
|
||||
<button type="button" class="icon-btn" data-act="del-option" data-oi="${oi}" title="Удалить вариант"><i data-lucide="trash-2"></i></button>
|
||||
</div>
|
||||
<div class="qe-opt-row" style="margin-top:8px">
|
||||
<input type="text" class="settings-input qe-opt-text" data-oi="${oi}" data-field="description" value="${at(o.description)}" placeholder="Пояснение (необязательно)">
|
||||
<button type="button" class="btn-link qe-mini" data-act="upload" data-owner="${owner}">Файл</button>
|
||||
</div>
|
||||
<div class="qe-assets" data-assets="${owner}">${assetsHtml(o.assets, owner)}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function acceptedHtml(q, qi, isTest) {
|
||||
if (!isFree(q.kind) || !isTest) return '';
|
||||
const hints = {
|
||||
line: 'Ответ вводится одной строкой. Регистр, «ё» и лишние пробелы не важны.',
|
||||
text: 'Ответ вводится многострочным текстом. Регистр, «ё» и лишние пробелы не важны.',
|
||||
number: 'Ответ сравнивается как число: «4», «4,0» и « 4 » совпадут.',
|
||||
date: 'Ответ сравнивается как дата: ГГГГ-ММ-ДД или ДД.ММ.ГГГГ.',
|
||||
};
|
||||
const placeholder = q.kind === 'number'
|
||||
? '4 4.0'
|
||||
: q.kind === 'date'
|
||||
? '2026-12-31 31.12.2026'
|
||||
: '4 четыре';
|
||||
const matchSelect = q.kind === 'line' || q.kind === 'text'
|
||||
? `<select class="settings-input" data-qi="${qi}" data-field="text_match">
|
||||
<option value="exact"${q.text_match !== 'contains' ? ' selected' : ''}>Точное совпадение</option>
|
||||
<option value="contains"${q.text_match === 'contains' ? ' selected' : ''}>Содержит ответ</option>
|
||||
</select>`
|
||||
: '<span></span>';
|
||||
return `<div class="qe-accepted" data-accepted="${qi}">
|
||||
<label class="qe-hint" for="qeAccepted${qi}" style="margin:0">Принимаемые ответы — по одному в строке. Если пусто, ответ проверяется вручную.</label>
|
||||
<span></span>
|
||||
<textarea id="qeAccepted${qi}" class="settings-input" rows="2" data-qi="${qi}" data-field="accepted_raw" placeholder="${placeholder}" maxlength="4000">${esc((q.accepted_answers || []).join('\n'))}</textarea>
|
||||
${matchSelect}
|
||||
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос: вес вопроса.</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function questionHtml(q, qi) {
|
||||
const isTest = state.quiz.kind === 'test';
|
||||
const owner = `q:${qi}`;
|
||||
const kindOptions = [
|
||||
['single', 'Один ответ (радиокнопки)'],
|
||||
['multiple', 'Несколько ответов (флажки)'],
|
||||
['select', 'Выпадающий список'],
|
||||
['line', 'Строка'],
|
||||
['text', 'Многострочный текст'],
|
||||
['number', 'Число'],
|
||||
['date', 'Дата'],
|
||||
].map(([value, label]) => `<option value="${value}"${q.kind === value ? ' selected' : ''}>${label}</option>`).join('');
|
||||
const options = isOptionKind(q.kind) ? `
|
||||
<div data-options="${qi}">${q.options.map((o, oi) => optionHtml(o, qi, oi, isTest)).join('')}</div>
|
||||
<button type="button" class="btn-link qe-mini" data-act="add-option" data-qi="${qi}"><i data-lucide="plus"></i> Добавить вариант</button>` : '';
|
||||
return `<section class="qe-q" data-qi="${qi}">
|
||||
<div class="qe-q-head">
|
||||
<span class="qe-drag" draggable="true" title="Перетащить вопрос">⠿</span>
|
||||
<span class="qe-q-num">${qi + 1}</span>
|
||||
<select class="settings-input" data-role="qkind" data-qi="${qi}">${kindOptions}</select>
|
||||
${isTest ? `<input type="number" class="settings-input" style="max-width:110px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}" title="Вес вопроса">` : ''}
|
||||
<span class="spacer"></span>
|
||||
<button type="button" class="icon-btn" data-act="up" data-qi="${qi}" title="Выше"><i data-lucide="arrow-up"></i></button>
|
||||
<button type="button" class="icon-btn" data-act="down" data-qi="${qi}" title="Ниже"><i data-lucide="arrow-down"></i></button>
|
||||
<button type="button" class="icon-btn" data-act="del-question" data-qi="${qi}" title="Удалить вопрос"><i data-lucide="trash-2"></i></button>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<textarea class="settings-input" rows="2" data-qi="${qi}" data-field="text" placeholder="Текст вопроса" maxlength="5000">${esc(q.text)}</textarea>
|
||||
</div>
|
||||
<div class="settings-field">
|
||||
<textarea class="settings-input" rows="2" data-qi="${qi}" data-field="description" placeholder="Пояснение к вопросу (необязательно)" maxlength="5000">${esc(q.description)}</textarea>
|
||||
</div>
|
||||
<div class="qe-row-btns" style="margin-bottom:8px">
|
||||
<button type="button" class="btn-link qe-mini" data-act="upload" data-owner="${owner}">Прикрепить файл</button>
|
||||
${isTest && q.kind === 'multiple' ? `<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="partial_credit"${q.partial_credit ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Частичный зачёт</small></span></label>` : ''}
|
||||
${isOptionKind(q.kind) && q.kind !== 'select' ? `<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="options_inline"${q.options_inline ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Ответы в строку</small></span></label>` : ''}
|
||||
<label class="toggle" style="padding:2px 6px"><input type="checkbox" data-qi="${qi}" data-field="required"${q.required ? ' checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><small>Обязательный</small></span></label>
|
||||
${q.required && (q.kind === 'line' || q.kind === 'text') ? `<label class="qe-min-len">Мин. длина <input type="number" class="settings-input" data-qi="${qi}" data-field="min_length" min="0" max="2000" value="${at(q.min_length || 0)}"></label>` : ''}
|
||||
</div>
|
||||
<div class="qe-assets" data-assets="${owner}">${assetsHtml(q.assets, owner)}</div>
|
||||
${acceptedHtml(q, qi, isTest)}
|
||||
${options}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function renderCover() {
|
||||
const el = document.getElementById('qeCover');
|
||||
const p = state.quiz.cover_path;
|
||||
el.innerHTML = (p
|
||||
? `<img class="qe-cover-preview" src="${at(thumbSrc(p))}" data-img="${at(API + p)}" alt="Обложка">`
|
||||
: '<div class="qe-cover-empty">Без обложки</div>')
|
||||
+ (p ? '<button type="button" class="btn-link danger qe-mini" data-act="del-cover">Удалить обложку</button>' : '');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function renderQuestions() {
|
||||
const wrap = document.getElementById('qeQuestions');
|
||||
if (!state.questions.length) {
|
||||
wrap.innerHTML = '<div class="qe-panel"><p class="qe-hint" style="margin:0">Вопросов пока нет. Добавьте первый вопрос.</p></div>';
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = state.questions.map(questionHtml).join('');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function renderQuizAssets() {
|
||||
const el = document.querySelector('[data-assets="quiz"]');
|
||||
if (el) {
|
||||
el.innerHTML = assetsHtml(state.assets, 'quiz');
|
||||
renderIcons();
|
||||
}
|
||||
}
|
||||
|
||||
function renderPreview() {
|
||||
const box = document.getElementById('qeDescPreview');
|
||||
const btn = document.getElementById('qeDescPreviewBtn');
|
||||
if (!box) return;
|
||||
if (box.hidden) {
|
||||
btn.textContent = 'Предпросмотр Markdown';
|
||||
return;
|
||||
}
|
||||
const text = document.getElementById('qeDesc').value;
|
||||
box.innerHTML = text.trim() ? WhatIDoMD.render(text) : '<span class="qe-hint">Пусто</span>';
|
||||
btn.textContent = 'Скрыть предпросмотр';
|
||||
}
|
||||
|
||||
function renderAnon() {
|
||||
const wrap = document.getElementById('qeAnonWrap');
|
||||
if (!wrap) return;
|
||||
const isSurvey = state.quiz.kind === 'survey';
|
||||
wrap.hidden = !isSurvey;
|
||||
if (!isSurvey) return;
|
||||
document.getElementById('qeAnonymous').checked = state.quiz.allow_anonymous;
|
||||
const link = document.getElementById('qeAnonLink');
|
||||
const hint = document.getElementById('qeAnonPublishHint');
|
||||
const ready = state.quiz.allow_anonymous && state.quiz.is_published;
|
||||
const visible = ready && !dirty;
|
||||
link.hidden = !visible;
|
||||
let text = '';
|
||||
if (state.quiz.allow_anonymous && !state.quiz.is_published) text = 'Опубликуйте опрос, чтобы ссылка заработала.';
|
||||
else if (ready && dirty) text = 'Сохраните опрос, чтобы ссылка заработала.';
|
||||
hint.hidden = !text;
|
||||
hint.textContent = text;
|
||||
if (visible) {
|
||||
const url = location.origin + '/quiz-public.html?id=' + state.quiz.id;
|
||||
document.getElementById('qeAnonUrl').value = url;
|
||||
document.getElementById('qeAnonOpen').href = url;
|
||||
}
|
||||
}
|
||||
|
||||
function renderSide() {
|
||||
const q = state.quiz;
|
||||
document.getElementById('qeName').value = q.title;
|
||||
document.getElementById('qeDesc').value = q.description;
|
||||
document.getElementById('qePass').value = q.pass_percent;
|
||||
document.getElementById('qeAttempts').value = q.max_attempts;
|
||||
document.getElementById('qeTime').value = q.time_limit_min;
|
||||
document.getElementById('qePublished').checked = q.is_published;
|
||||
document.getElementById('qeShuffleQ').checked = q.shuffle_questions;
|
||||
document.getElementById('qeShuffleO').checked = q.shuffle_options;
|
||||
document.getElementById('qeShowResults').checked = q.show_results;
|
||||
document.querySelectorAll('#qeKindSeg .qe-seg-btn').forEach(b => {
|
||||
b.classList.toggle('on', b.dataset.kind === q.kind);
|
||||
});
|
||||
document.getElementById('qePassWrap').hidden = q.kind !== 'test';
|
||||
document.getElementById('qeBarTitle').textContent = q.title || 'Без названия';
|
||||
document.getElementById('qePreviewBtn').href = 'quiz.html?id=' + q.id;
|
||||
renderCover();
|
||||
renderQuizAssets();
|
||||
renderAnon();
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
renderSide();
|
||||
renderQuestions();
|
||||
renderPreview();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId, { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тест');
|
||||
if (!data.can_edit) throw new Error('Изменять тест может только автор или администратор');
|
||||
fromServer(data);
|
||||
clearDirty();
|
||||
renderAll();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
document.getElementById('qeQuestions').innerHTML = `<div class="qe-panel"><p class="qe-hint" style="margin:0">${esc(e.message)}</p></div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (saving) return;
|
||||
const q = state.quiz;
|
||||
if (!q.title.trim()) { showToast('Укажите название теста', true); return; }
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const item = state.questions[i];
|
||||
if (!String(item.text || '').trim()) { showToast('Вопрос ' + (i + 1) + ': заполните текст', true); return; }
|
||||
if (isFree(item.kind)) continue;
|
||||
if (item.options.length < 2) { showToast('Вопрос ' + (i + 1) + ': нужно минимум два варианта', true); return; }
|
||||
if (item.options.some(o => !String(o.text || '').trim())) { showToast('Вопрос ' + (i + 1) + ': заполните все варианты', true); return; }
|
||||
if (q.kind === 'test') {
|
||||
const correct = item.options.filter(o => o.is_correct).length;
|
||||
if ((item.kind === 'single' || item.kind === 'select') && correct !== 1) {
|
||||
showToast('Вопрос ' + (i + 1) + ': отметьте ровно один верный ответ', true);
|
||||
return;
|
||||
}
|
||||
if (item.kind === 'multiple' && correct < 1) { showToast('Вопрос ' + (i + 1) + ': отметьте хотя бы один верный ответ', true); return; }
|
||||
}
|
||||
}
|
||||
saving = true;
|
||||
const btn = document.getElementById('qeSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify(payload()),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось сохранить тест');
|
||||
fromServer(data);
|
||||
clearDirty();
|
||||
renderAll();
|
||||
showToast('Сохранено');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
} finally {
|
||||
saving = false;
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function pickFile(cb) {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.addEventListener('change', () => {
|
||||
const file = input.files && input.files[0];
|
||||
if (file) cb(file);
|
||||
});
|
||||
input.click();
|
||||
}
|
||||
|
||||
async function uploadAsset(owner, file) {
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append('file', file);
|
||||
const res = await fetch(API + '/api/quizzes/assets', { method: 'POST', headers: hdr(), body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить файл');
|
||||
const asset = data.item;
|
||||
if (owner === 'quiz') state.assets.push(asset);
|
||||
else if (owner.startsWith('q:')) state.questions[Number(owner.split(':')[1])].assets.push(asset);
|
||||
else {
|
||||
const parts = owner.split(':');
|
||||
state.questions[Number(parts[1])].options[Number(parts[2])].assets.push(asset);
|
||||
}
|
||||
markDirty();
|
||||
renderAll();
|
||||
showToast('Файл загружен');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteAsset(owner, id) {
|
||||
if (!confirm('Удалить файл?')) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/assets/' + id, { method: 'DELETE', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось удалить файл');
|
||||
const strip = list => list.filter(a => Number(a.id) !== Number(id));
|
||||
if (owner === 'quiz') state.assets = strip(state.assets);
|
||||
else if (owner.startsWith('q:')) {
|
||||
const qi = Number(owner.split(':')[1]);
|
||||
state.questions[qi].assets = strip(state.questions[qi].assets);
|
||||
} else {
|
||||
const parts = owner.split(':');
|
||||
const qq = state.questions[Number(parts[1])];
|
||||
qq.options[Number(parts[2])].assets = strip(qq.options[Number(parts[2])].assets);
|
||||
}
|
||||
markDirty();
|
||||
renderAll();
|
||||
showToast('Файл удалён');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCaption(input) {
|
||||
const id = Number(input.dataset.capAsset);
|
||||
const asset = findAsset(id);
|
||||
if (!asset) return;
|
||||
const caption = input.value.trim();
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/assets/' + id, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ caption }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось сохранить подпись');
|
||||
asset.caption = data.item ? data.item.caption : caption;
|
||||
input.value = asset.caption || '';
|
||||
} catch (e) {
|
||||
input.value = asset.caption || '';
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function uploadCover(file) {
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append('photo', file);
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/cover', { method: 'POST', headers: hdr(), body: fd });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить обложку');
|
||||
state.quiz.cover_path = data.item.path;
|
||||
markDirty();
|
||||
renderCover();
|
||||
showToast('Обложка загружена');
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteCover() {
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/cover', { method: 'DELETE', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось удалить обложку');
|
||||
state.quiz.cover_path = null;
|
||||
markDirty();
|
||||
renderCover();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
function onField(e) {
|
||||
const el = e.target;
|
||||
const isChoice = el.tagName === 'SELECT' || el.type === 'checkbox' || el.type === 'radio';
|
||||
if (isChoice && e.type !== 'change') return;
|
||||
if (!isChoice && e.type !== 'input') return;
|
||||
const role = el.dataset.role;
|
||||
if (role === 'qkind') {
|
||||
const qi = Number(el.dataset.qi);
|
||||
const q = state.questions[qi];
|
||||
q.kind = normalizeKind(el.value);
|
||||
if (isFree(q.kind)) {
|
||||
q.options = [];
|
||||
} else if (q.options.length < 2) {
|
||||
q.options = [
|
||||
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
|
||||
];
|
||||
}
|
||||
markDirty();
|
||||
renderQuestions();
|
||||
renderPreview();
|
||||
return;
|
||||
}
|
||||
const field = el.dataset.field;
|
||||
if (!field) return;
|
||||
if (el.dataset.oi !== undefined) {
|
||||
const qi = Number(el.closest('[data-qi]').dataset.qi);
|
||||
const oi = Number(el.dataset.oi);
|
||||
const opt = state.questions[qi].options[oi];
|
||||
if (field === 'is_correct') {
|
||||
opt.is_correct = el.checked;
|
||||
if (opt.is_correct && state.questions[qi].kind === 'single') {
|
||||
state.questions[qi].options.forEach((o, idx) => { if (idx !== oi) o.is_correct = false; });
|
||||
renderQuestions();
|
||||
renderPreview();
|
||||
}
|
||||
} else if (field === 'weight') {
|
||||
opt.weight = el.value === '' ? 0 : Number(el.value);
|
||||
} else {
|
||||
opt[field] = el.value;
|
||||
}
|
||||
markDirty();
|
||||
return;
|
||||
}
|
||||
if (el.dataset.qi !== undefined) {
|
||||
const qi = Number(el.dataset.qi);
|
||||
const q = state.questions[qi];
|
||||
if (field === 'weight') q.weight = el.value === '' ? 0 : Number(el.value);
|
||||
else if (field === 'min_length') q.min_length = el.value === '' ? 0 : Math.max(0, Math.min(2000, Math.round(Number(el.value) || 0)));
|
||||
else if (field === 'partial_credit' || field === 'required' || field === 'options_inline') {
|
||||
q[field] = el.checked;
|
||||
if (field === 'required' && (q.kind === 'line' || q.kind === 'text')) {
|
||||
markDirty();
|
||||
renderQuestions();
|
||||
return;
|
||||
}
|
||||
} else if (field === 'accepted_raw') {
|
||||
q.accepted_answers = el.value.split('\n').map(s => s.trim()).filter(Boolean).slice(0, 50);
|
||||
} else if (field === 'text_match') {
|
||||
q.text_match = el.value === 'contains' ? 'contains' : 'exact';
|
||||
} else q[field] = el.value;
|
||||
markDirty();
|
||||
}
|
||||
}
|
||||
|
||||
function moveItem(list, from, to) {
|
||||
const [item] = list.splice(from, 1);
|
||||
list.splice(to, 0, item);
|
||||
}
|
||||
|
||||
function clearDragMarks() {
|
||||
document.querySelectorAll('.qe-dragging').forEach(el => el.classList.remove('qe-dragging'));
|
||||
document.querySelectorAll('.qe-drag-over').forEach(el => el.classList.remove('qe-drag-over'));
|
||||
}
|
||||
|
||||
function onDragStart(e) {
|
||||
const qHandle = e.target.closest('.qe-drag');
|
||||
const oHandle = e.target.closest('.qe-opt-drag');
|
||||
if (qHandle) {
|
||||
const card = qHandle.closest('.qe-q');
|
||||
dragState = { type: 'question', qi: Number(card.dataset.qi) };
|
||||
card.classList.add('qe-dragging');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
e.dataTransfer.setData('text/plain', 'question');
|
||||
return;
|
||||
}
|
||||
if (oHandle) {
|
||||
const opt = oHandle.closest('.qe-opt');
|
||||
const card = oHandle.closest('[data-qi]');
|
||||
dragState = { type: 'option', qi: Number(card.dataset.qi), oi: Number(opt.dataset.oi) };
|
||||
opt.classList.add('qe-dragging');
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
e.dataTransfer.setData('text/plain', 'option');
|
||||
}
|
||||
}
|
||||
|
||||
function onDragOver(e) {
|
||||
if (!dragState) return;
|
||||
const card = e.target.closest('.qe-q');
|
||||
if (!card) return;
|
||||
if (dragState.type === 'question') {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
document.querySelectorAll('.qe-q.qe-drag-over').forEach(el => el.classList.remove('qe-drag-over'));
|
||||
if (Number(card.dataset.qi) !== dragState.qi) card.classList.add('qe-drag-over');
|
||||
return;
|
||||
}
|
||||
const opt = e.target.closest('.qe-opt');
|
||||
if (!opt || Number(card.dataset.qi) !== dragState.qi) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = 'move';
|
||||
const scope = card.querySelectorAll('.qe-opt.qe-drag-over');
|
||||
scope.forEach(el => el.classList.remove('qe-drag-over'));
|
||||
if (Number(opt.dataset.oi) !== dragState.oi) opt.classList.add('qe-drag-over');
|
||||
}
|
||||
|
||||
function onDrop(e) {
|
||||
if (!dragState) return;
|
||||
const card = e.target.closest('.qe-q');
|
||||
if (!card) return;
|
||||
e.preventDefault();
|
||||
if (dragState.type === 'question') {
|
||||
const target = Number(card.dataset.qi);
|
||||
if (target !== dragState.qi) moveItem(state.questions, dragState.qi, target);
|
||||
} else {
|
||||
const opt = e.target.closest('.qe-opt');
|
||||
if (!opt || Number(card.dataset.qi) !== dragState.qi) { clearDragMarks(); dragState = null; return; }
|
||||
const target = Number(opt.dataset.oi);
|
||||
const opts = state.questions[dragState.qi].options;
|
||||
if (target !== dragState.oi) moveItem(opts, dragState.oi, target);
|
||||
}
|
||||
dragState = null;
|
||||
clearDragMarks();
|
||||
markDirty();
|
||||
renderQuestions();
|
||||
}
|
||||
|
||||
function onClick(e) {
|
||||
const btn = e.target.closest('[data-act]');
|
||||
if (!btn) return;
|
||||
const act = btn.dataset.act;
|
||||
if (act === 'add-option') {
|
||||
const qi = Number(btn.dataset.qi);
|
||||
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] });
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
}
|
||||
if (act === 'del-option') {
|
||||
const qi = Number(btn.closest('[data-qi]').dataset.qi);
|
||||
const oi = Number(btn.dataset.oi);
|
||||
state.questions[qi].options.splice(oi, 1);
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
}
|
||||
if (act === 'del-question') {
|
||||
const qi = Number(btn.dataset.qi);
|
||||
if (!confirm('Удалить вопрос?')) return;
|
||||
state.questions.splice(qi, 1);
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
}
|
||||
if (act === 'up' || act === 'down') {
|
||||
const qi = Number(btn.dataset.qi);
|
||||
const target = act === 'up' ? qi - 1 : qi + 1;
|
||||
if (target < 0 || target >= state.questions.length) return;
|
||||
moveItem(state.questions, qi, target);
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
}
|
||||
if (act === 'upload') {
|
||||
const owner = btn.dataset.owner;
|
||||
pickFile(file => uploadAsset(owner, file));
|
||||
return;
|
||||
}
|
||||
if (act === 'del-asset') {
|
||||
deleteAsset(btn.dataset.owner, btn.dataset.asset);
|
||||
return;
|
||||
}
|
||||
if (act === 'del-cover') {
|
||||
deleteCover();
|
||||
return;
|
||||
}
|
||||
if (act === 'copy-anon') {
|
||||
const input = document.getElementById('qeAnonUrl');
|
||||
input.select();
|
||||
const done = () => showToast('Ссылка скопирована');
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) {
|
||||
navigator.clipboard.writeText(input.value).then(done, () => { document.execCommand('copy'); done(); });
|
||||
} else {
|
||||
document.execCommand('copy');
|
||||
done();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.getElementById('qeName').addEventListener('input', e => {
|
||||
state.quiz.title = e.target.value;
|
||||
document.getElementById('qeBarTitle').textContent = e.target.value || 'Без названия';
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeDesc').addEventListener('input', e => {
|
||||
state.quiz.description = e.target.value;
|
||||
markDirty();
|
||||
if (!document.getElementById('qeDescPreview').hidden) renderPreview();
|
||||
});
|
||||
document.getElementById('qeDescPreviewBtn').addEventListener('click', () => {
|
||||
const box = document.getElementById('qeDescPreview');
|
||||
box.hidden = !box.hidden;
|
||||
renderPreview();
|
||||
});
|
||||
document.getElementById('qePass').addEventListener('input', e => {
|
||||
state.quiz.pass_percent = e.target.value === '' ? '' : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeAttempts').addEventListener('input', e => {
|
||||
state.quiz.max_attempts = e.target.value === '' ? '' : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeTime').addEventListener('input', e => {
|
||||
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeAnonymous'].forEach(id => {
|
||||
document.getElementById(id).addEventListener('change', e => {
|
||||
const map = {
|
||||
qePublished: 'is_published',
|
||||
qeShuffleQ: 'shuffle_questions',
|
||||
qeShuffleO: 'shuffle_options',
|
||||
qeShowResults: 'show_results',
|
||||
qeAnonymous: 'allow_anonymous',
|
||||
};
|
||||
state.quiz[map[id]] = e.target.checked;
|
||||
markDirty();
|
||||
if (id === 'qePublished' || id === 'qeAnonymous') renderAnon();
|
||||
});
|
||||
});
|
||||
document.getElementById('qeKindSeg').addEventListener('click', e => {
|
||||
const btn = e.target.closest('[data-kind]');
|
||||
if (!btn) return;
|
||||
if (state.quiz.kind === btn.dataset.kind) return;
|
||||
state.quiz.kind = btn.dataset.kind;
|
||||
if (state.quiz.kind !== 'survey') state.quiz.allow_anonymous = false;
|
||||
markDirty();
|
||||
renderSide();
|
||||
renderQuestions();
|
||||
});
|
||||
document.getElementById('qeAddQuestion').addEventListener('click', () => {
|
||||
state.questions.push({
|
||||
id: null,
|
||||
kind: 'single',
|
||||
text: '',
|
||||
description: '',
|
||||
weight: 1,
|
||||
partial_credit: false,
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
text_match: 'exact',
|
||||
accepted_answers: [],
|
||||
assets: [],
|
||||
options: [
|
||||
{ id: null, text: '', description: '', is_correct: true, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
|
||||
],
|
||||
});
|
||||
markDirty();
|
||||
renderAll();
|
||||
});
|
||||
document.getElementById('qeSaveBtn').addEventListener('click', save);
|
||||
document.getElementById('qeCoverFile').addEventListener('change', e => {
|
||||
const file = e.target.files && e.target.files[0];
|
||||
if (file) uploadCover(file);
|
||||
e.target.value = '';
|
||||
});
|
||||
document.getElementById('qeAssetFile').addEventListener('change', e => {
|
||||
const file = e.target.files && e.target.files[0];
|
||||
if (file) uploadAsset('quiz', file);
|
||||
e.target.value = '';
|
||||
});
|
||||
|
||||
const wrap = document.getElementById('qeQuestions');
|
||||
wrap.addEventListener('dragstart', onDragStart);
|
||||
wrap.addEventListener('dragover', onDragOver);
|
||||
wrap.addEventListener('drop', onDrop);
|
||||
wrap.addEventListener('dragend', () => { dragState = null; clearDragMarks(); });
|
||||
wrap.addEventListener('change', e => {
|
||||
const cap = e.target.closest('[data-cap-asset]');
|
||||
if (cap) saveCaption(cap);
|
||||
});
|
||||
|
||||
document.addEventListener('input', onField);
|
||||
document.addEventListener('change', onField);
|
||||
document.addEventListener('click', onClick);
|
||||
document.addEventListener('keydown', e => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
}
|
||||
});
|
||||
window.addEventListener('beforeunload', e => {
|
||||
if (!dirty) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
});
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (!Number.isInteger(quizId) || quizId < 1) {
|
||||
showToast('Неверный адрес теста', true);
|
||||
return;
|
||||
}
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
bind();
|
||||
await load();
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
@@ -0,0 +1,354 @@
|
||||
(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, '>')
|
||||
.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 = `<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 freeAnswerHtml(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}`;
|
||||
}
|
||||
|
||||
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">${esc2(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">${esc2(q.description)}</div>` : ''}
|
||||
${assetsHtml(q.assets)}
|
||||
<div style="margin-top:8px">${body}</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function introHtml() {
|
||||
const q = state.quiz;
|
||||
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 || 'Опрос')}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}</div>
|
||||
${q.description ? `<div class="qp-desc">${renderMd(q.description)}</div>` : ''}
|
||||
${assetsHtml(state.quizAssets)}
|
||||
<div class="qp-actions">
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
<span class="qp-hint">Ответы сохраняются без имени и входа в систему.</span>
|
||||
</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) {
|
||||
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' });
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
|
||||
<div class="qp-done-ic">✓</div>
|
||||
<div class="qp-title">Спасибо!</div>
|
||||
<p class="qp-hint" style="margin-top:8px">Ответы сохранены.</p>
|
||||
<div class="qp-actions" style="justify-content:center">
|
||||
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
|
||||
</div>
|
||||
</div>`;
|
||||
} 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 = '<div class="qp-error">Неверная ссылка на опрос</div>';
|
||||
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 || [];
|
||||
document.title = (state.quiz.title || 'Опрос') + ' — опрос';
|
||||
render();
|
||||
} catch (e) {
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-error">${esc2(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
@@ -0,0 +1,612 @@
|
||||
(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 = `<img src="${at(thumbSrc(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"><i data-lucide="file"></i> ${esc(a.original_name || 'Файл')}</a>`;
|
||||
}
|
||||
return `<div class="qz-asset">${inner}${a.caption ? `<div class="qz-asset-cap">${esc(a.caption)}</div>` : ''}</div>`;
|
||||
});
|
||||
return `<div class="qz-assets">${cards.join('')}</div>`;
|
||||
}
|
||||
|
||||
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 = [
|
||||
`<div class="qz-head">`,
|
||||
q.cover_path
|
||||
? `<img class="qz-head-cover" src="${at(thumbSrc(q.cover_path))}" data-img="${at(API + q.cover_path)}" alt="Обложка">`
|
||||
: '',
|
||||
`<div class="qz-head-main">`,
|
||||
`<div class="qz-title">${esc(q.title || 'Без названия')}</div>`,
|
||||
`<div class="qz-sub">`,
|
||||
`<span>${kindLabel(q.kind)}</span>`,
|
||||
`<span>Вопросов: ${state.questions.length}</span>`,
|
||||
q.author_name ? `<span>Автор: ${esc(q.author_name)}</span>` : '',
|
||||
q.max_attempts != null ? `<span>Попыток: ${q.max_attempts}</span>` : '',
|
||||
q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : '',
|
||||
q.kind === 'test' ? `<span>Порог: ${q.pass_percent}%</span>` : '',
|
||||
`</div>`,
|
||||
`<div class="qz-badges">`,
|
||||
`<span class="qz-badge${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`,
|
||||
state.quiz.can_edit ? '<span class="qz-badge on">Редактирование доступно</span>' : '',
|
||||
`</div>`,
|
||||
q.description ? `<div class="qz-desc">${renderMd(q.description)}</div>` : '',
|
||||
`</div>`,
|
||||
`</div>`,
|
||||
];
|
||||
if (state.quizAssets.length) {
|
||||
parts.push(`<div class="qz-panel"><div class="qz-hint" style="margin-bottom:6px">Материалы</div>${assetsHtml(state.quizAssets)}</div>`);
|
||||
}
|
||||
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 `<div class="qz-panel"><p class="qz-hint" style="margin:0 0 10px">Попытки закончились.</p>
|
||||
${state.quiz.my_attempts.length ? `<a class="btn-primary ghost" href="#" data-act="open-attempt" data-attempt="${state.quiz.my_attempts[0].id}">Посмотреть последний результат</a>` : ''}</div>`;
|
||||
}
|
||||
if (!q.is_published) {
|
||||
return '<div class="qz-panel"><p class="qz-hint" style="margin:0">Тест не опубликован. Пройти его может только автор после публикации.</p></div>';
|
||||
}
|
||||
return `<div class="qz-panel">
|
||||
<div class="qz-sub" style="margin:0 0 10px">
|
||||
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
|
||||
${q.time_limit_min ? ` На прохождение отводится ${q.time_limit_min} мин.` : ''}
|
||||
</div>
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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
|
||||
? `<div class="qz-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">${esc(value)}</textarea>${hint}`;
|
||||
}
|
||||
if (q.kind === 'number') {
|
||||
return `<input type="number" step="any" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Число" value="${esc(value)}">`;
|
||||
}
|
||||
if (q.kind === 'date') {
|
||||
return `<input type="date" class="settings-input qz-answer" data-qtext="${q.id}" value="${esc(value)}">`;
|
||||
}
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc(value)}">${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 = `<select class="settings-input qz-answer" data-q="${q.id}">
|
||||
<option value="">— выберите —</option>
|
||||
${opts.map(o => `<option value="${o.id}"${chosen.has(Number(o.id)) ? ' selected' : ''}>${esc(o.text)}</option>`).join('')}
|
||||
</select>${opts.map(o => o.description ? `<div class="qz-opt-desc" style="margin-top:6px">${esc(o.text)} — ${esc(o.description)}</div>` : '').join('')}`;
|
||||
} else {
|
||||
const items = opts.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">${esc(o.text)}${o.description ? `<div class="qz-opt-desc">${esc(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">${esc(q.text)}</span>
|
||||
</div>
|
||||
${q.description ? `<div class="qz-q-desc">${esc(q.description)}</div>` : ''}
|
||||
${assetsHtml(q.assets)}
|
||||
<div style="margin-top:8px">${body}</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
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 = `<div class="qz-actions" style="margin-bottom:12px">
|
||||
<span class="qz-timer" id="qzTimer"${deadline ? '' : ' hidden'}>—</span>
|
||||
<span class="qz-hint" style="margin:0">Отвечено: <b id="qzProgress">0</b> из ${state.questions.length}</span>
|
||||
<span style="flex:1"></span>
|
||||
<button type="button" class="btn-link" data-act="restart">Начать заново</button>
|
||||
<button type="button" class="btn-primary" data-act="submit">Отправить ответы</button>
|
||||
</div>
|
||||
<div id="qzQuestions">${list}</div>
|
||||
<div class="qz-actions"><button type="button" class="btn-primary" data-act="submit">Отправить ответы</button></div>`;
|
||||
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 = `<div class="qz-panel">
|
||||
<div class="qz-sub">${kindLabel(state.quiz.kind)} · ${fmtDateTime(attempt.finished_at || attempt.started_at)}</div>
|
||||
${state.quiz.kind === 'test'
|
||||
? `<div class="qz-score">${Number(attempt.score || 0).toFixed(2)} <small>из ${Number(attempt.max_score || 0).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||||
<div class="qz-bar ${attempt.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>
|
||||
<div class="qz-badges"><span class="qz-badge ${attempt.passed ? 'on' : 'warn'}">${attempt.passed ? 'Сдано' : 'Не сдано'}</span></div>`
|
||||
: '<div class="qz-hint" style="margin-top:6px">Ответы сохранены. Опрос не оценивается.</div>'}
|
||||
</div>`;
|
||||
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
|
||||
? '<span class="qz-check ok">верно</span>'
|
||||
: '<span class="qz-check bad">неверно</span>';
|
||||
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 ? `<div class="qz-hint">Ответ: ${esc(picked.join(', '))}</div>` : '';
|
||||
return `<section class="qz-q">
|
||||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(r.text || '')}</span>
|
||||
<span style="flex:1"></span>${mark}
|
||||
${state.quiz.kind === 'test' && r.max_score ? `<span class="qz-hint">${Number(r.score).toFixed(2)} / ${Number(r.max_score).toFixed(2)}</span>` : ''}
|
||||
</div>
|
||||
${pickedHtml}
|
||||
${r.text_answer ? `<div class="qz-hint">Ответ: ${esc(r.text_answer)}</div>` : ''}
|
||||
</section>`;
|
||||
}).join('');
|
||||
} else if (state.quiz.kind === 'test') {
|
||||
details = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Автор теста скрыл разбор ответов.</p></div>';
|
||||
}
|
||||
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 = `<div class="qz-panel">
|
||||
<div class="qz-sub">${esc(a.user_name || '')} · ${fmtDateTime(a.finished_at || a.started_at)}</div>
|
||||
${state.quiz.kind === 'test'
|
||||
? `<div class="qz-score">${Number(a.score).toFixed(2)} <small>из ${Number(a.max_score).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||||
<div class="qz-bar ${a.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>`
|
||||
: '<div class="qz-hint" style="margin-top:6px">Опрос не оценивается.</div>'}
|
||||
</div>`;
|
||||
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 `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">вес ${o.weight}</span>` : ''}</div>`;
|
||||
}).join('')
|
||||
: '';
|
||||
return `<section class="qz-q">
|
||||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(row.question_text || '')}</span>
|
||||
<span style="flex:1"></span>
|
||||
${data.revealed && row.is_correct !== null ? `<span class="qz-check ${row.is_correct ? 'ok' : 'bad'}">${row.is_correct ? 'верно' : 'неверно'}</span>` : ''}
|
||||
${data.revealed && state.quiz.kind === 'test' ? `<span class="qz-hint">${Number(row.score).toFixed(2)} / ${Number(row.max_score).toFixed(2)}</span>` : ''}
|
||||
</div>
|
||||
${row.text_answer ? `<div class="qz-hint">Ответ: ${esc(row.text_answer)}</div>` : ''}
|
||||
${opts}
|
||||
</section>`;
|
||||
}).join('');
|
||||
body.innerHTML = head + (rows || '<div class="qz-panel"><p class="qz-hint" style="margin:0">Ответов нет.</p></div>')
|
||||
+ '<div class="qz-actions"><button type="button" class="btn-primary ghost" data-act="tab" data-tab="attempts">К списку попыток</button></div>';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function renderAttempts() {
|
||||
const body = document.getElementById('qzBody');
|
||||
body.innerHTML = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Загрузка...</p></div>';
|
||||
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 = '<div class="qz-empty">Попыток пока нет</div>';
|
||||
return;
|
||||
}
|
||||
const rows = items.map(a => `<tr>
|
||||
<td>${esc(a.user_name || '—')}</td>
|
||||
<td>${fmtDateTime(a.finished_at || a.started_at)}</td>
|
||||
${state.quiz.kind === 'test' ? `<td>${Number(a.score).toFixed(2)} / ${Number(a.max_score).toFixed(2)}</td>
|
||||
<td>${Number(a.percent).toFixed(1)}%</td>
|
||||
<td>${a.passed ? '<span class="qz-check ok">сдано</span>' : '<span class="qz-check bad">не сдано</span>'}</td>` : '<td>—</td>'}
|
||||
<td><button type="button" class="btn-link" data-act="open-attempt" data-attempt="${a.id}">Открыть</button></td>
|
||||
</tr>`).join('');
|
||||
body.innerHTML = `<div class="qz-panel"><table class="qz-table">
|
||||
<thead><tr><th>Пользователь</th><th>Дата</th>${state.quiz.kind === 'test' ? '<th>Баллы</th><th>Процент</th><th>Итог</th>' : '<th>Оценка</th>'}<th></th></tr></thead>
|
||||
<tbody>${rows}</tbody></table>
|
||||
<div class="qz-hint" style="margin-top:8px">Всего попыток: ${data.total}</div></div>`;
|
||||
} catch (e) {
|
||||
body.innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function renderStats() {
|
||||
const body = document.getElementById('qzBody');
|
||||
body.innerHTML = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Загрузка...</p></div>';
|
||||
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 = `<div class="qz-panel">
|
||||
<div class="qz-sub" style="margin:0">
|
||||
<span>Попыток: <b>${totalAttempts}</b></span>
|
||||
<span>Участников: <b>${Number(t.users || 0)}</b></span>
|
||||
${state.quiz.kind === 'test' ? `<span>Средний результат: <b>${Number(t.avg_percent || 0).toFixed(1)}%</b></span>
|
||||
<span>Сдали: <b>${Number(t.passed || 0)}</b></span>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
const questions = (data.questions || []).map((q, i) => {
|
||||
const opts = (q.options || []).map(o => {
|
||||
const share = totalAttempts ? (o.count / totalAttempts) * 100 : 0;
|
||||
return `<div style="margin-top:8px">
|
||||
<div class="qz-stat-row"><span>${esc(o.text)}${o.is_correct ? ' <span class="qz-check ok">✓</span>' : ''}</span><span>${o.count} · ${share.toFixed(0)}%</span></div>
|
||||
<div class="qz-bar${o.is_correct ? ' ok' : ''}"><span style="width:${Math.max(0, Math.min(100, share))}%"></span></div>
|
||||
</div>`;
|
||||
}).join('');
|
||||
const texts = (q.texts || []).length
|
||||
? `<div class="qz-hint" style="margin-top:8px">Текстовые ответы (${q.texts.length}): ${q.texts.slice(0, 20).map(x => `«${esc(x)}»`).join(', ')}${q.texts.length > 20 ? ' …' : ''}</div>`
|
||||
: '';
|
||||
return `<section class="qz-q">
|
||||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(q.text)}</span></div>
|
||||
${opts}${texts}
|
||||
</section>`;
|
||||
}).join('');
|
||||
body.innerHTML = head + (questions || '<div class="qz-empty">Вопросов нет</div>');
|
||||
renderIcons();
|
||||
} catch (e) {
|
||||
body.innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
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 = '<div class="qz-error">Неверный адрес теста</div>';
|
||||
return;
|
||||
}
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
bind();
|
||||
try {
|
||||
await loadQuiz(false);
|
||||
renderHead();
|
||||
renderTab();
|
||||
} catch (e) {
|
||||
document.getElementById('qzHead').innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
@@ -0,0 +1,216 @@
|
||||
(function () {
|
||||
let items = [];
|
||||
let loading = false;
|
||||
let deletedMode = false;
|
||||
|
||||
function attr(s) {
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function filters() {
|
||||
return {
|
||||
search: document.getElementById('quizSearch').value.trim(),
|
||||
kind: document.getElementById('quizKindFilter').value,
|
||||
mine: document.getElementById('quizMineOnly').checked ? '1' : '',
|
||||
deleted: document.getElementById('quizDeletedOnly').checked ? '1' : '',
|
||||
};
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return kind === 'survey' ? 'Опрос' : 'Тест';
|
||||
}
|
||||
|
||||
function cardHtml(q) {
|
||||
const cover = q.cover_path
|
||||
? `<img src="${attr(thumbSrc(q.cover_path))}" alt="">`
|
||||
: '<span class="quiz-cover-ic"><i data-lucide="clipboard-list"></i></span>';
|
||||
const flags = [];
|
||||
flags.push(`<span class="quiz-flag${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`);
|
||||
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Анонимный</span>');
|
||||
if (q.deleted_at) flags.push('<span class="quiz-flag del">Удалён</span>');
|
||||
const attempts = q.kind === 'test'
|
||||
? `Попыток: <b>${q.attempt_count}</b>${q.my_attempt_count ? ` · моих: <b>${q.my_attempt_count}</b>` : ''}`
|
||||
: `Ответов: <b>${q.attempt_count}</b>`;
|
||||
const actions = [];
|
||||
if (q.deleted_at) {
|
||||
if (q.can_edit) {
|
||||
actions.push(`<button type="button" class="btn-link" data-restore="${q.id}">Восстановить</button>`);
|
||||
actions.push(`<button type="button" class="btn-link danger" data-perm="${q.id}">Удалить навсегда</button>`);
|
||||
}
|
||||
} else {
|
||||
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}">Пройти</a>`);
|
||||
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}">Изменить</a>`);
|
||||
if (q.can_edit) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}">Статистика</button>`);
|
||||
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}">Удалить</button>`);
|
||||
}
|
||||
return `<article class="quiz-card" data-open="${q.deleted_at ? '' : q.id}">
|
||||
<div class="quiz-cover">${cover}<span class="quiz-kind-badge${q.kind === 'survey' ? ' survey' : ''}">${kindLabel(q.kind)}</span></div>
|
||||
<div class="quiz-body">
|
||||
<div class="quiz-title">${esc(q.title || 'Без названия')}</div>
|
||||
${q.description ? `<div class="quiz-desc">${esc(q.description)}</div>` : ''}
|
||||
<div class="quiz-meta">
|
||||
<span>Вопросов: <b>${q.question_count}</b></span>
|
||||
<span>${attempts}</span>
|
||||
</div>
|
||||
<div class="quiz-meta">
|
||||
<span>${esc(q.author_name || 'Автор удалён')}</span>
|
||||
<span>${fmtDateTime(q.updated_at)}</span>
|
||||
</div>
|
||||
<div class="quiz-flags">${flags.join('')}</div>
|
||||
</div>
|
||||
<div class="quiz-foot">${actions.join('')}</div>
|
||||
</article>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const list = document.getElementById('quizList');
|
||||
const empty = document.getElementById('quizEmpty');
|
||||
if (loading) {
|
||||
list.innerHTML = '';
|
||||
empty.hidden = true;
|
||||
return;
|
||||
}
|
||||
if (!items.length) {
|
||||
list.innerHTML = '';
|
||||
empty.hidden = false;
|
||||
empty.textContent = deletedMode ? 'В корзине нет тестов' : 'Тестов пока нет';
|
||||
return;
|
||||
}
|
||||
empty.hidden = true;
|
||||
list.innerHTML = items.map(cardHtml).join('');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function load() {
|
||||
loading = true;
|
||||
render();
|
||||
const f = filters();
|
||||
deletedMode = !!f.deleted;
|
||||
const params = new URLSearchParams();
|
||||
if (f.search) params.set('search', f.search);
|
||||
if (f.kind) params.set('kind', f.kind);
|
||||
if (f.mine) params.set('mine', f.mine);
|
||||
if (f.deleted) params.set('deleted', f.deleted);
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тесты');
|
||||
items = Array.isArray(data.items) ? data.items : [];
|
||||
} catch (e) {
|
||||
items = [];
|
||||
loading = false;
|
||||
const list = document.getElementById('quizList');
|
||||
const empty = document.getElementById('quizEmpty');
|
||||
list.innerHTML = '';
|
||||
empty.hidden = false;
|
||||
empty.className = 'quiz-error';
|
||||
empty.innerHTML = `${esc(e.message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
|
||||
document.getElementById('quizRetry').addEventListener('click', () => {
|
||||
empty.className = 'quiz-empty';
|
||||
load();
|
||||
});
|
||||
return;
|
||||
}
|
||||
loading = false;
|
||||
render();
|
||||
}
|
||||
|
||||
async function createQuiz(kind) {
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes', {
|
||||
method: 'POST',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ kind }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось создать');
|
||||
location.href = 'quiz-edit.html?id=' + data.quiz.id;
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function removeQuiz(id) {
|
||||
if (!confirm('Удалить тест? Он попадёт в корзину и будет удалён окончательно по истечении срока.')) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + id, { method: 'DELETE', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось удалить');
|
||||
showToast('Тест удалён');
|
||||
await load();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function restoreQuiz(id) {
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + id + '/restore', { method: 'PUT', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось восстановить');
|
||||
showToast('Тест восстановлен');
|
||||
await load();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function purgeQuiz(id) {
|
||||
if (!confirm('Удалить тест навсегда вместе с вопросами и файлами?')) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + id + '/permanent', { method: 'DELETE', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось удалить');
|
||||
showToast('Тест удалён навсегда');
|
||||
await load();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.getElementById('quizNewTestBtn').addEventListener('click', () => createQuiz('test'));
|
||||
document.getElementById('quizNewSurveyBtn').addEventListener('click', () => createQuiz('survey'));
|
||||
document.getElementById('quizSearch').addEventListener('input', () => {
|
||||
clearTimeout(bind.t);
|
||||
bind.t = setTimeout(load, 300);
|
||||
});
|
||||
document.getElementById('quizKindFilter').addEventListener('change', load);
|
||||
document.getElementById('quizMineOnly').addEventListener('change', load);
|
||||
document.getElementById('quizDeletedOnly').addEventListener('change', load);
|
||||
|
||||
document.addEventListener('click', e => {
|
||||
const del = e.target.closest('[data-del]');
|
||||
if (del) { e.preventDefault(); removeQuiz(del.dataset.del); return; }
|
||||
const restore = e.target.closest('[data-restore]');
|
||||
if (restore) { e.preventDefault(); restoreQuiz(restore.dataset.restore); return; }
|
||||
const perm = e.target.closest('[data-perm]');
|
||||
if (perm) { e.preventDefault(); purgeQuiz(perm.dataset.perm); return; }
|
||||
const stats = e.target.closest('[data-stats]');
|
||||
if (stats) { e.preventDefault(); location.href = 'quiz.html?id=' + stats.dataset.stats + '&tab=stats'; return; }
|
||||
if (e.target.closest('a')) return;
|
||||
const card = e.target.closest('[data-open]');
|
||||
if (card && card.dataset.open) location.href = 'quiz.html?id=' + card.dataset.open;
|
||||
});
|
||||
}
|
||||
|
||||
function connectLive() {
|
||||
let t = null;
|
||||
const es = new EventSource(API + '/api/events?token=' + encodeURIComponent(token || ''));
|
||||
es.addEventListener('quizzes_changed', () => {
|
||||
clearTimeout(t);
|
||||
t = setTimeout(load, 400);
|
||||
});
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
bind();
|
||||
renderIcons();
|
||||
await load();
|
||||
connectLive();
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
Reference in New Issue
Block a user