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
+2
View File
@@ -328,6 +328,8 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
- Each page = single HTML file + shared `admin.js` / `admin.css` - Each page = single HTML file + shared `admin.js` / `admin.css`
- API calls via `fetch` with `X-Auth-Token` (токен из `localStorage`); `X-Admin-Token` больше не используется и не работает - API calls via `fetch` with `X-Auth-Token` (токен из `localStorage`); `X-Admin-Token` больше не используется и не работает
- Share pages (`share.html`, `links.html`) work without auth - Share pages (`share.html`, `links.html`) work without auth
- **Миниатюры фото — только `thumbSrc(p)`** из `public/admin.js` (`/uploads/...` → `/uploads/thumb/<name>`, `/api/files/...` → `?thumb=1`, `.originals/...` отдаёт `/uploads/.originals/<name>` — серверный роут уже уменьшает). В карточках, сетках и списках `<img src>` **обязан** идти через него; сервер кэширует результат в `uploads/.thumbs/` и отдаёт `immutable`. Ручной `${API}/uploads/thumb/...` в страничных хелперах (`photoThumb`, `sThumb`, `dashThumb`, `fbStudentThumb`, `studentThumbSrc`) — историческое дублирование, новому коду оно не нужно
- **`data-img` — это лайтбокс, а не миниатюра**: в него кладут полный путь (`${API}${p}`), иначе клик по фото открывает 480px вместо оригинала. `thumbSrc` в `data-img` — баг: `.journal-cards`/`.journal-card` (`public/js/journal.js`), `.group-cover` (`public/js/groups.js`) уже на этом падали
### 6. Docker / Compose ### 6. Docker / Compose
- **Dockerfile**: Node 22 Alpine, installs deps; self-signed TLS cert генерируется **в entrypoint** (`entrypoint.sh`) только если его нет в `certs/` - **Dockerfile**: Node 22 Alpine, installs deps; self-signed TLS cert генерируется **в entrypoint** (`entrypoint.sh`) только если его нет в `certs/`
+2 -1
View File
@@ -6,7 +6,8 @@ function hdrJson() { return { 'Content-Type': 'application/json', 'X-Auth-Token'
function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; } function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
function thumbSrc(p) { function thumbSrc(p) {
if (!p) return p; if (!p) return p;
if (p.startsWith('/uploads/')) return `${API}/uploads/${p.slice('/uploads/'.length)}`; if (p.startsWith('/uploads/.originals/')) return `${API}${p}`;
if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`;
if (p.includes('/api/files/')) return p + (p.includes('?') ? '&' : '?') + 'thumb=1'; if (p.includes('/api/files/')) return p + (p.includes('?') ? '&' : '?') + 'thumb=1';
return p; return p;
} }
+31 -9
View File
@@ -22,9 +22,19 @@
.enhance-badge{position:absolute;top:10px;padding:4px 10px;border-radius:6px;background:rgba(17,17,17,.7);color:#fff;font-size:.78rem;pointer-events:none} .enhance-badge{position:absolute;top:10px;padding:4px 10px;border-radius:6px;background:rgba(17,17,17,.7);color:#fff;font-size:.78rem;pointer-events:none}
.enhance-badge.left{left:10px} .enhance-badge.left{left:10px}
.enhance-badge.right{right:10px} .enhance-badge.right{right:10px}
.enhance-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(17,17,17,.55);color:#fff;font-size:.95rem;gap:8px;display:none} .enhance-loading{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(17,17,17,.7);color:#fff;font-size:.95rem;gap:8px;display:none}
.enhance-loading::after{content:'';width:16px;height:16px;border:2px solid rgba(255,255,255,.6);border-top-color:transparent;border-radius:50%;animation:spin 1s linear infinite} .enhance-thinking{display:flex;flex-direction:column;align-items:center;gap:12px}
@keyframes spin{to{transform:rotate(360deg)}} .enhance-thinking-text{font-size:.9rem}
.enhance-thinking-dots{display:flex;gap:6px}
.enhance-thinking-dot{width:8px;height:8px;background:var(--accent);border-radius:50%;animation:thinking-pulse 1.4s ease-in-out infinite}
.enhance-thinking-dot:nth-child(1){animation-delay:0s}
.enhance-thinking-dot:nth-child(2){animation-delay:0.2s}
.enhance-thinking-dot:nth-child(3){animation-delay:0.4s}
@keyframes thinking-pulse{0%,80%,100%{opacity:.4;transform:scale(.8)}40%{opacity:1;transform:scale(1)}}
.enhance-progress{width:180px;height:4px;background:rgba(255,255,255,.3);border-radius:2px;overflow:hidden}
.enhance-progress-bar{height:100%;width:0%;background:#fff;border-radius:2px;transition:width .3s ease}
.enhance-compare.enhance-flash::after{content:'';position:absolute;inset:0;background:#fff;opacity:0;pointer-events:none;animation:enhance-flash 1.2s ease-out;z-index:5}
@keyframes enhance-flash{0%{opacity:.9}30%{opacity:0}45%{opacity:.5}100%{opacity:0}}
.enhance-sliders{flex:0 0 240px;display:flex;flex-direction:column;gap:14px} .enhance-sliders{flex:0 0 240px;display:flex;flex-direction:column;gap:14px}
.enhance-sliders .settings-field input[type=range]{width:100%} .enhance-sliders .settings-field input[type=range]{width:100%}
.enhance-foot{justify-content:flex-end;gap:8px;margin-top:14px;flex-wrap:wrap} .enhance-foot{justify-content:flex-end;gap:8px;margin-top:14px;flex-wrap:wrap}
@@ -182,10 +192,22 @@
<canvas id="enhanceCanvas"></canvas> <canvas id="enhanceCanvas"></canvas>
</div> </div>
</div> </div>
<div class="enhance-divider" id="enhanceDivider"><div class="enhance-handle">⇔</div></div> <div class="enhance-divider" id="enhanceDivider"><div class="enhance-handle"><i data-lucide="move-horizontal" style="width:18px;height:18px"></i></div></div>
<div class="enhance-badge left">Оригинал</div> <div class="enhance-badge left">Оригинал</div>
<div class="enhance-badge right">Результат</div> <div class="enhance-badge right">Результат</div>
<div class="enhance-loading" id="enhanceLoading">Загрузка...</div> <div class="enhance-loading" id="enhanceLoading">
<div class="enhance-thinking">
<div class="enhance-thinking-text" id="enhanceThinkingText">Загрузка...</div>
<div class="enhance-thinking-dots">
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
</div>
<div class="enhance-progress" id="enhanceProgress" style="display:none">
<div class="enhance-progress-bar" id="enhanceProgressBar"></div>
</div>
</div>
</div>
</div> </div>
<div class="enhance-sliders"> <div class="enhance-sliders">
<div class="settings-field"><label>Яркость <span id="enhanceBrightnessVal">100%</span></label><input type="range" id="enhanceBrightness" min="50" max="150" value="100"></div> <div class="settings-field"><label>Яркость <span id="enhanceBrightnessVal">100%</span></label><input type="range" id="enhanceBrightness" min="50" max="150" value="100"></div>
@@ -196,8 +218,8 @@
</div> </div>
</div> </div>
<div class="card-foot enhance-foot"> <div class="card-foot enhance-foot">
<button type="button" class="btn-primary ghost" id="enhanceHistoryBtn" title="История изменений фотографии">🕘 История</button> <button type="button" class="btn-primary ghost" id="enhanceHistoryBtn" title="История изменений фотографии"><i data-lucide="history"></i> История</button>
<button type="button" class="btn-primary ghost" id="enhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию">↩ Вернуть оригинал</button> <button type="button" class="btn-primary ghost" id="enhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию"><i data-lucide="undo-2"></i> Вернуть оригинал</button>
<select id="enhanceAiMode" class="settings-input enhance-ai-mode" style="display:none" title="Режим ИИ-обработки фото"> <select id="enhanceAiMode" class="settings-input enhance-ai-mode" style="display:none" title="Режим ИИ-обработки фото">
<option value="x2">Универсально (x2)</option> <option value="x2">Универсально (x2)</option>
<option value="x4">Быстро (x4)</option> <option value="x4">Быстро (x4)</option>
@@ -205,8 +227,8 @@
<option value="facesbg">Лица + фон</option> <option value="facesbg">Лица + фон</option>
</select> </select>
<span class="enhance-ai-hint" id="enhanceAiHint" style="display:none"></span> <span class="enhance-ai-hint" id="enhanceAiHint" style="display:none"></span>
<button type="button" class="btn-primary ghost" id="enhanceAiBtn" style="display:none" title="ИИ-восстановление (Real-ESRGAN)">🤖 ИИ</button> <button type="button" class="btn-primary ghost" id="enhanceAiBtn" style="display:none" title="ИИ-восстановление (Real-ESRGAN)"><i data-lucide="sparkles"></i> ИИ</button>
<button type="button" class="btn-primary ghost" id="enhanceAutoBtn" title="Подобрать настройки автоматически">✨ Авто</button> <button type="button" class="btn-primary ghost" id="enhanceAutoBtn" title="Подобрать настройки автоматически"><i data-lucide="wand-sparkles"></i> Авто</button>
<button type="button" class="btn-primary ghost" id="enhanceCancelBtn">Оставить как есть</button> <button type="button" class="btn-primary ghost" id="enhanceCancelBtn">Оставить как есть</button>
<button type="button" class="btn-primary" id="enhanceSaveBtn">Применить</button> <button type="button" class="btn-primary" id="enhanceSaveBtn">Применить</button>
</div> </div>
+32 -7
View File
@@ -23,7 +23,20 @@
.enhance-badge { position: absolute; top: 10px; padding: 3px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: .72rem; pointer-events: none; } .enhance-badge { position: absolute; top: 10px; padding: 3px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: .72rem; pointer-events: none; }
.enhance-badge.left { left: 10px; } .enhance-badge.left { left: 10px; }
.enhance-badge.right { right: 10px; } .enhance-badge.right { right: 10px; }
.enhance-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: .85rem; background: var(--bg); } .enhance-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: .85rem; background: rgba(255,255,255,.8); }
.enhance-loading::backdrop-filter { backdrop-filter: blur(2px); }
.enhance-thinking { display: flex; flex-direction: column; align-items: center; gap: 12px; }
.enhance-thinking-text { font-size: .9rem; }
.enhance-thinking-dots { display: flex; gap: 6px; }
.enhance-thinking-dot { width: 8px; height: 8px; background: var(--accent); border-radius: 50%; animation: thinking-pulse 1.4s ease-in-out infinite; }
.enhance-thinking-dot:nth-child(1) { animation-delay: 0s; }
.enhance-thinking-dot:nth-child(2) { animation-delay: 0.2s; }
.enhance-thinking-dot:nth-child(3) { animation-delay: 0.4s; }
@keyframes thinking-pulse { 0%, 80%, 100% { opacity: .4; transform: scale(.8); } 40% { opacity: 1; transform: scale(1); } }
.enhance-progress { width: 180px; height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; }
.enhance-progress-bar { height: 100%; width: 0%; background: var(--accent); border-radius: 2px; transition: width .3s ease; }
.enhance-compare.enhance-flash::after { content: ''; position: absolute; inset: 0; background: #fff; opacity: 0; pointer-events: none; animation: enhance-flash 1.2s ease-out; z-index: 5; }
@keyframes enhance-flash { 0% { opacity: .9; } 30% { opacity: 0; } 45% { opacity: .5; } 100% { opacity: 0; } }
.enhance-sliders { flex: 0 0 240px; display: flex; flex-direction: column; gap: 14px; } .enhance-sliders { flex: 0 0 240px; display: flex; flex-direction: column; gap: 14px; }
.enhance-sliders .settings-field input[type=range] { width: 100%; } .enhance-sliders .settings-field input[type=range] { width: 100%; }
.enhance-foot { justify-content: flex-end; gap: 8px; margin-top: 14px; } .enhance-foot { justify-content: flex-end; gap: 8px; margin-top: 14px; }
@@ -222,10 +235,22 @@
<canvas id="enhanceCanvas"></canvas> <canvas id="enhanceCanvas"></canvas>
</div> </div>
</div> </div>
<div class="enhance-divider" id="enhanceDivider"><div class="enhance-handle">⇔</div></div> <div class="enhance-divider" id="enhanceDivider"><div class="enhance-handle"><i data-lucide="move-horizontal" style="width:18px;height:18px"></i></div></div>
<div class="enhance-badge left">Оригинал</div> <div class="enhance-badge left">Оригинал</div>
<div class="enhance-badge right">Результат</div> <div class="enhance-badge right">Результат</div>
<div class="enhance-loading" id="enhanceLoading">Загрузка...</div> <div class="enhance-loading" id="enhanceLoading">
<div class="enhance-thinking">
<div class="enhance-thinking-text" id="enhanceThinkingText">Загрузка...</div>
<div class="enhance-thinking-dots">
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
</div>
<div class="enhance-progress" id="enhanceProgress" style="display:none">
<div class="enhance-progress-bar" id="enhanceProgressBar"></div>
</div>
</div>
</div>
</div> </div>
<div class="enhance-sliders"> <div class="enhance-sliders">
<div class="settings-field"><label>Яркость <span id="enhanceBrightnessVal">100%</span></label><input type="range" id="enhanceBrightness" min="50" max="150" value="100"></div> <div class="settings-field"><label>Яркость <span id="enhanceBrightnessVal">100%</span></label><input type="range" id="enhanceBrightness" min="50" max="150" value="100"></div>
@@ -236,8 +261,8 @@
</div> </div>
</div> </div>
<div class="card-foot enhance-foot"> <div class="card-foot enhance-foot">
<button type="button" class="btn-primary ghost" id="enhanceHistoryBtn" title="История изменений фотографии">🕘 История</button> <button type="button" class="btn-primary ghost" id="enhanceHistoryBtn" title="История изменений фотографии"><i data-lucide="history"></i> История</button>
<button type="button" class="btn-primary ghost" id="enhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию">↩ Вернуть оригинал</button> <button type="button" class="btn-primary ghost" id="enhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию"><i data-lucide="undo-2"></i> Вернуть оригинал</button>
<select id="enhanceAiMode" class="settings-input enhance-ai-mode" style="display:none" title="Режим ИИ-обработки фото"> <select id="enhanceAiMode" class="settings-input enhance-ai-mode" style="display:none" title="Режим ИИ-обработки фото">
<option value="x2">Универсально (x2)</option> <option value="x2">Универсально (x2)</option>
<option value="x4">Быстро (x4)</option> <option value="x4">Быстро (x4)</option>
@@ -245,8 +270,8 @@
<option value="facesbg">Лица + фон</option> <option value="facesbg">Лица + фон</option>
</select> </select>
<span class="enhance-ai-hint" id="enhanceAiHint" style="display:none"></span> <span class="enhance-ai-hint" id="enhanceAiHint" style="display:none"></span>
<button type="button" class="btn-primary ghost" id="enhanceAiBtn" style="display:none" title="ИИ-восстановление (Real-ESRGAN)">🤖 ИИ</button> <button type="button" class="btn-primary ghost" id="enhanceAiBtn" style="display:none" title="ИИ-восстановление (Real-ESRGAN)"><i data-lucide="sparkles"></i> ИИ</button>
<button type="button" class="btn-primary ghost" id="enhanceAutoBtn" title="Подобрать настройки автоматически">✨ Авто</button> <button type="button" class="btn-primary ghost" id="enhanceAutoBtn" title="Подобрать настройки автоматически"><i data-lucide="wand-sparkles"></i> Авто</button>
<button type="button" class="btn-primary ghost" id="enhanceCancelBtn">Оставить как есть</button> <button type="button" class="btn-primary ghost" id="enhanceCancelBtn">Оставить как есть</button>
<button type="button" class="btn-primary" id="enhanceSaveBtn">Применить</button> <button type="button" class="btn-primary" id="enhanceSaveBtn">Применить</button>
</div> </div>
+79 -13
View File
@@ -958,11 +958,53 @@ function showEnhanceResult(show) {
if (loading) loading.style.display = show ? 'none' : ''; 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) { function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading'); const el = document.getElementById('enhanceLoading');
if (!el) return; if (!el) return;
el.style.display = ''; 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) { function medianFilterPass(ctx, w, h) {
@@ -1405,7 +1447,7 @@ function openEnhance(id) {
const orig = document.getElementById('enhanceOrig'); const orig = document.getElementById('enhanceOrig');
if (orig) orig.src = API + p.photo_path; if (orig) orig.src = API + p.photo_path;
const btnAi = document.getElementById('enhanceAiBtn'); const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; } if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn'); const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = true; if (saveBtn) saveBtn.disabled = true;
loadPhotoAiConfig().then(() => { loadPhotoAiConfig().then(() => {
@@ -1419,13 +1461,25 @@ function openEnhance(id) {
setEnhanceLoadingText('Загрузка...'); setEnhanceLoadingText('Загрузка...');
const img = new Image(); const img = new Image();
img.onload = () => { img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img; enhanceSourceImg = img;
renderEnhancePreview(); renderEnhancePreview();
if (saveBtn) saveBtn.disabled = false; 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; img.src = API + p.photo_path;
modal.classList.add('open'); modal.classList.add('open');
renderIcons();
} }
function closeEnhance() { function closeEnhance() {
@@ -1441,6 +1495,8 @@ function closeEnhance() {
enhanceSaving = false; enhanceSaving = false;
resetEnhanceZoom(); resetEnhanceZoom();
if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; } if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; }
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
} }
async function runPhotoAi() { async function runPhotoAi() {
@@ -1453,11 +1509,11 @@ async function runPhotoAi() {
const btnAi = document.getElementById('enhanceAiBtn'); const btnAi = document.getElementById('enhanceAiBtn');
const saveBtn = document.getElementById('enhanceSaveBtn'); const saveBtn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true; enhanceSaving = true;
if (btnAi) { btnAi.disabled = true; btnAi.textContent = '⏳ ИИ...'; } if (btnAi) { btnAi.disabled = true; setBtnLabel(btnAi, '⏳ ИИ...'); }
if (saveBtn) saveBtn.disabled = true; if (saveBtn) saveBtn.disabled = true;
showEnhanceResult(false); showEnhanceResult(false);
setEnhanceLoadingText(mode.face === 'off' setEnhanceLoadingProgress(0, mode.face === 'off'
? 'ИИ обрабатывает фото... (может занять до минуты)' ? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...'); : 'ИИ обрабатывает фото и восстанавливает лица...');
try { try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, { const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, {
@@ -1469,7 +1525,7 @@ async function runPhotoAi() {
pollAiResult(); pollAiResult();
} catch (err) { } catch (err) {
enhanceSaving = false; enhanceSaving = false;
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; } if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null); if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null);
showEnhanceResult(true); showEnhanceResult(true);
alert(err.message); alert(err.message);
@@ -1478,6 +1534,7 @@ async function runPhotoAi() {
async function pollAiResult() { async function pollAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return; if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return;
if (enhanceAiResultPath) return;
try { try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai/${enhanceAiJobId}`, { headers: hdr() }); 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 || 'Ошибка статуса'); } if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка статуса'); }
@@ -1486,7 +1543,7 @@ async function pollAiResult() {
enhanceSaving = false; enhanceSaving = false;
enhanceAiResultPath = data.photo_path; enhanceAiResultPath = data.photo_path;
const btnAi = document.getElementById('enhanceAiBtn'); const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; } if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn'); const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = false; if (saveBtn) saveBtn.disabled = false;
const img = new Image(); const img = new Image();
@@ -1501,9 +1558,12 @@ async function pollAiResult() {
document.getElementById('enhanceSharp').value = 0; document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%'; document.getElementById('enhanceSharpVal').textContent = '0%';
renderEnhancePreview(); renderEnhancePreview();
flashEnhanceResult();
}; };
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить результат ИИ'); img.onerror = () => showEnhanceResult(true);
img.src = API + data.photo_path; img.src = API + data.photo_path;
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
showToast('ИИ результат готов'); showToast('ИИ результат готов');
return; return;
} }
@@ -1511,17 +1571,23 @@ async function pollAiResult() {
enhanceSaving = false; enhanceSaving = false;
alert(data.error || 'Ошибка обработки'); alert(data.error || 'Ошибка обработки');
const btnAi = document.getElementById('enhanceAiBtn'); const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; } if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
showEnhanceResult(true); showEnhanceResult(true);
return; 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) { } catch (err) {
enhanceSaving = false; enhanceSaving = false;
showEnhanceResult(true);
alert(err.message); alert(err.message);
const btnAi = document.getElementById('enhanceAiBtn'); const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; } if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
showEnhanceResult(true);
} }
} }
+97 -20
View File
@@ -263,38 +263,57 @@ function updateAttachHint() {
filesAttachHint.style.display = name && moduleAttachments.get(name) === true ? '' : 'none'; 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(); const p = new URLSearchParams();
if (q) p.set('search', q); if (q) p.set('search', q);
p.set('limit', String(limit)); p.set('limit', String(limit));
p.set('active', '1'); p.set('active', '1');
try { for (let i = 0; i < attempts; i++) {
const res = await fetch(`${API}/api/modules?${p}`); try {
if (!res.ok) return []; const res = await fetch(`${API}/api/modules?${p}`);
const data = await res.json(); if (!res.ok) return null;
return data.modules || []; const data = await res.json();
} catch (e) { return []; } return data.modules || [];
} catch (e) {
if (i < attempts - 1) await new Promise(r => setTimeout(r, 600));
}
}
return null;
} }
async function resolveModuleId(name) { async function resolveModuleId(name) {
const n = (name || '').trim(); const n = (name || '').trim();
if (!n) return null; 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); const list = await fetchModules(n, 5);
renderModuleOptions(list); if (list) renderModuleOptions(list);
const lower = n.toLowerCase(); 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; return exact ? exact.id : null;
} }
(async () => { (async () => {
await initDateTime(); await initDateTime();
try { try {
const list = await fetchModules('', 50); const list = await fetchModules('', MODULE_LIST_LIMIT);
if (list.length) { if (list) {
renderModuleOptions(list); renderModuleOptions(list);
moduleInput.required = true; if (list.length) {
moduleField.style.display = ''; moduleInput.required = true;
moduleField.style.display = '';
}
} }
} catch (e) { /* ignore */ } } catch (e) { /* ignore */ }
const res = await fetch(`${API}/api/students`); const res = await fetch(`${API}/api/students`);
@@ -405,6 +424,33 @@ function capture() {
}, 'image/jpeg', captureQuality); }, '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) => { form.addEventListener('submit', async (e) => {
e.preventDefault(); e.preventDefault();
if (!capturedBlob) { if (!capturedBlob) {
@@ -420,9 +466,19 @@ form.addEventListener('submit', async (e) => {
toast.textContent = 'Выберите тему модуля из списка подсказок'; toast.textContent = 'Выберите тему модуля из списка подсказок';
toast.classList.add('show', 'error'); toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3200); 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'); const btn = document.getElementById('submitBtn');
btn.disabled = true; btn.disabled = true;
btn.textContent = 'Отправка...'; btn.textContent = 'Отправка...';
@@ -437,15 +493,32 @@ form.addEventListener('submit', async (e) => {
fd.append('website', document.getElementById('hpWebsite').value); fd.append('website', document.getElementById('hpWebsite').value);
try { try {
const res = await fetch(`${API}/api/entries`, { method: 'POST', body: fd }); const { res, retried } = await postEntry(fd);
if (res.status === 429) { 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(() => ({})); const e = await res.json().catch(() => ({}));
toast.textContent = e.error || 'Уже ответили: подождите'; toast.textContent = e.error || 'Уже ответили: подождите';
toast.classList.add('show', 'error'); toast.classList.add('show', 'error');
setTimeout(() => toast.classList.remove('show', 'error'), 3200); setTimeout(() => toast.classList.remove('show', 'error'), 3200);
return; 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(); form.reset();
removePhoto(); removePhoto();
clearFiles(); clearFiles();
@@ -453,7 +526,7 @@ form.addEventListener('submit', async (e) => {
localStorage.setItem(SENT_KEY, String(Date.now())); localStorage.setItem(SENT_KEY, String(Date.now()));
showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs()); showSent('Запись отправлена!', 'Спасибо! Твоя запись уже передана преподавателю.', Date.now() + cooldownMs());
} catch (err) { } catch (err) {
alert('Ошибка: ' + err.message); notify('Не удалось отправить запись. Проверь интернет и попробуй ещё раз.', true);
} finally { } finally {
btn.disabled = false; btn.disabled = false;
btn.textContent = 'Отправить'; btn.textContent = 'Отправить';
@@ -475,12 +548,16 @@ moduleInput.addEventListener('input', () => {
clearTimeout(moduleSearchTimer); clearTimeout(moduleSearchTimer);
const q = moduleInput.value.trim(); const q = moduleInput.value.trim();
moduleSearchTimer = setTimeout(async () => { moduleSearchTimer = setTimeout(async () => {
renderModuleOptions(await fetchModules(q, 20)); const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT);
if (list) renderModuleOptions(list);
updateAttachHint(); updateAttachHint();
}, 250); }, 250);
}); });
moduleInput.addEventListener('focus', async () => { 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 () => { (async () => {
+132 -25
View File
@@ -7,6 +7,7 @@ let editGroups = [];
let editModules = []; let editModules = [];
let moduleNames = new Map(); let moduleNames = new Map();
let moduleFilterId = ''; let moduleFilterId = '';
const MODULE_LIST_LIMIT = 1000;
let moduleSearchTimer = null; let moduleSearchTimer = null;
let editModuleSearchTimer = null; let editModuleSearchTimer = null;
let modulesLoaded = false; let modulesLoaded = false;
@@ -250,7 +251,7 @@ function gridEntryHTML(e) {
const mp = mainPhotoPath(e); const mp = mainPhotoPath(e);
return ` return `
<div class="card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}"> <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="info">
<div class="name">${esc(e.student_name)}</div> <div class="name">${esc(e.student_name)}</div>
<div class="group">${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_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 ` return `
<div class="journal-card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}"> <div class="journal-card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}">
${mp ${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>`} : `<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.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>` : ''} ${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(); const p = new URLSearchParams();
if (q) p.set('search', q); if (q) p.set('search', q);
p.set('limit', String(limit)); p.set('limit', String(limit));
p.set('active', '1'); p.set('active', '1');
const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() }); for (let i = 0; i < attempts; i++) {
if (!res.ok) return []; try {
const data = await res.json().catch(() => ({})); const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() });
return data.modules || []; 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) { async function resolveModuleId(name) {
@@ -401,14 +409,18 @@ async function resolveModuleId(name) {
if (!n) return ''; if (!n) return '';
if (moduleNames.has(n)) return String(moduleNames.get(n)); if (moduleNames.has(n)) return String(moduleNames.get(n));
const list = await fetchModules(n, 10); const list = await fetchModules(n, 10);
if (!list) return null;
const lower = n.toLowerCase(); const lower = n.toLowerCase();
const exact = list.find(m => m.name.toLowerCase() === lower); const exact = list.find(m => m.name.toLowerCase() === lower);
return exact ? String(exact.id) : null; return exact ? String(exact.id) : null;
} }
async function loadModuleOptions() { async function loadModuleOptions() {
editModules = await fetchModules('', 50); const list = await fetchModules('', MODULE_LIST_LIMIT);
modulesLoaded = true; if (list) {
editModules = list;
modulesLoaded = true;
}
renderModuleOptions('moduleFilterList', editModules); renderModuleOptions('moduleFilterList', editModules);
} }
@@ -666,10 +678,53 @@ function showEnhanceResult(show) {
document.getElementById('enhanceLoading').style.display = show ? 'none' : ''; 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) { function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading'); const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = ''; 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; let enhanceZoom = 1;
@@ -835,20 +890,45 @@ async function runPhotoAi() {
const { jobId } = await res.json(); const { jobId } = await res.json();
enhanceAiJobId = jobId; enhanceAiJobId = jobId;
showEnhanceResult(false); 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) => { const result = await new Promise((resolve, reject) => {
photoAiPollTimer = setInterval(async () => { photoAiPollTimer = setInterval(async () => {
if (doneHandled) return;
try { try {
const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() }); const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() });
if (!r.ok) throw new Error('Ошибка опроса статуса'); if (!r.ok) throw new Error('Ошибка опроса статуса');
const s = await r.json(); const s = await r.json();
if (s.status === 'done') { clearInterval(photoAiPollTimer); resolve(s); } if (doneHandled) return;
else if (s.status === 'error') { clearInterval(photoAiPollTimer); reject(new Error(s.error || 'Ошибка ИИ')); } if (s.status === 'done') {
} catch (e) { clearInterval(photoAiPollTimer); reject(e); } doneHandled = true;
}, 2000); 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('ИИ результат готов'); showToast('ИИ результат готов');
enhanceAiResultPath = result.photo_path; enhanceAiResultPath = result.photo_path;
@@ -864,8 +944,9 @@ async function runPhotoAi() {
document.getElementById('enhanceDenoise').value = 0; document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%'; document.getElementById('enhanceDenoiseVal').textContent = '0%';
renderEnhancePreview(); renderEnhancePreview();
flashEnhanceResult();
}; };
aiImg.onerror = () => { showToast('Не удалось загрузить результат ИИ'); }; aiImg.onerror = () => { showEnhanceResult(true); showToast('Не удалось загрузить результат ИИ'); };
aiImg.src = `${API}${result.photo_path}`; aiImg.src = `${API}${result.photo_path}`;
} catch (e) { } catch (e) {
showEnhanceResult(true); showEnhanceResult(true);
@@ -873,7 +954,7 @@ async function runPhotoAi() {
} finally { } finally {
enhanceSaving = false; enhanceSaving = false;
btn.disabled = false; btn.disabled = false;
btn.textContent = '🤖 ИИ'; setBtnLabel(btn, 'ИИ');
} }
} }
@@ -921,6 +1002,8 @@ function openEnhance(id) {
const orig = document.getElementById('enhanceOrig'); const orig = document.getElementById('enhanceOrig');
orig.src = `${API}${mp}`; orig.src = `${API}${mp}`;
document.getElementById('enhanceRestoreBtn').style.display = e.photo_original_path ? '' : 'none'; document.getElementById('enhanceRestoreBtn').style.display = e.photo_original_path ? '' : 'none';
const aiBtn = document.getElementById('enhanceAiBtn');
if (aiBtn) { aiBtn.disabled = false; setBtnLabel(aiBtn, 'ИИ'); }
loadEnhanceEngine().then(() => { loadEnhanceEngine().then(() => {
const show = photoAiEnabled ? '' : 'none'; const show = photoAiEnabled ? '' : 'none';
document.getElementById('enhanceAiBtn').style.display = show; document.getElementById('enhanceAiBtn').style.display = show;
@@ -931,14 +1014,24 @@ function openEnhance(id) {
setEnhanceClip(50); setEnhanceClip(50);
resetEnhanceZoom(); resetEnhanceZoom();
showEnhanceResult(false); showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...'); setEnhanceLoadingProgress(0, 'Загрузка...');
renderIcons();
const img = new Image(); const img = new Image();
img.onload = () => { img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img; enhanceSourceImg = img;
renderEnhancePreview(); renderEnhancePreview();
}; };
img.onerror = () => { 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}`; img.src = `${API}${mp}`;
document.getElementById('enhanceModal').classList.add('open'); document.getElementById('enhanceModal').classList.add('open');
@@ -987,6 +1080,8 @@ function closeEnhance() {
enhanceEntryId = null; enhanceEntryId = null;
enhanceSourceImg = null; enhanceSourceImg = null;
enhanceAiResultPath = null; enhanceAiResultPath = null;
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
} }
function photoJobThumb(p) { function photoJobThumb(p) {
@@ -1061,13 +1156,23 @@ async function rollbackPhotoJob(jobId) {
const mp = data.photo_path; const mp = data.photo_path;
document.getElementById('enhanceOrig').src = `${API}${mp}`; document.getElementById('enhanceOrig').src = `${API}${mp}`;
showEnhanceResult(false); showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...'); setEnhanceLoadingProgress(0, 'Загрузка...');
const img = new Image(); const img = new Image();
img.onload = () => { img.onload = () => {
enhanceSourceImg = img; enhanceSourceImg = img;
renderEnhancePreview(); 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}`; img.src = `${API}${mp}`;
refreshEntryCard(enhanceEntryId); refreshEntryCard(enhanceEntryId);
} catch (e) { } catch (e) {
@@ -1475,14 +1580,16 @@ document.getElementById('moduleFilter').addEventListener('input', () => {
clearTimeout(moduleSearchTimer); clearTimeout(moduleSearchTimer);
const q = document.getElementById('moduleFilter').value.trim(); const q = document.getElementById('moduleFilter').value.trim();
moduleSearchTimer = setTimeout(async () => { 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); }, 250);
}); });
document.getElementById('editModule').addEventListener('input', () => { document.getElementById('editModule').addEventListener('input', () => {
clearTimeout(editModuleSearchTimer); clearTimeout(editModuleSearchTimer);
const q = document.getElementById('editModule').value.trim(); const q = document.getElementById('editModule').value.trim();
editModuleSearchTimer = setTimeout(async () => { 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); }, 250);
}); });
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadEntries(); }); 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 }) body: JSON.stringify({ used: next, used_at: next ? todayIso() : null })
}); });
if (!res.ok) { const err = await res.json().catch(() => ({})); showToast(err.error || 'Ошибка'); return; } 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 ? 'Отмечено как использованное' : 'Отметка снята'); showToast(next ? 'Отмечено как использованное' : 'Отметка снята');
} catch (e) { showToast('Ошибка: ' + e.message); } } catch (e) { showToast('Ошибка: ' + e.message); }
} }