Redesign B3 bordeaux + finish lab-page rework

- Lab page is now read-only with a settings screen for levels/variants;
  variant issuance moved to a large modal on the group page (assign-fragment).
- Header: bordeaux logo and 2px accent underline, bordeaux login/logout/theme
  buttons; smaller radii across the UI; filled secondary/danger buttons.
- Includes prior agent work (login backoff, no-cache pages, API timeouts,
  content tweaks) and fixes (variant usage Map.values, import order).
- Bump static asset version to v=9.
This commit is contained in:
2026-10-02 15:41:16 +03:00
parent 7a781fea33
commit 556fdf3b5e
67 changed files with 3019 additions and 653 deletions

View File

@@ -57,7 +57,7 @@ function csRow(text, tone) {
var rm = document.createElement('button');
rm.type = 'button';
rm.className = 'btn btn-secondary btn-sm';
rm.className = 'btn btn-secondary';
rm.textContent = 'удалить';
rm.onclick = function () { row.remove(); };
@@ -361,13 +361,13 @@ function applyDefenseToCell(s) {
}
if (label) {
label.textContent = started ? ''
: (s.status == null ? 'нет'
: (s.status === 'ready' ? 'готов'
: (s.code ? 'код' : 'ожид.')));
: (s.status == null ? '—'
: (s.status === 'ready' ? 'готова'
: (s.code ? 'код' : 'ожидает')));
}
if (s.status === 'ready') {
btn.title = 'Защита завершена: ' + (s.readyReason === 'timeout' ? 'время вышло' : 'студент нажал «Готов»');
if (label) label.textContent = 'готов';
if (label) label.textContent = 'готова';
}
}
@@ -521,7 +521,11 @@ function openVariant(btn) {
levelSel.innerHTML = '';
VARIANT_CACHE = {};
fetch('/admin/labs/' + encodeURIComponent(lab) + '/schema')
.then(function (r) { return r.ok ? r.json() : { levels: [] }; })
.then(function (r) { return r.ok && !r.redirected ? r.json() : { levels: [] }; })
.catch(function () {
alert('Не удалось загрузить уровни и варианты (возможно, сессия истекла). Обновите страницу и откройте модалку заново.');
return { levels: [] };
})
.then(function (data) {
(data.levels || []).forEach(function (lvl, i) {
var opt = document.createElement('option');
@@ -607,3 +611,55 @@ window.addEventListener('DOMContentLoaded', function () {
startDefenseWatch();
attachPublishToggles();
});
/* ---------- Большая модалка «Выдача вариантов» ---------- */
function refreshAssignModal(url) {
var body = document.getElementById('assign-modal-body');
if (!body) return Promise.resolve();
return fetch(url, { headers: { 'X-Requested-With': 'fetch' } })
.then(function (r) {
if (r.redirected) throw new Error('сессия истекла — обновите страницу');
return r.text();
})
.then(function (html) { body.innerHTML = html; });
}
window.openLabAssign = function (btn) {
var body = document.getElementById('assign-modal-body');
if (!body) return;
var title = document.getElementById('assign-modal-title');
if (title) title.textContent = 'Выдача вариантов — ' + (btn.getAttribute('data-lab-name') || '');
body.innerHTML = '<p class="text-muted">Загрузка…</p>';
openModal('modal-lab-assign');
refreshAssignModal(btn.getAttribute('data-url')).catch(function (e) {
body.innerHTML = '<p class="text-danger">Не удалось загрузить: ' + e.message + '</p>';
});
};
window.confirmAssignVariant = function (sel) {
var opt = sel.selectedOptions[0];
var taken = opt ? parseInt(opt.getAttribute('data-taken') || '0', 10) : 0;
if (opt && opt.value && taken > 0 && sel.value !== sel.dataset.prev) {
if (!confirm('Вариант уже занят (' + taken + '). Назначить всё равно?')) {
sel.value = sel.dataset.prev;
return;
}
}
sel.dataset.prev = sel.value;
sel.closest('form').requestSubmit();
};
/* Формы внутри модалки сохраняются через fetch — модалка не закрывается и обновляется */
document.addEventListener('submit', function (ev) {
var form = ev.target;
if (!form.classList || !form.classList.contains('js-assign-form')) return;
ev.preventDefault();
var btn = form.querySelector('button[type="submit"]');
if (btn) btn.disabled = true;
fetch(form.action, { method: 'POST', body: new FormData(form), headers: { 'X-Requested-With': 'fetch' } })
.then(function (r) { if (r.redirected) throw new Error('сессия истекла — обновите страницу'); return r.text(); })
.then(function () { return refreshAssignModal(form.getAttribute('data-refresh')); })
.catch(function (e) { showToast('Не удалось сохранить: ' + e.message, 'error'); })
.finally(function () { if (btn) btn.disabled = false; });
});

View File

@@ -1,36 +0,0 @@
function toggleAllStudents(cb) {
document.querySelectorAll('.pick-student').forEach(function (c) { c.checked = cb.checked; });
}
function collectPicked(form) {
var picked = Array.prototype.slice.call(document.querySelectorAll('.pick-student:checked'));
if (!picked.length) {
alert('Отметьте хотя бы одного студента.');
return false;
}
picked.forEach(function (c) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'studentIds';
input.value = c.value;
form.appendChild(input);
});
return true;
}
function confirmOccupied(sel) {
var opt = sel.options[sel.selectedIndex];
var taken = opt ? parseInt(opt.getAttribute('data-taken') || '0', 10) : 0;
if (opt && opt.value && taken > 0 && sel.value !== sel.dataset.prev) {
if (!confirm('Вариант уже занят (' + taken + '). Назначить всё равно?')) {
if (sel.dataset.prev !== undefined) sel.value = sel.dataset.prev;
return;
}
}
sel.dataset.prev = sel.value;
if (sel.form) sel.form.submit();
}
window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('.pick-variant').forEach(function (s) { s.dataset.prev = s.value; });
});

View File

@@ -239,6 +239,9 @@
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(collectPayload())
}).then(function (response) {
// после истечения сессии сервер отвечает редиректом на /login: fetch вернёт 200 с HTML —
// считать такое успехом нельзя, иначе порядок «сохранится» только на экране
if (response.redirected) throw new Error('сессия истекла — обновите страницу');
if (!response.ok) throw new Error('HTTP ' + response.status);
pending = false;
saving = false;

File diff suppressed because one or more lines are too long

View File

@@ -113,7 +113,8 @@
};
document.addEventListener('input', function (event) {
if (event.target && event.target.id === 'article-body') dirty = true;
var id = event.target && event.target.id;
if (id === 'article-body' || id === 'article-title') dirty = true;
});
/* Сохранение — это осознанный уход со страницы, подтверждение не нужно */

View File

@@ -0,0 +1,32 @@
/* Защита от двойной отправки: после сабмита формы кнопки блокируются до перехода.
Инлайн-onsubmit с confirm() успевает отработать раньше (обработчик из атрибута
регистрируется первым) — если сабмит отменён, кнопки не блокируются. */
(function () {
function buttonsOf(form) {
return form.querySelectorAll('button[type="submit"]');
}
function setDisabled(form, disabled) {
buttonsOf(form).forEach(function (btn) { btn.disabled = disabled; });
}
function arm(form) {
if (form.dataset.submitGuard) return;
form.dataset.submitGuard = '1';
form.addEventListener('submit', function (event) {
if (event.defaultPrevented) return;
window.setTimeout(function () {
// кто-то из более поздних обработчиков мог отменить сабмит
if (!event.defaultPrevented) setDisabled(form, true);
}, 0);
});
// возврат на страницу по Back/Forward из кэша — разблокируем
window.addEventListener('pageshow', function (event) {
if (event.persisted) setDisabled(form, false);
});
}
window.addEventListener('DOMContentLoaded', function () {
document.querySelectorAll('form').forEach(arm);
});
})();

View File

@@ -158,13 +158,26 @@
if (th.hasAttribute('data-nosort')) return;
th.classList.add('th-sortable');
if (!th.title) th.title = 'Сортировать по этому столбцу';
th.addEventListener('click', function (event) {
if (event.target.closest('form, button, a, select, input')) return;
// сортировка с клавиатуры: фокус + Enter/пробел, состояние доступно скринридеру
th.tabIndex = 0;
if (th.classList.contains('is-asc')) th.setAttribute('aria-sort', 'ascending');
function doSort() {
var asc = !th.classList.contains('is-asc');
clearAllMarkers(table);
th.classList.add(asc ? 'is-asc' : 'is-desc');
th.setAttribute('aria-sort', asc ? 'ascending' : 'descending');
sortColumn(table, index, asc ? 1 : -1);
th.title = (th.textContent.trim() || 'Столбец') + ' — ' + (asc ? 'по возрастанию' : 'по убыванию');
}
th.addEventListener('click', function (event) {
if (event.target.closest('form, button, a, select, input')) return;
doSort();
});
th.addEventListener('keydown', function (event) {
if (event.target !== th) return;
if (event.key !== 'Enter' && event.key !== ' ') return;
event.preventDefault();
doSort();
});
});
buildFilters(table);