feat(ui): улучшения фото-модалки, отправки записей и списка модулей

- enhance-модалка: индикатор «размышления» с прогрессом, иконки Lucide
  вместо эмодзи, подсветка готового результата, защита от гонок опроса
- index.js: лимит модулей 1000, повторные попытки загрузки списка,
  таймаут и ретрай отправки записи, требование вложений по флагу модуля
- journal.js/groups.js: `data-img` получает полный путь (лайтбокс вместо
  миниатюры), thumbSrc отдаёт `/uploads/thumb/` и оригиналы из `.originals/`
- shorts.js: переключение «Использовано» без полной перезагрузки списка
- AGENTS.md: правила миниатюр (`thumbSrc`) и `data-img`
This commit is contained in:
dev
2026-10-14 22:59:27 +03:00
parent 06bcbe0824
commit 853b446591
8 changed files with 389 additions and 76 deletions
+97 -20
View File
@@ -263,38 +263,57 @@ function updateAttachHint() {
filesAttachHint.style.display = name && moduleAttachments.get(name) === true ? '' : 'none';
}
async function fetchModules(q, limit) {
const MODULE_LIST_LIMIT = 1000;
function findModuleId(name) {
const lower = (name || '').trim().toLowerCase();
if (!lower) return null;
for (const [key, id] of moduleNames) {
if (key.toLowerCase() === lower) return id;
}
return null;
}
async function fetchModules(q, limit, attempts = 2) {
const p = new URLSearchParams();
if (q) p.set('search', q);
p.set('limit', String(limit));
p.set('active', '1');
try {
const res = await fetch(`${API}/api/modules?${p}`);
if (!res.ok) return [];
const data = await res.json();
return data.modules || [];
} catch (e) { return []; }
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch(`${API}/api/modules?${p}`);
if (!res.ok) return null;
const data = await res.json();
return data.modules || [];
} catch (e) {
if (i < attempts - 1) await new Promise(r => setTimeout(r, 600));
}
}
return null;
}
async function resolveModuleId(name) {
const n = (name || '').trim();
if (!n) return null;
if (moduleNames.has(n)) return moduleNames.get(n);
const cached = findModuleId(n);
if (cached) return cached;
const list = await fetchModules(n, 5);
renderModuleOptions(list);
if (list) renderModuleOptions(list);
const lower = n.toLowerCase();
const exact = list.find(m => m.name.toLowerCase() === lower);
const exact = (list || []).find(m => m.name.toLowerCase() === lower);
return exact ? exact.id : null;
}
(async () => {
await initDateTime();
try {
const list = await fetchModules('', 50);
if (list.length) {
const list = await fetchModules('', MODULE_LIST_LIMIT);
if (list) {
renderModuleOptions(list);
moduleInput.required = true;
moduleField.style.display = '';
if (list.length) {
moduleInput.required = true;
moduleField.style.display = '';
}
}
} catch (e) { /* ignore */ }
const res = await fetch(`${API}/api/students`);
@@ -405,6 +424,33 @@ function capture() {
}, 'image/jpeg', captureQuality);
}
const ENTRY_SUBMIT_TIMEOUT_MS = 180000;
const ENTRY_RETRY_STATUS = new Set([502, 503, 504]);
async function postEntryOnce(fd) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), ENTRY_SUBMIT_TIMEOUT_MS);
try {
return await fetch(`${API}/api/entries`, { method: 'POST', body: fd, signal: ctrl.signal });
} finally {
clearTimeout(timer);
}
}
async function postEntry(fd) {
try {
const res = await postEntryOnce(fd);
if (ENTRY_RETRY_STATUS.has(res.status)) {
await new Promise(r => setTimeout(r, 1500));
return { res: await postEntryOnce(fd), retried: true };
}
return { res, retried: false };
} catch (err) {
await new Promise(r => setTimeout(r, 1500));
return { res: await postEntryOnce(fd), retried: true };
}
}
form.addEventListener('submit', async (e) => {
e.preventDefault();
if (!capturedBlob) {
@@ -420,9 +466,19 @@ form.addEventListener('submit', async (e) => {
toast.textContent = 'Выберите тему модуля из списка подсказок';
toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
return;
return;
}
}
// Проверка: если модуль требует вложений, то файлы должны быть прикреплены
const moduleAttachmentEnabled = moduleAttachments.get(moduleId) === true;
if (moduleAttachmentEnabled && selectedFiles.length === 0) {
toast.textContent = 'Для этой темы необходимо прикрепить файлы';
toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3000);
return;
}
const btn = document.getElementById('submitBtn');
btn.disabled = true;
btn.textContent = 'Отправка...';
@@ -437,15 +493,32 @@ form.addEventListener('submit', async (e) => {
fd.append('website', document.getElementById('hpWebsite').value);
try {
const res = await fetch(`${API}/api/entries`, { method: 'POST', body: fd });
const { res, retried } = await postEntry(fd);
if (res.status === 429) {
if (retried) {
form.reset();
removePhoto();
clearFiles();
updateAttachHint();
localStorage.setItem(SENT_KEY, String(Date.now()));
showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs());
return;
}
const e = await res.json().catch(() => ({}));
toast.textContent = e.error || 'Уже ответили: подождите';
toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
return;
}
if (!res.ok) throw new Error(await res.text());
if (!res.ok) {
let msg = 'Не удалось отправить запись. Попробуй ещё раз.';
try {
const e = await res.json();
if (e && e.error) msg = e.error;
} catch (e) { /* not JSON */ }
notify(msg, true);
return;
}
form.reset();
removePhoto();
clearFiles();
@@ -453,7 +526,7 @@ form.addEventListener('submit', async (e) => {
localStorage.setItem(SENT_KEY, String(Date.now()));
showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs());
} catch (err) {
alert('Ошибка: ' + err.message);
notify('Не удалось отправить запись. Проверь интернет и попробуй ещё раз.', true);
} finally {
btn.disabled = false;
btn.textContent = 'Отправить';
@@ -475,12 +548,16 @@ moduleInput.addEventListener('input', () => {
clearTimeout(moduleSearchTimer);
const q = moduleInput.value.trim();
moduleSearchTimer = setTimeout(async () => {
renderModuleOptions(await fetchModules(q, 20));
const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT);
if (list) renderModuleOptions(list);
updateAttachHint();
}, 250);
});
moduleInput.addEventListener('focus', async () => {
if (!moduleInput.value.trim()) renderModuleOptions(await fetchModules('', 50));
if (!moduleInput.value.trim()) {
const list = await fetchModules('', MODULE_LIST_LIMIT);
if (list) renderModuleOptions(list);
}
});
(async () => {