Тесты и опросы: критерии оценки, génération ИИ, улучшения конструктора и прохождения
- lib/quizzes.js: система criterial-оценки (quiz_grade_scales/quiz_grade_ranges), подсчёт баллов, попытки, anon-опросы, системные поля, доступ по коду - lib/quiz-grades.js: CRUD критериев оценки, диапазоны, картинки - lib/quiz-ai.js: генерация черновика теста через ИИ - server.js: роуты тестов, критериев, медиа-ассетов, попыток - db/init.sql + db/migration.sql: таблицы quizzes*, валидация и индексы - public/: конструктор, прохождение, публичная страница, список, критерии оценки - quiz.selftest.js, quiz-ai.selftest.js: юнит-проверки
This commit is contained in:
@@ -9,6 +9,16 @@
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function canManage(s) {
|
||||
if (!s || typeof currentUser === 'undefined' || !currentUser) return false;
|
||||
if (currentUser.role === 'admin') return true;
|
||||
return s.created_by != null && Number(s.created_by) === Number(currentUser.id);
|
||||
}
|
||||
|
||||
function isAdmin() {
|
||||
return typeof currentUser !== 'undefined' && !!currentUser && currentUser.role === 'admin';
|
||||
}
|
||||
|
||||
function openModal(id) {
|
||||
const node = el(id);
|
||||
if (node) node.classList.add('open');
|
||||
@@ -46,16 +56,19 @@
|
||||
const ranges = (s.ranges || []).map(r =>
|
||||
`<span class="qs-range-chip">${esc(String(r.min_score))}–${esc(String(r.max_score))}: ${esc(r.label || '')}</span>`
|
||||
).join('');
|
||||
const acts = canManage(s)
|
||||
? `<div class="qs-item-acts">
|
||||
<button type="button" class="btn-link" data-qs-edit="${s.id}">Изменить</button>
|
||||
<button type="button" class="btn-link danger" data-qs-del="${s.id}">Удалить</button>
|
||||
</div>`
|
||||
: '';
|
||||
return `<div class="qs-item">
|
||||
<div class="qs-item-head">
|
||||
<div class="qs-item-main">
|
||||
<div class="qs-item-name">${esc(s.name || '')}</div>
|
||||
<div class="qs-item-name">${esc(s.name || '')}${s.is_shared ? ' <span class="qs-tag">Доступна всем</span>' : ''}</div>
|
||||
${s.description ? `<div class="qs-item-desc">${esc(s.description)}</div>` : ''}
|
||||
</div>
|
||||
<div class="qs-item-acts">
|
||||
<button type="button" class="btn-link" data-qs-edit="${s.id}">Изменить</button>
|
||||
<button type="button" class="btn-link danger" data-qs-del="${s.id}">Удалить</button>
|
||||
</div>
|
||||
${acts}
|
||||
</div>
|
||||
<div class="qs-item-ranges">${ranges || '<span class="qs-range-chip">нет диапазонов</span>'}</div>
|
||||
</div>`;
|
||||
@@ -68,6 +81,7 @@
|
||||
name: '',
|
||||
description: '',
|
||||
sort_order: 0,
|
||||
is_shared: false,
|
||||
ranges: [{ min_score: 0, max_score: '', label: '', image_path: null }],
|
||||
};
|
||||
}
|
||||
@@ -93,6 +107,8 @@
|
||||
el('qsName').value = d.name;
|
||||
el('qsDesc').value = d.description;
|
||||
el('qsSort').value = d.sort_order;
|
||||
el('qsPublicField').hidden = !isAdmin();
|
||||
el('qsPublic').checked = isAdmin() && d.is_shared === true;
|
||||
el('qsEditorTitle').textContent = d.id ? 'Изменить критерий' : 'Новый критерий оценки';
|
||||
renderRanges();
|
||||
}
|
||||
@@ -111,6 +127,7 @@
|
||||
name: s.name || '',
|
||||
description: s.description || '',
|
||||
sort_order: Number(s.sort_order) || 0,
|
||||
is_shared: s.is_shared === true,
|
||||
ranges: (s.ranges || []).map(r => ({
|
||||
min_score: Number(r.min_score),
|
||||
max_score: Number(r.max_score),
|
||||
@@ -143,6 +160,7 @@
|
||||
name,
|
||||
description: el('qsDesc').value.trim(),
|
||||
sort_order: Number(el('qsSort').value) || 0,
|
||||
is_shared: el('qsPublic').checked === true,
|
||||
ranges,
|
||||
};
|
||||
const btn = el('qsSaveBtn');
|
||||
|
||||
+71
-14
@@ -5,13 +5,18 @@
|
||||
let saving = false;
|
||||
let dragState = null;
|
||||
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const OPTION_KINDS = ['single', 'multiple', 'select'];
|
||||
|
||||
function isFree(kind) {
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isSystemKind(kind) {
|
||||
return SYSTEM_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function isOptionKind(kind) {
|
||||
return OPTION_KINDS.includes(kind);
|
||||
}
|
||||
@@ -24,6 +29,35 @@
|
||||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function round2(n) {
|
||||
return Math.round((Number(n) || 0) * 100) / 100;
|
||||
}
|
||||
|
||||
function isPlainFree(kind) {
|
||||
return kind === 'line' || kind === 'text' || kind === 'number' || kind === 'date';
|
||||
}
|
||||
|
||||
function questionPoints(q) {
|
||||
if (!state.quiz || state.quiz.kind !== 'test') return 0;
|
||||
if (isSystemKind(q.kind)) return 0;
|
||||
if (isFree(q.kind)) return round2(Math.max(0, Number(q.weight) || 0));
|
||||
return round2((q.options || []).reduce((sum, o) => sum + (o.is_correct ? Math.max(0, Number(o.weight) || 0) : 0), 0));
|
||||
}
|
||||
|
||||
function updatePoints() {
|
||||
const isTest = !!(state.quiz && state.quiz.kind === 'test');
|
||||
const totalEl = document.getElementById('qeTotalPoints');
|
||||
if (totalEl) {
|
||||
totalEl.hidden = !isTest;
|
||||
if (isTest) totalEl.textContent = 'Всего баллов: ' + round2(state.questions.reduce((sum, q) => sum + questionPoints(q), 0));
|
||||
}
|
||||
document.querySelectorAll('[data-qpoints]').forEach(node => {
|
||||
const q = state.questions[Number(node.dataset.qpoints)];
|
||||
if (!q) return;
|
||||
node.textContent = 'Макс. баллов: ' + round2(questionPoints(q));
|
||||
});
|
||||
}
|
||||
|
||||
function assetName(a) {
|
||||
return String(a.path || '').split('/').pop();
|
||||
}
|
||||
@@ -71,8 +105,10 @@
|
||||
show_answers: quiz.show_answers !== false,
|
||||
grade_scale_id: quiz.grade_scale_id == null ? '' : quiz.grade_scale_id,
|
||||
allow_anonymous: quiz.allow_anonymous === true,
|
||||
access_code: quiz.access_code || '',
|
||||
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
|
||||
time_limit_min: quiz.time_limit_min || 0,
|
||||
retry_cooldown_min: Number(quiz.retry_cooldown_min) || 0,
|
||||
pass_percent: quiz.pass_percent == null ? 60 : quiz.pass_percent,
|
||||
cover_path: quiz.cover_path || null,
|
||||
};
|
||||
@@ -82,7 +118,7 @@
|
||||
kind: normalizeKind(q.kind),
|
||||
text: q.text || '',
|
||||
description: q.description || '',
|
||||
weight: q.weight == null ? 1 : Number(q.weight),
|
||||
weight: q.weight == null ? 0 : Number(q.weight),
|
||||
partial_credit: q.partial_credit === true,
|
||||
required: q.required !== false,
|
||||
min_length: Number(q.min_length) || 0,
|
||||
@@ -95,7 +131,7 @@
|
||||
text: o.text || '',
|
||||
description: o.description || '',
|
||||
is_correct: o.is_correct === true,
|
||||
weight: o.weight == null ? 1 : Number(o.weight),
|
||||
weight: o.weight == null ? 0 : Number(o.weight),
|
||||
assets: Array.isArray(o.assets) ? o.assets.slice() : [],
|
||||
})),
|
||||
}));
|
||||
@@ -114,8 +150,10 @@
|
||||
show_answers: q.show_answers,
|
||||
grade_scale_id: q.grade_scale_id === '' ? null : q.grade_scale_id,
|
||||
allow_anonymous: q.allow_anonymous,
|
||||
access_code: q.access_code || '',
|
||||
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
|
||||
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
|
||||
retry_cooldown_min: q.retry_cooldown_min === '' ? 0 : q.retry_cooldown_min,
|
||||
pass_percent: q.pass_percent === '' ? 60 : q.pass_percent,
|
||||
cover_path: q.cover_path,
|
||||
asset_ids: state.assets.map(a => a.id),
|
||||
@@ -175,7 +213,7 @@
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><small>Верный</small></span>
|
||||
</label>
|
||||
<label class="qe-weight" title="Вес ответа"><span>вес</span>
|
||||
<label class="qe-weight" title="Баллы за вариант"><span>балл</span>
|
||||
<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)}">
|
||||
</label>` : ''}
|
||||
<button type="button" class="icon-btn" data-act="del-option" data-oi="${oi}" title="Удалить вариант"><i data-lucide="trash-2"></i></button>
|
||||
@@ -189,7 +227,7 @@
|
||||
}
|
||||
|
||||
function acceptedHtml(q, qi, isTest) {
|
||||
if (!isFree(q.kind) || !isTest) return '';
|
||||
if (!isFree(q.kind) || !isTest || isSystemKind(q.kind)) return '';
|
||||
const hints = {
|
||||
line: 'Ответ вводится одной строкой. Регистр, «ё» и лишние пробелы не важны.',
|
||||
text: 'Ответ вводится многострочным текстом. Регистр, «ё» и лишние пробелы не важны.',
|
||||
@@ -212,7 +250,7 @@
|
||||
<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>
|
||||
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос задаётся полем «балл» у вопроса.</span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@@ -227,6 +265,10 @@
|
||||
['text', 'Многострочный текст'],
|
||||
['number', 'Число'],
|
||||
['date', 'Дата'],
|
||||
['student', 'Ученик — поиск по имени'],
|
||||
['group', 'Группа — поиск по названию'],
|
||||
['branch', 'Филиал — поиск по названию'],
|
||||
['module', 'Тема модуля — поиск по названию'],
|
||||
].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>
|
||||
@@ -236,7 +278,8 @@
|
||||
<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 ? `<label class="qe-weight" title="Вес вопроса"><span>вес</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
|
||||
${isTest && isPlainFree(q.kind) ? `<label class="qe-weight" title="Баллы за вопрос"><span>балл</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
|
||||
${isTest && !isSystemKind(q.kind) ? `<span class="qe-points" data-qpoints="${qi}">Макс. баллов: ${round2(questionPoints(q))}</span>` : ''}
|
||||
<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>
|
||||
@@ -275,10 +318,12 @@
|
||||
const wrap = document.getElementById('qeQuestions');
|
||||
if (!state.questions.length) {
|
||||
wrap.innerHTML = '<div class="qe-panel"><p class="qe-hint" style="margin:0">Вопросов пока нет. Добавьте первый вопрос.</p></div>';
|
||||
updatePoints();
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = state.questions.map(questionHtml).join('');
|
||||
renderIcons();
|
||||
updatePoints();
|
||||
}
|
||||
|
||||
function renderQuizAssets() {
|
||||
@@ -365,11 +410,13 @@
|
||||
document.getElementById('qePass').value = q.pass_percent;
|
||||
document.getElementById('qeAttempts').value = q.max_attempts;
|
||||
document.getElementById('qeTime').value = q.time_limit_min;
|
||||
document.getElementById('qeRetry').value = q.retry_cooldown_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.getElementById('qeShowAnswers').checked = q.show_answers;
|
||||
document.getElementById('qeAccessCode').value = q.access_code || '';
|
||||
document.getElementById('qeShowAnswersWrap').hidden = q.kind !== 'test';
|
||||
document.getElementById('qeGradeWrap').hidden = q.kind !== 'test';
|
||||
renderGradeSelect();
|
||||
@@ -574,8 +621,8 @@
|
||||
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: [] },
|
||||
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 0, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
|
||||
];
|
||||
}
|
||||
markDirty();
|
||||
@@ -602,6 +649,7 @@
|
||||
opt[field] = el.value;
|
||||
}
|
||||
markDirty();
|
||||
updatePoints();
|
||||
return;
|
||||
}
|
||||
if (el.dataset.qi !== undefined) {
|
||||
@@ -622,6 +670,7 @@
|
||||
q.text_match = el.value === 'contains' ? 'contains' : 'exact';
|
||||
} else q[field] = el.value;
|
||||
markDirty();
|
||||
updatePoints();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -703,7 +752,7 @@
|
||||
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: [] });
|
||||
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] });
|
||||
markDirty();
|
||||
renderAll();
|
||||
return;
|
||||
@@ -787,6 +836,14 @@
|
||||
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeRetry').addEventListener('input', e => {
|
||||
state.quiz.retry_cooldown_min = e.target.value === '' ? 0 : Number(e.target.value);
|
||||
markDirty();
|
||||
});
|
||||
document.getElementById('qeAccessCode').addEventListener('input', e => {
|
||||
state.quiz.access_code = e.target.value;
|
||||
markDirty();
|
||||
});
|
||||
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeShowAnswers', 'qeAnonymous'].forEach(id => {
|
||||
document.getElementById(id).addEventListener('change', e => {
|
||||
const map = {
|
||||
@@ -821,8 +878,8 @@
|
||||
kind: 'single',
|
||||
text: '',
|
||||
description: '',
|
||||
weight: 1,
|
||||
partial_credit: false,
|
||||
weight: 0,
|
||||
partial_credit: true,
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
@@ -830,8 +887,8 @@
|
||||
accepted_answers: [],
|
||||
assets: [],
|
||||
options: [
|
||||
{ id: null, text: '', description: '', is_correct: true, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: true, weight: 0, assets: [] },
|
||||
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
|
||||
],
|
||||
});
|
||||
markDirty();
|
||||
|
||||
+168
-16
@@ -1,7 +1,9 @@
|
||||
(function () {
|
||||
const API = location.origin;
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
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: [],
|
||||
@@ -9,9 +11,14 @@
|
||||
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_' + (Number.isInteger(quizId) ? quizId : '');
|
||||
let retryTimer = null;
|
||||
|
||||
function esc2(v) {
|
||||
return String(v == null ? '' : v)
|
||||
@@ -60,6 +67,54 @@
|
||||
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 => {
|
||||
@@ -82,7 +137,23 @@
|
||||
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>`
|
||||
@@ -99,6 +170,34 @@
|
||||
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/' + quizId + '/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;
|
||||
@@ -130,16 +229,23 @@
|
||||
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>` : ''}${isTest ? `<span>${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}</span>` : ''}</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">
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
<span class="qp-hint">${isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.'}</span>
|
||||
${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>`;
|
||||
}
|
||||
|
||||
@@ -163,11 +269,16 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,16 +322,21 @@
|
||||
}
|
||||
|
||||
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/' + quizId + '/attempts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({}),
|
||||
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,
|
||||
@@ -264,6 +380,7 @@
|
||||
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>
|
||||
@@ -272,7 +389,9 @@
|
||||
<p class="qp-hint" style="margin-top:8px">${esc2(hint)}</p>
|
||||
${details}
|
||||
<div class="qp-actions" style="justify-content:center">
|
||||
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
|
||||
${until
|
||||
? `<span class="qp-hint">${esc2(retryLeftText(until))}</span>`
|
||||
: '<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>'}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -280,6 +399,19 @@
|
||||
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;
|
||||
@@ -289,13 +421,6 @@
|
||||
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;
|
||||
@@ -303,17 +428,19 @@
|
||||
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/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: state.attempt.anon_token, answers }),
|
||||
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);
|
||||
@@ -345,12 +472,37 @@
|
||||
}
|
||||
});
|
||||
document.addEventListener('input', e => {
|
||||
if (e.target.dataset.qtext) {
|
||||
state.texts.set(Number(e.target.dataset.qtext), e.target.value);
|
||||
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; }
|
||||
|
||||
+164
-11
@@ -1,5 +1,7 @@
|
||||
(function () {
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
|
||||
const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' };
|
||||
const params = new URLSearchParams(location.search);
|
||||
const quizId = parseInt(params.get('id'), 10);
|
||||
const state = {
|
||||
@@ -9,7 +11,10 @@
|
||||
attempt: null,
|
||||
selection: new Map(),
|
||||
texts: new Map(),
|
||||
systemIds: new Map(),
|
||||
sugTimers: new Map(),
|
||||
timer: null,
|
||||
retryTimer: null,
|
||||
result: null,
|
||||
revealed: false,
|
||||
tab: params.get('tab') === 'stats' ? 'stats' : params.get('tab') === 'attempts' ? 'attempts' : 'take',
|
||||
@@ -54,6 +59,58 @@
|
||||
return arr;
|
||||
}
|
||||
|
||||
function retryKey() {
|
||||
return 'whatido_quiz_retry_' + quizId;
|
||||
}
|
||||
|
||||
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(retryKey()); } 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(retryKey()); } catch (e) { /* ignore */ }
|
||||
return 0;
|
||||
}
|
||||
return until;
|
||||
}
|
||||
|
||||
function markRetry() {
|
||||
if (!(Number(state.quiz && state.quiz.retry_cooldown_min) > 0)) return;
|
||||
try { localStorage.setItem(retryKey(), 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 (state.retryTimer) clearInterval(state.retryTimer);
|
||||
state.retryTimer = null;
|
||||
}
|
||||
|
||||
function startRetryTimer(until) {
|
||||
stopRetryTimer();
|
||||
const tick = () => {
|
||||
const el = document.getElementById('qzRetryTimer');
|
||||
if (!el) { stopRetryTimer(); return; }
|
||||
if (Date.now() >= until) {
|
||||
stopRetryTimer();
|
||||
renderTab();
|
||||
return;
|
||||
}
|
||||
el.textContent = retryLeftText(until);
|
||||
};
|
||||
tick();
|
||||
state.retryTimer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function kindLabel(kind) {
|
||||
return kind === 'survey' ? 'Опрос' : 'Тест';
|
||||
}
|
||||
@@ -87,6 +144,7 @@
|
||||
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.retry_cooldown_min ? `<span>Повтор: через ${q.retry_cooldown_min} мин</span>` : '',
|
||||
q.kind === 'test' ? `<span>Порог: ${q.pass_percent}%</span>` : '',
|
||||
`</div>`,
|
||||
`<div class="qz-badges">`,
|
||||
@@ -123,6 +181,13 @@
|
||||
if (!q.is_published) {
|
||||
return '<div class="qz-panel"><p class="qz-hint" style="margin:0">Тест не опубликован. Пройти его может только автор после публикации.</p></div>';
|
||||
}
|
||||
const until = retryUntil();
|
||||
if (until) {
|
||||
return `<div class="qz-panel">
|
||||
<p class="qz-hint" style="margin:0 0 6px">Вы уже прошли ${q.kind === 'survey' ? 'этот опрос' : 'этот тест'} в этом браузере.</p>
|
||||
<p class="qz-hint" id="qzRetryTimer" style="margin:0">${retryLeftText(until)}</p>
|
||||
</div>`;
|
||||
}
|
||||
return `<div class="qz-panel">
|
||||
<div class="qz-sub" style="margin:0 0 10px">
|
||||
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
|
||||
@@ -136,7 +201,23 @@
|
||||
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="${esc(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="qz-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
||||
@@ -153,6 +234,32 @@
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc(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 res = await fetch(API + '/api/quizzes/system-options?field=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(text), { headers: hdr() });
|
||||
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="${at(it.name)}"><span>${esc(it.name)}</span>${it.sub ? `<small>${esc(it.sub)}</small>` : ''}</button>`).join('')
|
||||
: '<div class="qz-sug-empty">Ничего не найдено</div>';
|
||||
box.hidden = false;
|
||||
} catch (e) {
|
||||
box.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
function questionTakeHtml(q, index) {
|
||||
const opts = q.options || [];
|
||||
const chosen = state.selection.get(q.id) || new Set();
|
||||
@@ -189,8 +296,12 @@
|
||||
if (!state.attempt) {
|
||||
body.innerHTML = takeIntroHtml();
|
||||
renderIcons();
|
||||
const until = retryUntil();
|
||||
if (until) startRetryTimer(until);
|
||||
else stopRetryTimer();
|
||||
return;
|
||||
}
|
||||
stopRetryTimer();
|
||||
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
|
||||
@@ -323,7 +434,7 @@
|
||||
? 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>`;
|
||||
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">
|
||||
@@ -420,6 +531,8 @@
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const until = retryUntil();
|
||||
if (until) { showToast(retryLeftText(until), true); return; }
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts', { method: 'POST', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
@@ -431,6 +544,8 @@
|
||||
}
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
state.result = null;
|
||||
state.attemptDetail = null;
|
||||
renderTake();
|
||||
@@ -442,6 +557,19 @@
|
||||
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) {
|
||||
showToast(`Вопрос ${i + 1}: ответ обязателен`, true);
|
||||
const qEl = document.querySelectorAll('#qzQuestions .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;
|
||||
@@ -451,13 +579,6 @@
|
||||
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;
|
||||
@@ -465,12 +586,13 @@
|
||||
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/quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ answers }),
|
||||
body: JSON.stringify({ answers, time_up: auto === true }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
@@ -479,6 +601,7 @@
|
||||
state.result = data.result;
|
||||
state.revealed = data.revealed;
|
||||
state.tab = 'take';
|
||||
markRetry();
|
||||
renderTab();
|
||||
await loadQuiz(true);
|
||||
showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены');
|
||||
@@ -489,6 +612,8 @@
|
||||
}
|
||||
|
||||
async function restart() {
|
||||
const until = retryUntil();
|
||||
if (until) { showToast(retryLeftText(until), true); return; }
|
||||
if (!confirm('Начать попытку заново? Текущие ответы не сохранятся.')) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/restart', {
|
||||
@@ -503,6 +628,8 @@
|
||||
state.attemptDetail = null;
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
renderTake();
|
||||
} catch (e) {
|
||||
showToast(e.message, true);
|
||||
@@ -548,11 +675,35 @@
|
||||
document.addEventListener('input', e => {
|
||||
const el = e.target;
|
||||
if (el.dataset.qtext) {
|
||||
state.texts.set(Number(el.dataset.qtext), el.value);
|
||||
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 tabBtn = e.target.closest('[data-act="tab"]');
|
||||
if (tabBtn) {
|
||||
e.preventDefault();
|
||||
@@ -606,6 +757,8 @@
|
||||
state.revealed = false;
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
} else {
|
||||
state.attempt = prevAttempt;
|
||||
state.result = prevResult;
|
||||
|
||||
@@ -728,7 +728,7 @@
|
||||
if (!(await checkAuth())) return;
|
||||
buildSidebar(document.body.dataset.page);
|
||||
const scalesBtn = document.getElementById('quizScalesBtn');
|
||||
if (scalesBtn) scalesBtn.hidden = !(currentUser && currentUser.role === 'admin');
|
||||
if (scalesBtn) scalesBtn.hidden = false;
|
||||
bind();
|
||||
bindVisibility();
|
||||
renderIcons();
|
||||
|
||||
Reference in New Issue
Block a user