From 853b4465915249288dd1d4a63af3aef71ad3a965 Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 14 Oct 2026 22:59:27 +0300 Subject: [PATCH] =?UTF-8?q?feat(ui):=20=D1=83=D0=BB=D1=83=D1=87=D1=88?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=84=D0=BE=D1=82=D0=BE-=D0=BC?= =?UTF-8?q?=D0=BE=D0=B4=D0=B0=D0=BB=D0=BA=D0=B8,=20=D0=BE=D1=82=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BA=D0=B8=20=D0=B7=D0=B0=D0=BF=D0=B8=D1=81?= =?UTF-8?q?=D0=B5=D0=B9=20=D0=B8=20=D1=81=D0=BF=D0=B8=D1=81=D0=BA=D0=B0=20?= =?UTF-8?q?=D0=BC=D0=BE=D0=B4=D1=83=D0=BB=D0=B5=D0=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - enhance-модалка: индикатор «размышления» с прогрессом, иконки Lucide вместо эмодзи, подсветка готового результата, защита от гонок опроса - index.js: лимит модулей 1000, повторные попытки загрузки списка, таймаут и ретрай отправки записи, требование вложений по флагу модуля - journal.js/groups.js: `data-img` получает полный путь (лайтбокс вместо миниатюры), thumbSrc отдаёт `/uploads/thumb/` и оригиналы из `.originals/` - shorts.js: переключение «Использовано» без полной перезагрузки списка - AGENTS.md: правила миниатюр (`thumbSrc`) и `data-img` --- AGENTS.md | 2 + public/admin.js | 3 +- public/groups.html | 40 ++++++++--- public/journal.html | 39 +++++++++-- public/js/groups.js | 92 +++++++++++++++++++++---- public/js/index.js | 117 ++++++++++++++++++++++++++------ public/js/journal.js | 157 ++++++++++++++++++++++++++++++++++++------- public/js/shorts.js | 15 ++++- 8 files changed, 389 insertions(+), 76 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index fd7f77b..826c9a9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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` - API calls via `fetch` with `X-Auth-Token` (токен из `localStorage`); `X-Admin-Token` больше не используется и не работает - Share pages (`share.html`, `links.html`) work without auth +- **Миниатюры фото — только `thumbSrc(p)`** из `public/admin.js` (`/uploads/...` → `/uploads/thumb/`, `/api/files/...` → `?thumb=1`, `.originals/...` отдаёт `/uploads/.originals/` — серверный роут уже уменьшает). В карточках, сетках и списках `` **обязан** идти через него; сервер кэширует результат в `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 - **Dockerfile**: Node 22 Alpine, installs deps; self-signed TLS cert генерируется **в entrypoint** (`entrypoint.sh`) только если его нет в `certs/` diff --git a/public/admin.js b/public/admin.js index d87d5b7..2444082 100644 --- a/public/admin.js +++ b/public/admin.js @@ -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 thumbSrc(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'; return p; } diff --git a/public/groups.html b/public/groups.html index 6567c48..0c3a0d3 100644 --- a/public/groups.html +++ b/public/groups.html @@ -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.left{left: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::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} -@keyframes spin{to{transform:rotate(360deg)}} +.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-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: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 .settings-field input[type=range]{width:100%} .enhance-foot{justify-content:flex-end;gap:8px;margin-top:14px;flex-wrap:wrap} @@ -182,10 +192,22 @@ -
⇔
+
Оригинал
Результат
-
Загрузка...
+
+
+
Загрузка...
+
+
+
+
+
+ +
+
@@ -196,8 +218,8 @@
- - + + - - + +
diff --git a/public/journal.html b/public/journal.html index d43f463..ed7cd0a 100644 --- a/public/journal.html +++ b/public/journal.html @@ -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.left { left: 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 .settings-field input[type=range] { width: 100%; } .enhance-foot { justify-content: flex-end; gap: 8px; margin-top: 14px; } @@ -222,10 +235,22 @@ -
⇔
+
Оригинал
Результат
-
Загрузка...
+
+
+
Загрузка...
+
+
+
+
+
+ +
+
@@ -236,8 +261,8 @@
- - + + - - + +
diff --git a/public/js/groups.js b/public/js/groups.js index 210e35d..495af3c 100644 --- a/public/js/groups.js +++ b/public/js/groups.js @@ -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, 'ИИ'); } } } diff --git a/public/js/index.js b/public/js/index.js index 4843e0d..c671a15 100644 --- a/public/js/index.js +++ b/public/js/index.js @@ -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 () => { diff --git a/public/js/journal.js b/public/js/journal.js index 83723f3..4c9a0e8 100644 --- a/public/js/journal.js +++ b/public/js/journal.js @@ -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 `
- ${mp ? `` : ''} + ${mp ? `` : ''}
${esc(e.student_name)}
${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}
@@ -271,7 +272,7 @@ function cardEntryHTML(e) { return `
${mp - ? `` + ? `` : `
`} ${e.group_name ? `${esc(e.group_name)}` : ''} ${e.module_name ? `${esc(e.module_name)}` : ''} @@ -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(); }); diff --git a/public/js/shorts.js b/public/js/shorts.js index 62322c5..e7cdc78 100644 --- a/public/js/shorts.js +++ b/public/js/shorts.js @@ -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 = ' Использовано'; + chip.title = 'Снять отметку об использовании'; + } else { + chip.classList.remove('on'); + chip.innerHTML = ' Не использовано'; + chip.title = 'Отметить как использованное'; + } + renderIcons(); + } showToast(next ? 'Отмечено как использованное' : 'Отметка снята'); } catch (e) { showToast('Ошибка: ' + e.message); } }