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
+79 -13
View File
@@ -958,11 +958,53 @@ function showEnhanceResult(show) {
if (loading) loading.style.display = show ? 'none' : '';
}
function flashEnhanceResult() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
area.classList.remove('enhance-flash');
void area.offsetWidth;
area.classList.add('enhance-flash');
setTimeout(() => area.classList.remove('enhance-flash'), 1200);
}
function setBtnLabel(btn, text) {
if (!btn) return;
const icon = btn.querySelector('svg, i[data-lucide]');
btn.textContent = '';
if (icon) {
btn.appendChild(icon);
btn.appendChild(document.createTextNode(' ' + text));
} else {
btn.textContent = text;
}
}
function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
el.textContent = text;
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = '';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
function setEnhanceLoadingProgress(pct, text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
const textEl = document.getElementById('enhanceThinkingText');
if (textEl && text) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = pct >= 100 ? 'none' : '';
const progress = document.getElementById('enhanceProgress');
const bar = document.getElementById('enhanceProgressBar');
if (progress && bar) {
progress.style.display = '';
bar.style.width = Math.min(100, Math.max(0, pct)) + '%';
}
}
function medianFilterPass(ctx, w, h) {
@@ -1405,7 +1447,7 @@ function openEnhance(id) {
const orig = document.getElementById('enhanceOrig');
if (orig) orig.src = API + p.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = true;
loadPhotoAiConfig().then(() => {
@@ -1419,13 +1461,25 @@ function openEnhance(id) {
setEnhanceLoadingText('Загрузка...');
const img = new Image();
img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img;
renderEnhancePreview();
if (saveBtn) saveBtn.disabled = false;
};
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить фото');
img.onerror = () => {
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) {
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = 'Не удалось загрузить фото';
const dots = loadingEl.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = 'none';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
};
img.src = API + p.photo_path;
modal.classList.add('open');
renderIcons();
}
function closeEnhance() {
@@ -1441,6 +1495,8 @@ function closeEnhance() {
enhanceSaving = false;
resetEnhanceZoom();
if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; }
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
}
async function runPhotoAi() {
@@ -1453,11 +1509,11 @@ async function runPhotoAi() {
const btnAi = document.getElementById('enhanceAiBtn');
const saveBtn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true;
if (btnAi) { btnAi.disabled = true; btnAi.textContent = '⏳ ИИ...'; }
if (btnAi) { btnAi.disabled = true; setBtnLabel(btnAi, '⏳ ИИ...'); }
if (saveBtn) saveBtn.disabled = true;
showEnhanceResult(false);
setEnhanceLoadingText(mode.face === 'off'
? 'ИИ обрабатывает фото... (может занять до минуты)'
setEnhanceLoadingProgress(0, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, {
@@ -1469,7 +1525,7 @@ async function runPhotoAi() {
pollAiResult();
} catch (err) {
enhanceSaving = false;
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null);
showEnhanceResult(true);
alert(err.message);
@@ -1478,6 +1534,7 @@ async function runPhotoAi() {
async function pollAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return;
if (enhanceAiResultPath) return;
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai/${enhanceAiJobId}`, { headers: hdr() });
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка статуса'); }
@@ -1486,7 +1543,7 @@ async function pollAiResult() {
enhanceSaving = false;
enhanceAiResultPath = data.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = false;
const img = new Image();
@@ -1501,9 +1558,12 @@ async function pollAiResult() {
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
renderEnhancePreview();
flashEnhanceResult();
};
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить результат ИИ');
img.onerror = () => showEnhanceResult(true);
img.src = API + data.photo_path;
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
showToast('ИИ результат готов');
return;
}
@@ -1511,17 +1571,23 @@ async function pollAiResult() {
enhanceSaving = false;
alert(data.error || 'Ошибка обработки');
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
showEnhanceResult(true);
return;
}
setTimeout(pollAiResult, 2000);
// Simulate progress
const currentMode = photoAiMode();
const progress = Math.min(95, Date.now() % 10000 / 100); // Cycles 0-95 over 10 seconds
setEnhanceLoadingProgress(progress, currentMode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
setTimeout(pollAiResult, 500);
} catch (err) {
enhanceSaving = false;
showEnhanceResult(true);
alert(err.message);
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
showEnhanceResult(true);
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
}
}
+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 () => {
+132 -25
View File
@@ -7,6 +7,7 @@ let editGroups = [];
let editModules = [];
let moduleNames = new Map();
let moduleFilterId = '';
const MODULE_LIST_LIMIT = 1000;
let moduleSearchTimer = null;
let editModuleSearchTimer = null;
let modulesLoaded = false;
@@ -250,7 +251,7 @@ function gridEntryHTML(e) {
const mp = mainPhotoPath(e);
return `
<div class="card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}">
${mp ? `<img src="${thumbSrc(mp)}" data-img="${esc(thumbSrc(mp))}" loading="lazy" decoding="async" alt="">` : ''}
${mp ? `<img src="${thumbSrc(mp)}" data-img="${API}${mp}" loading="lazy" decoding="async" alt="">` : ''}
<div class="info">
<div class="name">${esc(e.student_name)}</div>
<div class="group">${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}</div>
@@ -271,7 +272,7 @@ function cardEntryHTML(e) {
return `
<div class="journal-card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}">
${mp
? `<img src="${thumbSrc(mp)}" data-img="${esc(thumbSrc(mp))}" loading="lazy" decoding="async" alt="">`
? `<img src="${thumbSrc(mp)}" data-img="${API}${mp}" loading="lazy" decoding="async" alt="">`
: `<div class="no-photo"><svg viewBox="0 0 240 160" preserveAspectRatio="xMidYMid meet" aria-hidden="true"><circle cx="105" cy="48" r="15"/><path d="M74 140 C74 106 88 92 105 92 C122 92 136 106 136 140 Z"/><circle cx="145" cy="58" r="18"/><path d="M108 144 C108 104 124 88 145 88 C166 88 182 104 182 144 Z"/></svg></div>`}
${e.group_name ? `<span class="group-badge" title="${esc(e.group_name)}">${esc(e.group_name)}</span>` : ''}
${e.module_name ? `<span class="group-badge" style="left:auto;right:8px;background:rgba(37,99,235,.8)" title="Модуль: ${esc(e.module_name)}">${esc(e.module_name)}</span>` : ''}
@@ -385,15 +386,22 @@ function renderModuleOptions(datalistId, list) {
});
}
async function fetchModules(q, limit) {
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');
const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() });
if (!res.ok) return [];
const data = await res.json().catch(() => ({}));
return data.modules || [];
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() });
if (!res.ok) return null;
const data = await res.json().catch(() => ({}));
return data.modules || [];
} catch (e) {
if (i < attempts - 1) await new Promise(r => setTimeout(r, 600));
}
}
return null;
}
async function resolveModuleId(name) {
@@ -401,14 +409,18 @@ async function resolveModuleId(name) {
if (!n) return '';
if (moduleNames.has(n)) return String(moduleNames.get(n));
const list = await fetchModules(n, 10);
if (!list) return null;
const lower = n.toLowerCase();
const exact = list.find(m => m.name.toLowerCase() === lower);
return exact ? String(exact.id) : null;
}
async function loadModuleOptions() {
editModules = await fetchModules('', 50);
modulesLoaded = true;
const list = await fetchModules('', MODULE_LIST_LIMIT);
if (list) {
editModules = list;
modulesLoaded = true;
}
renderModuleOptions('moduleFilterList', editModules);
}
@@ -666,10 +678,53 @@ function showEnhanceResult(show) {
document.getElementById('enhanceLoading').style.display = show ? 'none' : '';
}
function flashEnhanceResult() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
area.classList.remove('enhance-flash');
void area.offsetWidth;
area.classList.add('enhance-flash');
setTimeout(() => area.classList.remove('enhance-flash'), 1200);
}
function setBtnLabel(btn, text) {
if (!btn) return;
const icon = btn.querySelector('svg, i[data-lucide]');
btn.textContent = '';
if (icon) {
btn.appendChild(icon);
btn.appendChild(document.createTextNode(' ' + text));
} else {
btn.textContent = text;
}
}
function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
el.textContent = text;
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = '';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
function setEnhanceLoadingProgress(pct, text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
const textEl = document.getElementById('enhanceThinkingText');
if (textEl && text) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = pct >= 100 ? 'none' : '';
const progress = document.getElementById('enhanceProgress');
const bar = document.getElementById('enhanceProgressBar');
if (progress && bar) {
progress.style.display = '';
bar.style.width = Math.min(100, Math.max(0, pct)) + '%';
}
}
let enhanceZoom = 1;
@@ -835,20 +890,45 @@ async function runPhotoAi() {
const { jobId } = await res.json();
enhanceAiJobId = jobId;
showEnhanceResult(false);
setEnhanceLoadingText(mode.face === 'off'
? 'ИИ обрабатывает фото... (может занять до минуты)'
setEnhanceLoadingProgress(0, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
btn.textContent = '⏳ ИИ...';
setBtnLabel(btn, '⏳ ИИ...');
let doneHandled = false;
const result = await new Promise((resolve, reject) => {
photoAiPollTimer = setInterval(async () => {
if (doneHandled) return;
try {
const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() });
if (!r.ok) throw new Error('Ошибка опроса статуса');
const s = await r.json();
if (s.status === 'done') { clearInterval(photoAiPollTimer); resolve(s); }
else if (s.status === 'error') { clearInterval(photoAiPollTimer); reject(new Error(s.error || 'Ошибка ИИ')); }
} catch (e) { clearInterval(photoAiPollTimer); reject(e); }
}, 2000);
if (doneHandled) return;
if (s.status === 'done') {
doneHandled = true;
clearInterval(photoAiPollTimer);
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
resolve(s);
}
else if (s.status === 'error') {
doneHandled = true;
clearInterval(photoAiPollTimer);
showEnhanceResult(true);
reject(new Error(s.error || 'Ошибка ИИ'));
}
else {
const progress = Math.min(95, Date.now() % 10000 / 100);
setEnhanceLoadingProgress(progress, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
}
} catch (e) {
doneHandled = true;
clearInterval(photoAiPollTimer);
showEnhanceResult(true);
reject(e);
}
}, 500);
});
showToast('ИИ результат готов');
enhanceAiResultPath = result.photo_path;
@@ -864,8 +944,9 @@ async function runPhotoAi() {
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
renderEnhancePreview();
flashEnhanceResult();
};
aiImg.onerror = () => { showToast('Не удалось загрузить результат ИИ'); };
aiImg.onerror = () => { showEnhanceResult(true); showToast('Не удалось загрузить результат ИИ'); };
aiImg.src = `${API}${result.photo_path}`;
} catch (e) {
showEnhanceResult(true);
@@ -873,7 +954,7 @@ async function runPhotoAi() {
} finally {
enhanceSaving = false;
btn.disabled = false;
btn.textContent = '🤖 ИИ';
setBtnLabel(btn, 'ИИ');
}
}
@@ -921,6 +1002,8 @@ function openEnhance(id) {
const orig = document.getElementById('enhanceOrig');
orig.src = `${API}${mp}`;
document.getElementById('enhanceRestoreBtn').style.display = e.photo_original_path ? '' : 'none';
const aiBtn = document.getElementById('enhanceAiBtn');
if (aiBtn) { aiBtn.disabled = false; setBtnLabel(aiBtn, 'ИИ'); }
loadEnhanceEngine().then(() => {
const show = photoAiEnabled ? '' : 'none';
document.getElementById('enhanceAiBtn').style.display = show;
@@ -931,14 +1014,24 @@ function openEnhance(id) {
setEnhanceClip(50);
resetEnhanceZoom();
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
setEnhanceLoadingProgress(0, 'Загрузка...');
renderIcons();
const img = new Image();
img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img;
renderEnhancePreview();
};
img.onerror = () => {
setEnhanceLoadingText('Не удалось загрузить фото');
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) {
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = 'Не удалось загрузить фото';
const dots = loadingEl.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = 'none';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
};
img.src = `${API}${mp}`;
document.getElementById('enhanceModal').classList.add('open');
@@ -987,6 +1080,8 @@ function closeEnhance() {
enhanceEntryId = null;
enhanceSourceImg = null;
enhanceAiResultPath = null;
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
}
function photoJobThumb(p) {
@@ -1061,13 +1156,23 @@ async function rollbackPhotoJob(jobId) {
const mp = data.photo_path;
document.getElementById('enhanceOrig').src = `${API}${mp}`;
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
setEnhanceLoadingProgress(0, 'Загрузка...');
const img = new Image();
img.onload = () => {
enhanceSourceImg = img;
renderEnhancePreview();
};
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить фото');
img.onerror = () => {
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) {
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = 'Не удалось загрузить фото';
const dots = loadingEl.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = 'none';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
};
img.src = `${API}${mp}`;
refreshEntryCard(enhanceEntryId);
} catch (e) {
@@ -1475,14 +1580,16 @@ document.getElementById('moduleFilter').addEventListener('input', () => {
clearTimeout(moduleSearchTimer);
const q = document.getElementById('moduleFilter').value.trim();
moduleSearchTimer = setTimeout(async () => {
renderModuleOptions('moduleFilterList', await fetchModules(q, 20));
const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT);
if (list) renderModuleOptions('moduleFilterList', list);
}, 250);
});
document.getElementById('editModule').addEventListener('input', () => {
clearTimeout(editModuleSearchTimer);
const q = document.getElementById('editModule').value.trim();
editModuleSearchTimer = setTimeout(async () => {
renderModuleOptions('editModuleList', await fetchModules(q, 20));
const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT);
if (list) renderModuleOptions('editModuleList', list);
}, 250);
});
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadEntries(); });
+14 -1
View File
@@ -326,7 +326,20 @@ async function toggleUsed(id) {
body: JSON.stringify({ used: next, used_at: next ? todayIso() : null })
});
if (!res.ok) { const err = await res.json().catch(() => ({})); showToast(err.error || 'Ошибка'); return; }
await loadShorts();
// Update only the current element's UI instead of reloading entire page
const chip = row.querySelector('[data-toggle-used]');
if (chip) {
if (next) {
chip.classList.add('on');
chip.innerHTML = '<i data-lucide="check-circle-2"></i> Использовано';
chip.title = 'Снять отметку об использовании';
} else {
chip.classList.remove('on');
chip.innerHTML = '<i data-lucide="circle"></i> Не использовано';
chip.title = 'Отметить как использованное';
}
renderIcons();
}
showToast(next ? 'Отмечено как использованное' : 'Отметка снята');
} catch (e) { showToast('Ошибка: ' + e.message); }
}