В части браузеров no-cache + ETag + HTTP/1.1-лимит соединений (3 постоянных SSE на страницу) давали вечное «Загрузка...» у авторизованных пользователей:
- server.js: глобальная шапка Cache-Control: no-store вместо no-cache, app.set('etag', false); медиа-/thumb-роуты и SSE по-прежнему задают свой заголовок
- journal.js/modules.js: сбой загрузки теперь показывает ошибку с кнопкой «Повторить» вместо зависшего «Загрузка...»
- admin.js: connectChatStream/connectNotifyStream стартуют отложенно (1.5/3 с), чтобы первичные фетчи данных заняли слоты соединений
- scripts/build.sh: сборка app через buildx bake --allow=network.host (docker compose build на новых BuildKit падает из-за build network: host)
- AGENTS.md: задокументированы контракты по кэш-заголовкам и сборке
3452 lines
137 KiB
JavaScript
3452 lines
137 KiB
JavaScript
let currentEntries = [];
|
||
let seenEntryIds = new Set();
|
||
let highlightNewIds = new Set();
|
||
let highlightClearTimer = null;
|
||
let editId = null;
|
||
let editGroups = [];
|
||
let editModules = [];
|
||
let moduleNames = new Map();
|
||
let moduleFilterId = '';
|
||
const MODULE_LIST_LIMIT = 1000;
|
||
let moduleSearchTimer = null;
|
||
let editModuleSearchTimer = null;
|
||
let modulesLoaded = false;
|
||
let groupsLoaded = false;
|
||
let studentsLoaded = false;
|
||
const PAGE_SIZE = 20;
|
||
let page = 1;
|
||
let totalEntries = 0;
|
||
let searchTimer = null;
|
||
let view = localStorage.getItem('journalView') === 'cards' ? 'cards' : 'list';
|
||
let aiCorrecting = false;
|
||
let editDeletePhoto = false;
|
||
let editAiSuggestion = null;
|
||
let linkSettings = null;
|
||
|
||
async function loadLinkSettings() {
|
||
if (!linkSettings) {
|
||
const res = await fetch(`${API}/api/settings`, { headers: hdr() });
|
||
linkSettings = await res.json().catch(() => ({}));
|
||
}
|
||
return linkSettings;
|
||
}
|
||
|
||
function isImageFile(name) {
|
||
return /\.(jpe?g|jfif|png|gif|webp|bmp|avif|svg|ico)$/i.test(name || '');
|
||
}
|
||
|
||
function isPlayableVideoFile(name) {
|
||
return /\.(mp4|m4v|webm|ogv)$/i.test(name || '');
|
||
}
|
||
|
||
function isVideoFile(name) {
|
||
return /\.(mp4|m4v|webm|ogv|mov|mkv|avi|mpeg|mpg|3gp|ts)$/i.test(name || '');
|
||
}
|
||
|
||
function mainPhotoPath(e) {
|
||
if (e.photo_path) return e.photo_path;
|
||
if (e.photos && e.photos.length) return e.photos[0].photo_path;
|
||
return null;
|
||
}
|
||
|
||
function journalImgHTML(mp) {
|
||
return `<div class="img-media"><img class="img-load" src="${thumbSrc(mp)}" data-img="${API}${mp}" loading="lazy" decoding="async" alt=""><div class="img-skeleton"><span class="img-spin"></span><span>Загрузка…</span></div></div>`;
|
||
}
|
||
|
||
const REPORT_CARD_FIELDS = [
|
||
{ key: 'photo', label: 'Фото' },
|
||
{ key: 'lastname', label: 'Фамилия' },
|
||
{ key: 'firstname', label: 'Имя' },
|
||
{ key: 'group', label: 'Группа' },
|
||
{ key: 'module', label: 'Модуль' },
|
||
{ key: 'topic', label: 'Сообщение' },
|
||
{ key: 'date', label: 'Дата и время' },
|
||
{ key: 'files', label: 'Файлы' },
|
||
];
|
||
const REPORT_CARD_FIELDS_KEY = 'reportCardFields';
|
||
const reportCardFields = loadReportCardFields();
|
||
const REPORT_CARD_EMBED_KEY = 'reportCardEmbedImages';
|
||
let reportCardEmbed = loadReportCardEmbed();
|
||
const REPORT_CARD_STUDENT_WORKS_KEY = 'reportCardStudentWorks';
|
||
let reportCardStudentWorks = loadReportCardStudentWorks();
|
||
const REPORT_CARD_LOGO_KEY = 'reportCardLogo';
|
||
let reportCardLogoOn = loadReportCardLogo();
|
||
let reportCardLogoSrc = '';
|
||
let reportCardEntryId = null;
|
||
let galleryList = [];
|
||
let galleryIndex = -1;
|
||
const studentWorksCache = new Map();
|
||
const studentImagesCache = new Map();
|
||
let reportCardEmbedImages = [];
|
||
|
||
function loadReportCardEmbed() {
|
||
try {
|
||
return localStorage.getItem(REPORT_CARD_EMBED_KEY) === '1';
|
||
} catch (err) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function saveReportCardEmbed() {
|
||
try {
|
||
localStorage.setItem(REPORT_CARD_EMBED_KEY, reportCardEmbed ? '1' : '0');
|
||
} catch (err) {
|
||
showToast('Не удалось сохранить настройку галереи', true);
|
||
}
|
||
}
|
||
|
||
function loadReportCardStudentWorks() {
|
||
try {
|
||
return localStorage.getItem(REPORT_CARD_STUDENT_WORKS_KEY) === '1';
|
||
} catch (err) {
|
||
return false;
|
||
}
|
||
}
|
||
|
||
function saveReportCardStudentWorks() {
|
||
try {
|
||
localStorage.setItem(REPORT_CARD_STUDENT_WORKS_KEY, reportCardStudentWorks ? '1' : '0');
|
||
} catch (err) {
|
||
showToast('Не удалось сохранить настройку «Фото на занятиях»', true);
|
||
}
|
||
}
|
||
|
||
function loadReportCardLogo() {
|
||
try {
|
||
return localStorage.getItem(REPORT_CARD_LOGO_KEY) !== '0';
|
||
} catch (err) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
function saveReportCardLogo() {
|
||
try {
|
||
localStorage.setItem(REPORT_CARD_LOGO_KEY, reportCardLogoOn ? '1' : '0');
|
||
} catch (err) {
|
||
showToast('Не удалось сохранить настройку «Логотип»', true);
|
||
}
|
||
}
|
||
|
||
function reportCardEmbedTokens() {
|
||
return new Set(reportCardEmbedImages.map(f => f.token));
|
||
}
|
||
|
||
function loadReportCardFields() {
|
||
const all = REPORT_CARD_FIELDS.map(f => f.key);
|
||
try {
|
||
const raw = JSON.parse(localStorage.getItem(REPORT_CARD_FIELDS_KEY) || 'null');
|
||
if (Array.isArray(raw)) return all.filter(k => raw.includes(k));
|
||
} catch (err) {
|
||
return all;
|
||
}
|
||
return all;
|
||
}
|
||
|
||
function saveReportCardFields() {
|
||
try {
|
||
localStorage.setItem(REPORT_CARD_FIELDS_KEY, JSON.stringify(reportCardFields));
|
||
} catch (err) {
|
||
showToast('Не удалось сохранить настройки полей', true);
|
||
}
|
||
}
|
||
|
||
function reportCardFieldOn(key) {
|
||
return reportCardFields.includes(key);
|
||
}
|
||
|
||
function splitStudentName(full) {
|
||
const s = String(full || '').trim();
|
||
const i = s.indexOf(' ');
|
||
if (i < 0) return { lastname: s, firstname: '' };
|
||
return { lastname: s.slice(0, i), firstname: s.slice(i + 1).trim() };
|
||
}
|
||
|
||
function reportCardFilesHTML(e) {
|
||
const hidden = reportCardEmbed ? reportCardEmbedTokens() : null;
|
||
const files = (e.files || []).filter(f => !(hidden && hidden.has(f.token)));
|
||
if (!files.length) return '';
|
||
return `<div class="student-card__meta-files" id="reportCardFiles">${files.map(f => {
|
||
const url = `${API}/api/files/${f.token}`;
|
||
if (isImageFile(f.name)) return `<a href="#" data-img="${url}" title="Открыть">${esc(f.name)}</a>`;
|
||
if (isPlayableVideoFile(f.name)) return `<a href="${url}?play=1" data-video="${url}?play=1" data-video-name="${esc(f.name)}" data-video-token="${f.token}" title="Смотреть">${esc(f.name)}</a>`;
|
||
const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать';
|
||
return `<a href="${url}" download title="${note}">${esc(f.name)}</a>`;
|
||
}).join('')}</div>`;
|
||
}
|
||
|
||
function reportCardGalleryHTML() {
|
||
if (!reportCardEmbed) return '';
|
||
return '<div class="student-card__gallery-grid is-loading" id="reportCardEmbedGallery"></div>';
|
||
}
|
||
|
||
function paintReportCardEmbedGallery(box, images) {
|
||
if (!box) return;
|
||
box.classList.remove('is-loading');
|
||
if (!images.length) { box.remove(); galleryList = []; return; }
|
||
galleryList = images.map(f => `${API}/api/files/${f.token}`);
|
||
box.innerHTML = images.map((f, i) => {
|
||
const url = `${API}/api/files/${f.token}`;
|
||
return `<button type="button" class="sc-gal__shot" data-img="${url}" data-gal-index="${i}" title="${esc(f.name)}" aria-label="${esc(f.name)}">
|
||
<img class="sc-gal__img" src="${thumbSrc(url)}" alt="${esc(f.name)}" loading="lazy" decoding="async">
|
||
<span class="sc-gal__spin" aria-hidden="true"></span>
|
||
<span class="sc-gal__zoom" aria-hidden="true"><i data-lucide="maximize-2"></i></span>
|
||
</button>`;
|
||
}).join('');
|
||
settleReportGallery(box);
|
||
equalizeReportGallery(box);
|
||
}
|
||
|
||
function equalizeReportGallery(root) {
|
||
if (!root) return;
|
||
const imgs = Array.from(root.querySelectorAll('.sc-gal__img'));
|
||
if (!imgs.length) return;
|
||
let pending = imgs.length;
|
||
const apply = () => {
|
||
requestAnimationFrame(() => {
|
||
let maxH = 0;
|
||
imgs.forEach(img => {
|
||
const h = img.getBoundingClientRect().height;
|
||
if (h > maxH) maxH = h;
|
||
});
|
||
if (maxH > 0) {
|
||
root.style.setProperty('--gal-h', `${Math.round(maxH)}px`);
|
||
root.classList.add('is-equal');
|
||
}
|
||
});
|
||
};
|
||
const done = () => { pending -= 1; if (pending <= 0) apply(); };
|
||
imgs.forEach(img => {
|
||
if (img.complete && img.naturalWidth > 0) { done(); return; }
|
||
img.addEventListener('load', done, { once: true });
|
||
img.addEventListener('error', done, { once: true });
|
||
});
|
||
}
|
||
|
||
function settleReportGallery(root) {
|
||
if (!root) return;
|
||
root.querySelectorAll('.sc-gal__img').forEach(img => {
|
||
const shot = img.closest('.sc-gal__shot');
|
||
const ready = () => {
|
||
img.classList.add('is-loaded');
|
||
if (img.naturalWidth > 0 && img.naturalHeight > 0 && img.naturalWidth > img.naturalHeight) img.classList.add('is-landscape');
|
||
if (shot) shot.classList.add('is-ready');
|
||
};
|
||
const failed = () => {
|
||
img.classList.add('is-error');
|
||
if (shot) shot.classList.add('is-error');
|
||
};
|
||
if (img.complete) {
|
||
if (img.naturalWidth > 0) ready(); else failed();
|
||
return;
|
||
}
|
||
img.addEventListener('load', ready, { once: true });
|
||
img.addEventListener('error', failed, { once: true });
|
||
});
|
||
}
|
||
|
||
async function hydrateReportCardEmbedGallery(e) {
|
||
const box = document.getElementById('reportCardEmbedGallery');
|
||
if (!box) { reportCardEmbedImages = []; galleryList = []; return; }
|
||
const name = String(e.student_name || '').trim();
|
||
if (!name) { reportCardEmbedImages = []; box.remove(); galleryList = []; return; }
|
||
let images = studentImagesCache.get(name);
|
||
if (!images) {
|
||
box.innerHTML = '<span class="sc-w__spin" aria-hidden="true"></span>';
|
||
try {
|
||
const res = await fetch(`${API}/api/students/image-files-by-name?name=${encodeURIComponent(name)}&limit=3`, { headers: hdr() });
|
||
const data = await res.json();
|
||
images = (data.files || []).filter(f => f && f.token);
|
||
studentImagesCache.set(name, images);
|
||
} catch (err) {
|
||
if (reportCardEntryId === e.id) {
|
||
const cur = document.getElementById('reportCardEmbedGallery');
|
||
if (cur) cur.remove();
|
||
}
|
||
return;
|
||
}
|
||
}
|
||
if (reportCardEntryId !== e.id) return;
|
||
reportCardEmbedImages = images;
|
||
paintReportCardEmbedGallery(box, images);
|
||
refreshReportCardFiles(e);
|
||
renderIcons();
|
||
}
|
||
|
||
function refreshReportCardFiles(e) {
|
||
const el = document.getElementById('reportCardFiles');
|
||
const html = reportCardFilesHTML(e);
|
||
if (!html) { if (el) el.remove(); return; }
|
||
if (el) el.outerHTML = html;
|
||
}
|
||
|
||
function paintReportCardStudentWorks(box, photos, entryId) {
|
||
if (!box || reportCardEntryId !== entryId) return;
|
||
if (!photos.length) { box.remove(); return; }
|
||
box.classList.remove('is-loading');
|
||
box.innerHTML = photos.map(p => `<button type="button" class="sc-w__shot" data-img="${API}${p}" title="Открыть фотографию" aria-label="Открыть фотографию">
|
||
<img class="sc-w__img" src="${thumbSrc(p)}" alt="" loading="lazy" decoding="async">
|
||
</button>`).join('');
|
||
}
|
||
|
||
async function hydrateReportCardStudentWorks(e) {
|
||
const box = document.getElementById('reportCardStudentWorks');
|
||
if (!box) return;
|
||
const name = String(e.student_name || '').trim();
|
||
if (!name) { box.remove(); return; }
|
||
const key = `${name}#${e.id}`;
|
||
const cached = studentWorksCache.get(key);
|
||
if (cached) { paintReportCardStudentWorks(box, cached, e.id); return; }
|
||
box.classList.add('is-loading');
|
||
box.innerHTML = '<span class="sc-w__spin" aria-hidden="true"></span>';
|
||
try {
|
||
const res = await fetch(`${API}/api/students/works-by-name?name=${encodeURIComponent(name)}&limit=3&exclude_entry=${encodeURIComponent(e.id)}`, { headers: hdr() });
|
||
const data = await res.json();
|
||
const photos = (data.photos || []).filter(Boolean);
|
||
studentWorksCache.set(key, photos);
|
||
if (reportCardEntryId !== e.id) return;
|
||
paintReportCardStudentWorks(document.getElementById('reportCardStudentWorks'), photos, e.id);
|
||
} catch (err) {
|
||
if (reportCardEntryId === e.id) {
|
||
const cur = document.getElementById('reportCardStudentWorks');
|
||
if (cur) cur.remove();
|
||
}
|
||
}
|
||
}
|
||
|
||
function reportCardMetaHTML(e) {
|
||
let html = '';
|
||
if (reportCardFieldOn('date') && e.created_at) {
|
||
html += `<div class="student-card__meta-val">${esc(fmtFull(e.created_at))}</div>`;
|
||
}
|
||
if (reportCardFieldOn('files')) html += reportCardFilesHTML(e);
|
||
html += reportCardGalleryHTML();
|
||
if (reportCardStudentWorks && e.student_name) html += '<div class="student-card__student-works" id="reportCardStudentWorks"></div>';
|
||
return html;
|
||
}
|
||
|
||
function moduleIconText(name) {
|
||
const s = (name || '').trim().slice(0, 2);
|
||
if (!s) return '';
|
||
return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase();
|
||
}
|
||
|
||
function renderReportCard(e) {
|
||
const photo = document.getElementById('reportCardPhoto');
|
||
const noPhoto = document.getElementById('reportCardNoPhoto');
|
||
document.getElementById('reportCardMedia').hidden = !reportCardFieldOn('photo');
|
||
const mp = mainPhotoPath(e);
|
||
if (mp) {
|
||
photo.src = thumbSrc(mp);
|
||
photo.dataset.img = `${API}${mp}`;
|
||
photo.alt = e.student_name || '';
|
||
photo.hidden = false;
|
||
noPhoto.hidden = true;
|
||
} else {
|
||
photo.src = '';
|
||
delete photo.dataset.img;
|
||
photo.alt = '';
|
||
photo.hidden = true;
|
||
noPhoto.hidden = false;
|
||
}
|
||
document.getElementById('reportCardLogo').hidden = !reportCardLogoOn || !reportCardLogoSrc;
|
||
const name = splitStudentName(e.student_name);
|
||
const lastEl = document.getElementById('reportCardLastName');
|
||
const firstEl = document.getElementById('reportCardFirstName');
|
||
lastEl.textContent = reportCardFieldOn('lastname') ? name.lastname : '';
|
||
firstEl.textContent = reportCardFieldOn('firstname') ? name.firstname : '';
|
||
document.getElementById('reportCardName').hidden = !lastEl.textContent && !firstEl.textContent;
|
||
const topic = e.description || '';
|
||
const topicEl = document.getElementById('reportCardText');
|
||
topicEl.textContent = topic;
|
||
topicEl.hidden = !reportCardFieldOn('topic') || !topic;
|
||
const groupBadge = document.getElementById('reportCardTime');
|
||
const group = e.group_name || '';
|
||
groupBadge.textContent = group;
|
||
groupBadge.parentElement.hidden = !reportCardFieldOn('group') || !group;
|
||
const toolBadge = document.getElementById('reportCardModule').parentElement;
|
||
const tool = e.module_name || '';
|
||
document.getElementById('reportCardModule').textContent = tool;
|
||
document.getElementById('reportCardModuleIcon').textContent = moduleIconText(tool);
|
||
toolBadge.hidden = !reportCardFieldOn('module') || !tool;
|
||
const meta = document.getElementById('reportCardMeta');
|
||
reportCardEmbedImages = [];
|
||
meta.innerHTML = reportCardMetaHTML(e);
|
||
galleryList = [];
|
||
settleReportGallery(meta);
|
||
hydrateReportCardEmbedGallery(e);
|
||
hydrateReportCardStudentWorks(e);
|
||
renderIcons();
|
||
}
|
||
|
||
function refreshReportCard() {
|
||
if (reportCardEntryId === null) return;
|
||
const e = currentEntries.find(x => x.id === reportCardEntryId);
|
||
if (e) renderReportCard(e);
|
||
}
|
||
|
||
function openReportCard(id) {
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (!e) return;
|
||
reportCardEntryId = id;
|
||
renderReportCard(e);
|
||
document.getElementById('reportCardModal').classList.add('open');
|
||
document.body.classList.add('report-card-open');
|
||
}
|
||
|
||
function closeReportCard() {
|
||
reportCardEntryId = null;
|
||
galleryList = [];
|
||
galleryIndex = -1;
|
||
closeImgModal();
|
||
document.getElementById('reportCardModal').classList.remove('open');
|
||
document.body.classList.remove('report-card-open');
|
||
setReportFieldsOpen(false);
|
||
}
|
||
|
||
function filesHTML(files) {
|
||
if (!files || !files.length) return '';
|
||
return `<div class="entry-files">${files.map(f => {
|
||
const url = `${API}/api/files/${f.token}`;
|
||
let link;
|
||
if (isImageFile(f.name)) {
|
||
link = `<a class="f-link" href="#" data-img="${url}" title="Открыть">${esc(f.name)}</a>`;
|
||
} else if (isPlayableVideoFile(f.name)) {
|
||
link = `<a class="f-link" href="${url}?play=1" data-video="${url}?play=1" data-video-name="${esc(f.name)}" data-video-token="${f.token}" title="Смотреть">${esc(f.name)}</a>`;
|
||
} else {
|
||
const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать';
|
||
link = `<a class="f-link" href="${url}" download title="${note}">${esc(f.name)}</a>`;
|
||
}
|
||
return `<span class="f-item">${link}<button class="f-detach" data-detach="${f.id}" title="Открепить файл">✕</button></span>`;
|
||
}).join('')}</div>`;
|
||
}
|
||
|
||
const AI_STATUS_LABELS = {
|
||
pending: 'ИИ: в очереди',
|
||
processing: 'ИИ: проверяет…',
|
||
done: 'ИИ: проверено',
|
||
skipped: 'ИИ: пропущено',
|
||
error: 'ИИ: ошибка',
|
||
reverted: 'ИИ: возвращён оригинал',
|
||
};
|
||
|
||
const AI_STATUS_ICONS = {
|
||
pending: 'clock',
|
||
processing: 'loader',
|
||
done: 'circle-check',
|
||
skipped: 'skip-forward',
|
||
error: 'circle-alert',
|
||
reverted: 'undo',
|
||
};
|
||
|
||
function aiBadge(e) {
|
||
if (!e || !e.ai_status) return '';
|
||
const st = e.ai_status;
|
||
const label = AI_STATUS_LABELS[st] || `ИИ: ${st}`;
|
||
const icon = AI_STATUS_ICONS[st] || 'sparkles';
|
||
return `<span class="ai-badge ai-badge-ic ai-badge-${esc(st)}" data-ai-badge="${e.id}" title="${esc(label)}" role="img" aria-label="${esc(label)}"><i data-lucide="${icon}"></i></span>`;
|
||
}
|
||
|
||
function findFile(id) {
|
||
for (const e of currentEntries) {
|
||
const f = (e.files || []).find(x => x.id === id);
|
||
if (f) return f;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
async function detachFile(id) {
|
||
const f = findFile(id);
|
||
if (!f) return;
|
||
if (!confirm(`Открепить файл «${f.name}» от записи? Он переместится в «Файлы → Откреплённые».`)) return;
|
||
const res = await fetch(`${API}/api/files/${id}/detach`, { method: 'POST', headers: hdr() });
|
||
if (res.ok) {
|
||
showToast('Файл откреплён');
|
||
if (f.entry_id) refreshEntryCard(f.entry_id);
|
||
else loadEntries();
|
||
} else {
|
||
const err = await res.json().catch(() => ({}));
|
||
alert(err.error || 'Ошибка');
|
||
}
|
||
}
|
||
|
||
function gridEntryHTML(e) {
|
||
const mp = mainPhotoPath(e);
|
||
return `
|
||
<div class="card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}">
|
||
${mp ? journalImgHTML(mp) : ''}
|
||
<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>
|
||
<div class="desc">${esc(e.description)}${aiBadge(e)}</div>
|
||
${filesHTML(e.files)}
|
||
<div class="time">${fmtFull(e.created_at)}</div>
|
||
</div>
|
||
<button class="edit" data-report="${e.id}" title="Карточка отчёта"><i data-lucide="contact"></i></button>
|
||
<button class="edit" data-edit="${e.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||
${mp ? `<button class="edit" data-enhance="${e.id}" title="Улучшить фото"><i data-lucide="sparkles"></i></button>` : ''}
|
||
${mp ? `<button class="edit" data-cpuenhance="${e.id}" title="CPU-обработка фото"><i data-lucide="cpu"></i></button>` : ''}
|
||
<button class="del" data-del="${e.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function cardEntryHTML(e) {
|
||
const mp = mainPhotoPath(e);
|
||
return `
|
||
<div class="journal-card${highlightNewIds.has(e.id) ? ' entry-appear' : ' entry-enter'}">
|
||
${mp
|
||
? journalImgHTML(mp)
|
||
: `<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>` : ''}
|
||
<div class="body">
|
||
<div class="name">${esc(e.student_name)}</div>
|
||
<div class="desc">${esc(e.description)}${aiBadge(e)}</div>
|
||
${filesHTML(e.files)}
|
||
</div>
|
||
<div class="foot">
|
||
<span>${fmtFull(e.created_at)}</span>
|
||
<span>
|
||
<button class="edit" data-report="${e.id}" title="Карточка отчёта"><i data-lucide="contact"></i></button>
|
||
<button class="edit" data-edit="${e.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||
${mp ? `<button class="edit" data-enhance="${e.id}" title="Улучшить фото"><i data-lucide="sparkles"></i></button>` : ''}
|
||
${mp ? `<button class="edit" data-cpuenhance="${e.id}" title="CPU-обработка фото"><i data-lucide="cpu"></i></button>` : ''}
|
||
<button class="del" data-del="${e.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||
</span>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function renderGrid() {
|
||
const grid = document.getElementById('grid');
|
||
if (!currentEntries.length) {
|
||
const fmt = d => d ? d.split('-').reverse().join('.') : '';
|
||
const from = fmt(document.getElementById('dateFrom').value);
|
||
const to = fmt(document.getElementById('dateTo').value);
|
||
let range = '';
|
||
if (from && to) range = ` за ${from} – ${to}`;
|
||
else if (from) range = ` с ${from}`;
|
||
else if (to) range = ` по ${to}`;
|
||
grid.className = 'grid';
|
||
grid.innerHTML = `<div class="empty">Ничего не найдено${range}</div>`;
|
||
return;
|
||
}
|
||
if (view === 'cards') {
|
||
grid.className = 'journal-cards';
|
||
grid.innerHTML = currentEntries.map(cardEntryHTML).join('');
|
||
} else {
|
||
grid.className = 'grid';
|
||
grid.innerHTML = currentEntries.map(gridEntryHTML).join('');
|
||
}
|
||
const items = Array.from(grid.children);
|
||
items.forEach((el, i) => {
|
||
el.style.animationDelay = `${Math.min(i * 45, 500)}ms`;
|
||
});
|
||
renderIcons();
|
||
settleJournalThumbs(grid);
|
||
}
|
||
|
||
function settleJournalThumbs(root) {
|
||
if (!root) return;
|
||
root.querySelectorAll('.img-media img.img-load, .img-media img.img-error').forEach((img) => {
|
||
if (img.complete && img.naturalWidth > 0) {
|
||
img.classList.remove('img-load', 'img-error');
|
||
img.classList.add('img-loaded');
|
||
} else if (img.complete && img.naturalWidth === 0) {
|
||
img.classList.remove('img-load');
|
||
img.classList.add('img-error');
|
||
const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton');
|
||
if (sk) sk.innerHTML = '<span>Нет фото</span>';
|
||
}
|
||
});
|
||
}
|
||
|
||
function bindJournalThumbLoading() {
|
||
const grid = document.getElementById('grid');
|
||
if (!grid) return;
|
||
const settle = (img) => {
|
||
if (!img || !img.classList) return;
|
||
img.classList.remove('img-load', 'img-error');
|
||
img.classList.add('img-loaded');
|
||
};
|
||
const fail = (img) => {
|
||
if (!img || !img.classList) return;
|
||
img.classList.remove('img-load');
|
||
img.classList.add('img-error');
|
||
const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton');
|
||
if (sk) sk.innerHTML = '<span>Нет фото</span>';
|
||
};
|
||
grid.addEventListener('load', (e) => {
|
||
if (e.target.tagName === 'IMG') settle(e.target);
|
||
}, true);
|
||
grid.addEventListener('error', (e) => {
|
||
if (e.target.tagName === 'IMG') fail(e.target);
|
||
}, true);
|
||
}
|
||
|
||
function refreshEntryCardDom(e) {
|
||
const btn = document.querySelector(`[data-edit="${e.id}"]`);
|
||
const card = btn ? btn.closest('.card, .journal-card') : null;
|
||
if (!card) return;
|
||
const tmp = document.createElement('div');
|
||
tmp.innerHTML = (view === 'cards' ? cardEntryHTML(e) : gridEntryHTML(e)).trim();
|
||
const fresh = tmp.firstElementChild;
|
||
fresh.classList.remove('entry-enter', 'entry-appear');
|
||
fresh.style.animationDelay = '';
|
||
card.replaceWith(fresh);
|
||
renderIcons();
|
||
settleJournalThumbs(fresh);
|
||
}
|
||
|
||
async function refreshEntryCard(id) {
|
||
const res = await fetch(`${API}/api/entries/${id}`, { headers: hdr() });
|
||
if (!res.ok) return false;
|
||
const e = await res.json();
|
||
const idx = currentEntries.findIndex(x => x.id === e.id);
|
||
if (idx !== -1) currentEntries[idx] = e;
|
||
refreshEntryCardDom(e);
|
||
return true;
|
||
}
|
||
|
||
function setView(v) {
|
||
view = v === 'cards' ? 'cards' : 'list';
|
||
localStorage.setItem('journalView', view);
|
||
document.querySelectorAll('#viewToggle button').forEach(b => {
|
||
b.classList.toggle('active', b.dataset.view === view);
|
||
});
|
||
renderGrid();
|
||
}
|
||
|
||
function setDefaultDates() {
|
||
const today = todayIso();
|
||
document.getElementById('dateFrom').value = today;
|
||
document.getElementById('dateTo').value = today;
|
||
}
|
||
|
||
async function loadGroupOptions() {
|
||
if (groupsLoaded) return;
|
||
const sel = document.getElementById('groupFilter');
|
||
while (sel.options.length > 1) sel.remove(1);
|
||
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
|
||
const groups = await res.json();
|
||
groups.forEach(g => {
|
||
const o = document.createElement('option');
|
||
o.value = g.id; o.textContent = g.name;
|
||
sel.appendChild(o);
|
||
});
|
||
groupsLoaded = true;
|
||
}
|
||
|
||
function renderModuleOptions(datalistId, list) {
|
||
list.forEach(m => moduleNames.set(m.name, m.id));
|
||
const dl = document.getElementById(datalistId);
|
||
if (!dl) return;
|
||
dl.innerHTML = '';
|
||
list.forEach(m => {
|
||
const opt = document.createElement('option');
|
||
opt.value = m.name;
|
||
dl.appendChild(opt);
|
||
});
|
||
}
|
||
|
||
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');
|
||
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) {
|
||
const n = (name || '').trim();
|
||
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() {
|
||
const list = await fetchModules('', MODULE_LIST_LIMIT);
|
||
if (list) {
|
||
editModules = list;
|
||
modulesLoaded = true;
|
||
}
|
||
renderModuleOptions('moduleFilterList', editModules);
|
||
}
|
||
|
||
async function applyModuleFilter() {
|
||
const inp = document.getElementById('moduleFilter');
|
||
const resolved = await resolveModuleId(inp.value);
|
||
if (resolved === null) {
|
||
inp.value = '';
|
||
moduleFilterId = '';
|
||
showToast('Модуль не найден — фильтр сброшен');
|
||
} else {
|
||
moduleFilterId = resolved;
|
||
}
|
||
page = 1;
|
||
loadEntries();
|
||
}
|
||
|
||
function fillEditModuleInput(entry) {
|
||
const inp = document.getElementById('editModule');
|
||
if (!inp) return;
|
||
if (entry.module_name && entry.module_id) moduleNames.set(entry.module_name, entry.module_id);
|
||
inp.value = entry.module_name || '';
|
||
renderModuleOptions('editModuleList', editModules);
|
||
}
|
||
|
||
async function loadStudentOptions() {
|
||
if (studentsLoaded) return;
|
||
const dl = document.getElementById('studentFilterList');
|
||
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
|
||
const names = await res.json();
|
||
dl.innerHTML = names.map(n => `<option value="${esc(n)}">`).join('');
|
||
studentsLoaded = true;
|
||
}
|
||
|
||
function renderGridLoadError(msg) {
|
||
const grid = document.getElementById('grid');
|
||
if (!grid) return;
|
||
if (grid.querySelector('.empty') && grid.children.length === 1 && !seenEntryIds.size) grid.innerHTML = `<div class="empty">${esc(msg)} <button type="button" class="btn-link" data-retry-entries>Повторить</button></div>`;
|
||
const btn = grid.querySelector('[data-retry-entries]');
|
||
if (btn) btn.addEventListener('click', () => gridErrorRetry(btn));
|
||
}
|
||
|
||
function gridErrorRetry(btn) {
|
||
const grid = document.getElementById('grid');
|
||
if (grid && grid.querySelector('[data-retry-entries]') === btn) grid.innerHTML = '<div class="empty">Загрузка...</div>';
|
||
loadEntries();
|
||
}
|
||
|
||
async function loadEntries() {
|
||
const p = new URLSearchParams();
|
||
const q = document.getElementById('searchInput').value;
|
||
const sn = document.getElementById('studentFilter').value;
|
||
const gid = document.getElementById('groupFilter').value;
|
||
const df = document.getElementById('dateFrom').value;
|
||
const dt = document.getElementById('dateTo').value;
|
||
if (q) p.set('search', q);
|
||
if (sn) p.set('student_name', sn);
|
||
if (gid) p.set('group_id', gid);
|
||
if (df) p.set('date_from', df);
|
||
if (dt) p.set('date_to', dt);
|
||
if (moduleFilterId) p.set('module_id', moduleFilterId);
|
||
p.set('limit', PAGE_SIZE);
|
||
p.set('offset', (page - 1) * PAGE_SIZE);
|
||
let res;
|
||
try {
|
||
res = await fetch(`${API}/api/entries?${p}`, { headers: hdr() });
|
||
} catch (e) {
|
||
return renderGridLoadError('Не удалось загрузить записи — сеть недоступна');
|
||
}
|
||
if (!res.ok) {
|
||
return renderGridLoadError(`Не удалось загрузить записи (${res.status})`);
|
||
}
|
||
let data;
|
||
try {
|
||
data = await res.json();
|
||
} catch (e) {
|
||
return renderGridLoadError('Не удалось загрузить записи — некорректный ответ сервера');
|
||
}
|
||
if (!data || !Array.isArray(data.entries)) {
|
||
return renderGridLoadError('Не удалось загрузить записи — некорректный ответ сервера');
|
||
}
|
||
const firstLoad = seenEntryIds.size === 0;
|
||
const newIds = firstLoad ? [] : data.entries.filter(e => !seenEntryIds.has(e.id)).map(e => e.id);
|
||
if (newIds.length) {
|
||
highlightNewIds = new Set([...highlightNewIds, ...newIds]);
|
||
if (highlightClearTimer) clearTimeout(highlightClearTimer);
|
||
highlightClearTimer = setTimeout(() => { highlightNewIds = new Set(); }, 8000);
|
||
}
|
||
data.entries.forEach(e => seenEntryIds.add(e.id));
|
||
currentEntries = data.entries;
|
||
totalEntries = data.total;
|
||
renderGrid();
|
||
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalEntries / PAGE_SIZE)), goPage);
|
||
}
|
||
|
||
function goPage(p) {
|
||
page = p;
|
||
loadEntries();
|
||
}
|
||
|
||
let liveSource = null;
|
||
let liveReconnectTimer = null;
|
||
let entriesRefreshTimer = null;
|
||
function applyAiUpdate(update) {
|
||
const e = currentEntries.find(x => x.id === update.id);
|
||
if (!e) return;
|
||
e.ai_status = update.ai_status;
|
||
e.ai_error = update.ai_error || null;
|
||
if (update.description !== null && update.description !== undefined) e.description = update.description;
|
||
if (update.description_ai !== null && update.description_ai !== undefined) e.description_ai = update.description_ai;
|
||
if (update.description_original !== null && update.description_original !== undefined) e.description_original = update.description_original;
|
||
if (update.ai_status === 'done' || update.ai_status === 'reverted') e.ai_checked_at = new Date().toISOString();
|
||
document.querySelectorAll(`[data-ai-badge="${update.id}"]`).forEach(badgeEl => {
|
||
const desc = badgeEl.closest('.desc');
|
||
if (desc && update.description !== null && update.description !== undefined) {
|
||
desc.textContent = e.description;
|
||
desc.insertAdjacentHTML('beforeend', aiBadge(e));
|
||
} else {
|
||
badgeEl.outerHTML = aiBadge(e);
|
||
}
|
||
});
|
||
renderIcons();
|
||
const editBadge = document.getElementById('editAiStatus');
|
||
if (editId === update.id && editBadge && editBadge.style.display !== 'none') {
|
||
renderEditAiStatus(e);
|
||
}
|
||
if (editId === update.id) {
|
||
const ta = document.getElementById('editDesc');
|
||
if (ta && document.activeElement !== ta && update.description !== null && update.description !== undefined) {
|
||
ta.value = e.description;
|
||
}
|
||
}
|
||
}
|
||
function connectLiveUpdates() {
|
||
if (liveSource) { liveSource.close(); liveSource = null; }
|
||
const connect = () => {
|
||
const t = sessionStorage.getItem('authToken');
|
||
if (!t) return;
|
||
liveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
|
||
liveSource.addEventListener('entries_changed', () => {
|
||
if (entriesRefreshTimer) return;
|
||
entriesRefreshTimer = setTimeout(() => {
|
||
entriesRefreshTimer = null;
|
||
showToast('Поступила новая запись — список обновлён');
|
||
page = 1;
|
||
loadEntries();
|
||
}, 300);
|
||
});
|
||
liveSource.addEventListener('ai_status', ev => {
|
||
try { applyAiUpdate(JSON.parse(ev.data)); } catch (err) {}
|
||
});
|
||
liveSource.onerror = () => {
|
||
if (liveSource) { liveSource.close(); liveSource = null; }
|
||
if (liveReconnectTimer) clearTimeout(liveReconnectTimer);
|
||
liveReconnectTimer = setTimeout(connect, 5000);
|
||
};
|
||
};
|
||
connect();
|
||
window.addEventListener('beforeunload', () => { if (liveSource) liveSource.close(); });
|
||
}
|
||
|
||
async function openEdit(id) {
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (!e) return;
|
||
editId = id;
|
||
editDeletePhoto = false;
|
||
editAiSuggestion = null;
|
||
fillAutocomplete();
|
||
document.getElementById('editName').value = e.student_name;
|
||
document.getElementById('editDesc').value = e.description;
|
||
renderEditAiStatus(e);
|
||
const sel = document.getElementById('editGroup');
|
||
if (!editGroups.length) {
|
||
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
|
||
editGroups = await res.json();
|
||
sel.innerHTML = editGroups.map(g => `<option value="${g.id}">${esc(g.name)}</option>`).join('');
|
||
}
|
||
sel.value = e.group_id;
|
||
if (!modulesLoaded) await loadModuleOptions();
|
||
fillEditModuleInput(e);
|
||
renderEditPhotos(e.photos || [], e.photo_path);
|
||
document.getElementById('editModal').classList.add('open');
|
||
}
|
||
|
||
function renderEditPhotos(photos, mainPath) {
|
||
const preview = document.getElementById('editPhotoPreview');
|
||
preview.innerHTML = '';
|
||
if (!photos.length) return;
|
||
photos.forEach((p) => {
|
||
const isMain = p.photo_path === mainPath;
|
||
const div = document.createElement('div');
|
||
div.className = 'file-preview-item';
|
||
div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem';
|
||
div.dataset.photoId = p.id;
|
||
const applyStyle = isMain
|
||
? 'background:#16a34a;border:none;color:#fff;border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:default;white-space:nowrap'
|
||
: 'background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:pointer;white-space:nowrap';
|
||
div.innerHTML = `<img src="${thumbSrc(p.photo_path)}" style="width:48px;height:48px;object-fit:cover;border-radius:4px"> <span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(p.photo_path.split('/').pop())}</span> <button type="button" class="apply-photo-btn" style="${applyStyle}" title="${isMain ? 'Главное фото записи' : 'Сделать главным фото записи'}" ${isMain ? 'disabled' : ''}>${isMain ? 'Применено ✓' : 'Применить'}</button> <button type="button" class="delete-entry-photo" style="background:none;border:none;color:#ef4444;cursor:pointer;font-size:1.1rem;line-height:1" title="Удалить фото">✕</button>`;
|
||
preview.appendChild(div);
|
||
const thumb = div.querySelector('img');
|
||
const showMissing = () => {
|
||
const ph = document.createElement('span');
|
||
ph.textContent = 'нет файла';
|
||
ph.style.cssText = 'width:48px;height:48px;display:flex;align-items:center;justify-content:center;background:var(--bg);border:1px dashed var(--border);border-radius:4px;font-size:.6rem;color:var(--muted);text-align:center;line-height:1.1;flex:0 0 auto';
|
||
thumb.replaceWith(ph);
|
||
};
|
||
thumb.addEventListener('error', showMissing);
|
||
if (thumb.complete && thumb.naturalWidth === 0) showMissing();
|
||
div.querySelector('.delete-entry-photo').addEventListener('click', async () => {
|
||
if (!confirm('Удалить это фото?')) return;
|
||
const res = await fetch(`${API}/api/entries/${editId}/photos/${p.id}`, { method: 'DELETE', headers: hdr() });
|
||
if (res.ok) {
|
||
div.remove();
|
||
showToast('Фото удалено');
|
||
refreshEntryCard(editId);
|
||
} else {
|
||
alert('Ошибка удаления');
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
async function applyMainPhoto(btn) {
|
||
const div = btn.closest('.file-preview-item');
|
||
const photoId = div?.dataset.photoId;
|
||
if (!photoId) return;
|
||
btn.disabled = true;
|
||
const res = await fetch(`${API}/api/entries/${editId}/photos/${photoId}/main`, { method: 'PUT', headers: hdr() });
|
||
if (!res.ok) {
|
||
btn.disabled = false;
|
||
const err = await res.json().catch(() => ({}));
|
||
alert(err.error || 'Ошибка');
|
||
return;
|
||
}
|
||
document.querySelectorAll('#editPhotoPreview .apply-photo-btn').forEach(b => {
|
||
b.disabled = false;
|
||
b.textContent = 'Применить';
|
||
b.title = 'Сделать главным фото записи';
|
||
b.style.background = 'var(--card)';
|
||
b.style.color = 'var(--text)';
|
||
});
|
||
btn.disabled = true;
|
||
btn.textContent = 'Применено ✓';
|
||
btn.title = 'Главное фото записи';
|
||
btn.style.background = '#16a34a';
|
||
btn.style.color = '#fff';
|
||
showToast('Главное фото обновлено');
|
||
refreshEntryCard(editId);
|
||
}
|
||
|
||
function closeEdit() {
|
||
document.getElementById('editModal').classList.remove('open');
|
||
document.getElementById('editFiles').value = '';
|
||
document.getElementById('editFilesPreview').innerHTML = '';
|
||
document.getElementById('editPhoto').value = '';
|
||
document.getElementById('editPhotoPreview').innerHTML = '';
|
||
document.getElementById('editAiStatus').style.display = 'none';
|
||
editId = null;
|
||
editDeletePhoto = false;
|
||
}
|
||
|
||
let enhanceEntryId = null;
|
||
let enhanceSourceImg = null;
|
||
let enhanceTimer = null;
|
||
let enhanceSaving = false;
|
||
let enhanceEngine = 'auto';
|
||
let enhanceEngineLoaded = false;
|
||
let photoAiEnabled = false;
|
||
let photoAiFaceMode = 'off';
|
||
let photoAiFaceModel = 'gfpgan';
|
||
let photoAiDevice = '';
|
||
let photoAiPollTimer = null;
|
||
let enhanceAiResultPath = null;
|
||
let enhanceAiJobId = null;
|
||
let enhanceClipPos = 50;
|
||
|
||
function setEnhanceClip(p) {
|
||
enhanceClipPos = Math.min(100, Math.max(0, p));
|
||
document.getElementById('enhanceTop').style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`;
|
||
document.getElementById('enhanceDivider').style.left = enhanceClipPos + '%';
|
||
}
|
||
|
||
function showEnhanceResult(show) {
|
||
document.getElementById('enhanceTop').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) {
|
||
const el = document.getElementById('enhanceLoading');
|
||
if (!el) return;
|
||
el.style.display = '';
|
||
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 enhancePanX = 0;
|
||
let enhancePanY = 0;
|
||
|
||
function applyEnhanceTransform() {
|
||
const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`;
|
||
document.getElementById('enhanceStage').style.transform = t;
|
||
document.getElementById('enhanceInner').style.transform = t;
|
||
const area = document.getElementById('enhanceCompare');
|
||
area.classList.toggle('zoomed', enhanceZoom > 1);
|
||
if (enhanceZoom <= 1) area.classList.remove('panning');
|
||
}
|
||
|
||
function clampEnhancePan() {
|
||
const rect = document.getElementById('enhanceCompare').getBoundingClientRect();
|
||
const minX = rect.width * (1 - enhanceZoom);
|
||
const minY = rect.height * (1 - enhanceZoom);
|
||
enhancePanX = Math.min(0, Math.max(minX, enhancePanX));
|
||
enhancePanY = Math.min(0, Math.max(minY, enhancePanY));
|
||
}
|
||
|
||
function resetEnhanceZoom() {
|
||
enhanceZoom = 1;
|
||
enhancePanX = 0;
|
||
enhancePanY = 0;
|
||
applyEnhanceTransform();
|
||
}
|
||
|
||
(function initEnhanceDrag() {
|
||
const area = document.getElementById('enhanceCompare');
|
||
let dragging = false;
|
||
let dividerDrag = false;
|
||
let lastX = 0;
|
||
let lastY = 0;
|
||
const move = ev => {
|
||
const rect = area.getBoundingClientRect();
|
||
setEnhanceClip(((ev.clientX - rect.left) / rect.width) * 100);
|
||
};
|
||
area.addEventListener('pointerdown', ev => {
|
||
dividerDrag = !!ev.target.closest('#enhanceDivider');
|
||
dragging = true;
|
||
lastX = ev.clientX;
|
||
lastY = ev.clientY;
|
||
area.setPointerCapture(ev.pointerId);
|
||
if (!dividerDrag && enhanceZoom === 1) move(ev);
|
||
});
|
||
area.addEventListener('pointermove', ev => {
|
||
if (!dragging) return;
|
||
if (dividerDrag || enhanceZoom === 1) {
|
||
move(ev);
|
||
} else {
|
||
area.classList.add('panning');
|
||
enhancePanX += ev.clientX - lastX;
|
||
enhancePanY += ev.clientY - lastY;
|
||
lastX = ev.clientX;
|
||
lastY = ev.clientY;
|
||
clampEnhancePan();
|
||
applyEnhanceTransform();
|
||
}
|
||
});
|
||
const end = () => {
|
||
dragging = false;
|
||
area.classList.remove('panning');
|
||
};
|
||
area.addEventListener('pointerup', end);
|
||
area.addEventListener('pointercancel', end);
|
||
area.addEventListener('wheel', ev => {
|
||
ev.preventDefault();
|
||
const rect = area.getBoundingClientRect();
|
||
const cx = ev.clientX - rect.left;
|
||
const cy = ev.clientY - rect.top;
|
||
const prev = enhanceZoom;
|
||
const next = Math.min(5, Math.max(1, enhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15)));
|
||
if (next === prev) return;
|
||
enhanceZoom = next;
|
||
enhancePanX = cx - (cx - enhancePanX) * (next / prev);
|
||
enhancePanY = cy - (cy - enhancePanY) * (next / prev);
|
||
clampEnhancePan();
|
||
applyEnhanceTransform();
|
||
}, { passive: false });
|
||
area.addEventListener('dblclick', resetEnhanceZoom);
|
||
})();
|
||
|
||
const PHOTO_AI_MODES = {
|
||
x2: { model: 'x2plus', face: 'off', face_model: null, title: 'Универсально (x2)' },
|
||
x4: { model: 'general-x4v3', face: 'off', face_model: null, title: 'Быстро (x4)' },
|
||
faces: { model: 'x2plus', face: 'face', face_model: null, title: 'Лица (восстановление)' },
|
||
facesbg: { model: 'x2plus', face: 'all', face_model: null, title: 'Лица + фон' },
|
||
};
|
||
|
||
function photoAiMode() {
|
||
const sel = document.getElementById('enhanceAiMode');
|
||
const key = sel && PHOTO_AI_MODES[sel.value] ? sel.value : 'x2';
|
||
const m = { ...PHOTO_AI_MODES[key] };
|
||
m.face_model = m.face === 'off' ? null : photoAiFaceModel;
|
||
return m;
|
||
}
|
||
|
||
function defaultPhotoAiModeKey() {
|
||
if (photoAiFaceMode === 'all') return 'facesbg';
|
||
if (photoAiFaceMode === 'face') return 'faces';
|
||
return 'x2';
|
||
}
|
||
|
||
function updateAiHint() {
|
||
const hint = document.getElementById('enhanceAiHint');
|
||
if (!hint) return;
|
||
const cpu = photoAiDevice.startsWith('cpu');
|
||
hint.textContent = cpu ? 'Фото-ИИ считает на CPU — лицевые режимы могут занять несколько минут' : '';
|
||
hint.style.display = photoAiEnabled && cpu ? '' : 'none';
|
||
}
|
||
|
||
async function loadPhotoAiDevice() {
|
||
if (!isAdmin()) return;
|
||
try {
|
||
const r = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() });
|
||
if (!r.ok) return;
|
||
const h = await r.json();
|
||
if (h && h.device) photoAiDevice = String(h.device);
|
||
updateAiHint();
|
||
} catch (e) {}
|
||
}
|
||
|
||
async function loadEnhanceEngine() {
|
||
if (enhanceEngineLoaded) return;
|
||
enhanceEngineLoaded = true;
|
||
try {
|
||
const r = await fetch(`${API}/api/public-settings`);
|
||
const f = await r.json();
|
||
if (['auto', 'server', 'client'].includes(f.photo_enhance_engine)) enhanceEngine = f.photo_enhance_engine;
|
||
photoAiEnabled = f.photo_ai_enabled === 'true';
|
||
if (['off', 'face', 'all'].includes(f.photo_ai_face_mode)) photoAiFaceMode = f.photo_ai_face_mode;
|
||
if (['gfpgan', 'codeformer'].includes(f.photo_ai_face_model)) photoAiFaceModel = f.photo_ai_face_model;
|
||
const sel = document.getElementById('enhanceAiMode');
|
||
if (sel) sel.value = defaultPhotoAiModeKey();
|
||
loadPhotoAiDevice();
|
||
} catch (e) {}
|
||
}
|
||
|
||
async function runPhotoAi() {
|
||
if (!enhanceEntryId || enhanceSaving) return;
|
||
const entryId = enhanceEntryId;
|
||
const mode = photoAiMode();
|
||
const faceNote = mode.face === 'off'
|
||
? 'Может занять до минуты на CPU.'
|
||
: `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`;
|
||
if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return;
|
||
enhanceSaving = true;
|
||
const btn = document.getElementById('enhanceAiBtn');
|
||
if (btn) btn.disabled = true;
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }),
|
||
});
|
||
if (!res.ok) {
|
||
const err = await res.json().catch(() => ({}));
|
||
throw new Error(err.error || 'Ошибка запуска ИИ');
|
||
}
|
||
const { jobId } = await res.json();
|
||
enhanceAiJobId = jobId;
|
||
showEnhanceResult(false);
|
||
setEnhanceLoadingProgress(0, mode.face === 'off'
|
||
? 'ИИ обрабатывает фото...'
|
||
: 'ИИ обрабатывает фото и восстанавливает лица...');
|
||
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 (doneHandled) return;
|
||
if (s.status === 'done') {
|
||
doneHandled = true;
|
||
clearInterval(photoAiPollTimer);
|
||
setEnhanceLoadingProgress(100, 'Загрузка результата...');
|
||
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;
|
||
const aiImg = new Image();
|
||
aiImg.onload = () => {
|
||
enhanceSourceImg = aiImg;
|
||
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
|
||
document.getElementById('enhance' + k).value = 100;
|
||
document.getElementById('enhance' + k + 'Val').textContent = '100%';
|
||
});
|
||
document.getElementById('enhanceSharp').value = 0;
|
||
document.getElementById('enhanceSharpVal').textContent = '0%';
|
||
document.getElementById('enhanceDenoise').value = 0;
|
||
document.getElementById('enhanceDenoiseVal').textContent = '0%';
|
||
renderEnhancePreview();
|
||
flashEnhanceResult();
|
||
};
|
||
aiImg.onerror = () => { showEnhanceResult(true); showToast('Не удалось загрузить результат ИИ'); };
|
||
aiImg.src = `${API}${result.photo_path}`;
|
||
} catch (e) {
|
||
showEnhanceResult(true);
|
||
alert(e.message);
|
||
} finally {
|
||
enhanceSaving = false;
|
||
if (btn) btn.disabled = false;
|
||
setBtnLabel(btn, 'ИИ');
|
||
}
|
||
}
|
||
|
||
async function restoreOriginal() {
|
||
if (!enhanceEntryId || enhanceSaving) return;
|
||
if (!confirm('Вернуть исходную фотографию? Текущая улучшенная версия будет удалена.')) return;
|
||
enhanceSaving = true;
|
||
const btn = document.getElementById('enhanceRestoreBtn');
|
||
btn.disabled = true;
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/restore-original`, { method: 'POST', headers: hdr() });
|
||
if (!res.ok) {
|
||
const err = await res.json().catch(() => ({}));
|
||
throw new Error(err.error || 'Ошибка восстановления');
|
||
}
|
||
const savedId = enhanceEntryId;
|
||
showToast('Оригинал возвращён');
|
||
closeEnhance();
|
||
refreshEntryCard(savedId);
|
||
} catch (e) {
|
||
alert(e.message);
|
||
} finally {
|
||
enhanceSaving = false;
|
||
btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
function openEnhance(id) {
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (!e) return;
|
||
const mp = mainPhotoPath(e);
|
||
if (!mp) { showToast('У записи нет фото'); return; }
|
||
enhanceEntryId = id;
|
||
enhanceSourceImg = null;
|
||
enhanceAiResultPath = null;
|
||
enhanceAiJobId = null;
|
||
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
|
||
const el = document.getElementById('enhance' + k);
|
||
el.value = 100;
|
||
document.getElementById('enhance' + k + 'Val').textContent = '100%';
|
||
});
|
||
const sharp = document.getElementById('enhanceSharp');
|
||
sharp.value = 0;
|
||
document.getElementById('enhanceSharpVal').textContent = '0%';
|
||
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;
|
||
document.getElementById('enhanceAiMode').style.display = show;
|
||
updateAiHint();
|
||
});
|
||
const canvas = document.getElementById('enhanceCanvas');
|
||
setEnhanceClip(50);
|
||
resetEnhanceZoom();
|
||
showEnhanceResult(false);
|
||
setEnhanceLoadingProgress(0, 'Загрузка...');
|
||
renderIcons();
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
if (enhanceAiResultPath) return;
|
||
enhanceSourceImg = img;
|
||
renderEnhancePreview();
|
||
};
|
||
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}`;
|
||
document.getElementById('enhanceModal').classList.add('open');
|
||
}
|
||
|
||
function isDefaultEnhanceParams() {
|
||
const p = enhanceParams();
|
||
return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0;
|
||
}
|
||
|
||
async function applyAiResult(signal) {
|
||
if (!enhanceAiJobId || !enhanceEntryId) return false;
|
||
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/apply`, {
|
||
method: 'POST',
|
||
headers: hdr(),
|
||
signal,
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата');
|
||
enhanceAiResultPath = null;
|
||
enhanceAiJobId = null;
|
||
return true;
|
||
}
|
||
|
||
function cleanupAiPreview() {
|
||
if (!enhanceEntryId) return;
|
||
if (enhanceAiJobId) {
|
||
fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/reject`, {
|
||
method: 'POST',
|
||
headers: hdr(),
|
||
}).catch(() => {});
|
||
} else if (enhanceAiResultPath) {
|
||
fetch(`${API}/api/entries/${enhanceEntryId}/photo/enhance-ai/preview`, {
|
||
method: 'DELETE',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ path: enhanceAiResultPath }),
|
||
}).catch(() => {});
|
||
}
|
||
enhanceAiResultPath = null;
|
||
enhanceAiJobId = null;
|
||
}
|
||
|
||
function closeEnhance() {
|
||
cleanupAiPreview();
|
||
document.getElementById('enhanceModal').classList.remove('open');
|
||
document.getElementById('photoHistoryModal').classList.remove('open');
|
||
enhanceEntryId = null;
|
||
enhanceSourceImg = null;
|
||
enhanceAiResultPath = null;
|
||
const loadingEl = document.getElementById('enhanceLoading');
|
||
if (loadingEl) loadingEl.style.display = 'none';
|
||
}
|
||
|
||
let cpuEnhanceEntryId = null;
|
||
let cpuEnhanceSaving = false;
|
||
let cpuEnhanceAiJobId = null;
|
||
let cpuEnhanceAiResultPath = null;
|
||
let cpuEnhancePreviewUrl = '';
|
||
let cpuEnhanceParamsTouched = false;
|
||
let cpuEnhanceActiveKey = '';
|
||
let cpuEnhanceDevice = { device: '', name: '', ready: false };
|
||
let cpuEnhanceZoom = 1;
|
||
let cpuEnhancePanX = 0;
|
||
let cpuEnhancePanY = 0;
|
||
let cpuEnhanceView = 'split';
|
||
let cpuEnhanceBusy = false;
|
||
let cpuEnhanceReturnFocus = null;
|
||
|
||
const CPU_ENHANCE_SLIDERS = ['Quality', 'Clarity', 'Denoise', 'Sharp', 'Brightness', 'Contrast', 'Saturate', 'Warmth'];
|
||
const CPU_ENHANCE_DEFAULTS = { Quality: 92, Clarity: 40, Denoise: 0, Sharp: 30, Brightness: 100, Contrast: 100, Saturate: 100, Warmth: 0 };
|
||
const CPU_ENHANCE_PREVIEW_MAX_PX = 1400;
|
||
|
||
function cpuEnhanceSliderLabel(k) {
|
||
const el = document.getElementById('cpuEnhance' + k);
|
||
if (!el) return '';
|
||
const v = parseInt(el.value, 10) || 0;
|
||
if (k === 'Warmth') return (v > 0 ? '+' : '') + v;
|
||
if (k === 'Quality') return v + '%';
|
||
return String(v);
|
||
}
|
||
|
||
function cpuEnhanceSyncSlider(k) {
|
||
const el = document.getElementById('cpuEnhance' + k);
|
||
if (!el) return;
|
||
const text = cpuEnhanceSliderLabel(k);
|
||
const out = document.getElementById('cpuEnhance' + k + 'Val');
|
||
if (out) out.textContent = text;
|
||
el.setAttribute('aria-valuetext', text);
|
||
const field = el.closest('.settings-field');
|
||
if (field) field.classList.toggle('is-changed', parseInt(el.value, 10) !== CPU_ENHANCE_DEFAULTS[k]);
|
||
}
|
||
|
||
function cpuEnhanceHasResult() {
|
||
const el = document.getElementById('cpuEnhanceResult');
|
||
return !!(el && el.getAttribute('src'));
|
||
}
|
||
|
||
function cpuEnhanceSetResultSrc(src) {
|
||
const el = document.getElementById('cpuEnhanceResult');
|
||
const empty = document.getElementById('cpuEnhanceEmpty');
|
||
if (el) {
|
||
if (src) el.src = src;
|
||
else el.removeAttribute('src');
|
||
}
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (area) area.classList.toggle('no-result', !src);
|
||
if (empty) empty.hidden = !!src;
|
||
if (!src && cpuEnhanceView !== 'orig') cpuEnhanceSetView('split');
|
||
}
|
||
|
||
function cpuEnhanceSetError(msg) {
|
||
const box = document.getElementById('cpuEnhanceError');
|
||
const text = document.getElementById('cpuEnhanceErrorText');
|
||
if (text) text.textContent = msg || '';
|
||
if (box) box.hidden = !msg;
|
||
}
|
||
|
||
function cpuEnhanceClearError() {
|
||
cpuEnhanceSetError('');
|
||
}
|
||
|
||
function cpuEnhanceFocusables() {
|
||
const modal = document.getElementById('cpuEnhanceModal');
|
||
if (!modal) return [];
|
||
return [...modal.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')]
|
||
.filter(el => el.offsetParent !== null || el.id === 'cpuEnhanceCompare');
|
||
}
|
||
|
||
function cpuEnhanceReadParams() {
|
||
const get = id => document.getElementById('cpuEnhance' + id);
|
||
const num = id => parseInt(get(id).value, 10) || 0;
|
||
const mode = get('Mode').value;
|
||
const preset = mode === 'cpu' ? 'quality' : 'auto';
|
||
const params = {
|
||
preset,
|
||
scale: parseInt(get('Scale').value, 10) || 1,
|
||
quality: num('Quality'),
|
||
clarity: num('Clarity'),
|
||
denoise: num('Denoise'),
|
||
sharp: num('Sharp'),
|
||
brightness: num('Brightness'),
|
||
contrast: num('Contrast'),
|
||
saturate: num('Saturate'),
|
||
warmth: num('Warmth'),
|
||
};
|
||
return params;
|
||
}
|
||
|
||
async function cpuEnhanceProbeDevice() {
|
||
cpuEnhanceDevice = { device: '', name: '', ready: false };
|
||
try {
|
||
const res = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() });
|
||
if (!res.ok) throw new Error('health ' + res.status);
|
||
const h = await res.json();
|
||
const dev = String(h && h.device ? h.device : '');
|
||
if (dev.startsWith('cuda')) cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'GPU'), ready: true, gpu: true };
|
||
else if (dev === 'mps') cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'Apple GPU'), ready: true, gpu: true };
|
||
else cpuEnhanceDevice = { device: dev || 'cpu', name: String((h && h.device_name) || 'CPU'), ready: false, gpu: false };
|
||
} catch (e) {
|
||
cpuEnhanceDevice = { device: 'cpu', name: 'CPU (фото-ИИ недоступно)', ready: false, gpu: false };
|
||
}
|
||
cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto');
|
||
return cpuEnhanceDevice;
|
||
}
|
||
|
||
let cpuEnhanceBaseImg = null;
|
||
let cpuEnhanceBaseKind = 'orig';
|
||
|
||
function cpuEnhanceNum(id) {
|
||
const el = document.getElementById('cpuEnhance' + id);
|
||
return el ? parseInt(el.value, 10) || 0 : 0;
|
||
}
|
||
|
||
function cpuEnhanceWarmthFilter(v) {
|
||
if (!v) return '';
|
||
const t = Math.max(-100, Math.min(100, v)) / 100;
|
||
const sep = 'sepia(' + Math.round(Math.abs(t) * 0.7) + ')';
|
||
return t > 0 ? 'sepia(' + Math.round(t * 0.5) + ') hue-rotate(' + Math.round(-8 * t) + 'deg) saturate(' + (1 + t * 0.25) + ')' : sep + ' hue-rotate(' + Math.round(8 * Math.abs(t)) + 'deg) saturate(1.1)';
|
||
}
|
||
|
||
function cpuEnhanceUnsharpPass(ctx, w, h, amount) {
|
||
if (amount <= 0) return;
|
||
const img = ctx.getImageData(0, 0, w, h);
|
||
const src = img.data;
|
||
const out = new Uint8ClampedArray(src);
|
||
const row = w * 4;
|
||
const a = Math.max(0, Math.min(1, (amount / 100) * 0.9));
|
||
for (let y = 1; y < h - 1; y++) {
|
||
for (let x = 1; x < w - 1; x++) {
|
||
const i = y * row + x * 4;
|
||
for (let ch = 0; ch < 3; ch++) {
|
||
const c = src[i + ch];
|
||
const blur = (src[i - 4 + ch] + src[i + 4 + ch] + src[i - row + ch] + src[i + row + ch] + 2 * c) / 6;
|
||
out[i + ch] = c + (c - blur) * a * 2;
|
||
}
|
||
}
|
||
}
|
||
ctx.putImageData(new ImageData(out, w, h), 0, 0);
|
||
}
|
||
|
||
let cpuEnhanceDrawRaf = 0;
|
||
|
||
function cpuEnhanceDrawLocal() {
|
||
if (cpuEnhanceDrawRaf) return;
|
||
cpuEnhanceDrawRaf = requestAnimationFrame(() => {
|
||
cpuEnhanceDrawRaf = 0;
|
||
cpuEnhanceDrawLocalNow();
|
||
});
|
||
}
|
||
|
||
function cpuEnhanceDrawLocalNow() {
|
||
const result = document.getElementById('cpuEnhanceResult');
|
||
if (!result || !cpuEnhanceBaseImg) return;
|
||
const img = cpuEnhanceBaseImg;
|
||
const scale = Math.min(1, CPU_ENHANCE_PREVIEW_MAX_PX / (img.naturalWidth || 1));
|
||
const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale));
|
||
const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale));
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = w;
|
||
canvas.height = h;
|
||
const ctx = canvas.getContext('2d');
|
||
|
||
const brightness = cpuEnhanceNum('Brightness');
|
||
const contrast = cpuEnhanceNum('Contrast');
|
||
const saturate = cpuEnhanceNum('Saturate');
|
||
const denoise = cpuEnhanceNum('Denoise');
|
||
const sharp = cpuEnhanceNum('Sharp');
|
||
const clarity = cpuEnhanceNum('Clarity');
|
||
const warmth = cpuEnhanceNum('Warmth');
|
||
|
||
const filters = [];
|
||
if (brightness !== 100) filters.push('brightness(' + (brightness / 100) + ')');
|
||
if (contrast !== 100) filters.push('contrast(' + (contrast / 100) + ')');
|
||
if (saturate !== 100) filters.push('saturate(' + (saturate / 100) + ')');
|
||
const wf = cpuEnhanceWarmthFilter(warmth);
|
||
if (wf) filters.push(wf);
|
||
ctx.filter = filters.join(' ') || 'none';
|
||
ctx.drawImage(img, 0, 0, w, h);
|
||
ctx.filter = 'none';
|
||
|
||
if (denoise > 0) {
|
||
medianFilterPass(ctx, w, h);
|
||
if (denoise > 70) medianFilterPass(ctx, w, h);
|
||
}
|
||
if (clarity > 0) cpuEnhanceUnsharpPass(ctx, w, h, clarity);
|
||
if (sharp > 0) sharpenPass(ctx, w, h, sharp);
|
||
|
||
const url = canvas.toDataURL('image/jpeg', Math.min(1, cpuEnhanceNum('Quality') / 100));
|
||
cpuEnhanceSetResultSrc(url);
|
||
}
|
||
|
||
function cpuEnhanceSetBaseImg(path) {
|
||
cpuEnhanceBaseImg = null;
|
||
cpuEnhanceBaseKind = 'orig';
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
if (String(cpuEnhanceBaseKind) !== 'orig') return;
|
||
cpuEnhanceBaseImg = img;
|
||
cpuEnhanceDrawLocal();
|
||
};
|
||
img.onerror = () => { cpuEnhanceBaseImg = null; };
|
||
img.src = `${API}${path}`;
|
||
}
|
||
|
||
function cpuEnhanceAdoptPreviewAsBase() {
|
||
if (!cpuEnhancePreviewUrl) return;
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
cpuEnhanceBaseImg = img;
|
||
cpuEnhanceBaseKind = 'preview';
|
||
};
|
||
img.onerror = () => {};
|
||
img.src = cpuEnhancePreviewUrl;
|
||
}
|
||
|
||
function cpuEnhanceLoadAiBase() {
|
||
if (!cpuEnhanceAiResultPath) return;
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
cpuEnhanceBaseImg = img;
|
||
cpuEnhanceBaseKind = 'result';
|
||
};
|
||
img.onerror = () => {};
|
||
img.src = `${API}${cpuEnhanceAiResultPath}`;
|
||
}
|
||
|
||
function cpuEnhanceSetBase(src, kind) {
|
||
if (!src) return;
|
||
cpuEnhanceBaseImg = src;
|
||
cpuEnhanceBaseKind = kind === 'result' ? 'result' : 'orig';
|
||
cpuEnhanceDrawLocal();
|
||
}
|
||
|
||
function cpuEnhanceParamsKey() {
|
||
return JSON.stringify(cpuEnhanceReadParams());
|
||
}
|
||
|
||
function cpuEnhanceIsDirty() {
|
||
return cpuEnhanceActiveKey !== cpuEnhanceParamsKey();
|
||
}
|
||
|
||
function cpuEnhanceSyncPending() {
|
||
const dirty = cpuEnhanceIsDirty();
|
||
const ready = !!cpuEnhanceActiveKey;
|
||
const mode = (document.getElementById('cpuEnhanceMode') || {}).value || 'auto';
|
||
const status = document.getElementById('cpuEnhanceStatus');
|
||
const text = document.getElementById('cpuEnhanceStatusText');
|
||
if (status) {
|
||
status.classList.toggle('is-dirty', dirty && ready);
|
||
status.classList.toggle('is-ok', ready && !dirty);
|
||
status.classList.toggle('is-idle', !ready);
|
||
}
|
||
if (text) {
|
||
if (!ready) text.textContent = 'Результата пока нет — настройте параметры и нажмите «Активировать»';
|
||
else if (dirty) text.textContent = 'Параметры изменены — результат устарел, нажмите «Активировать»';
|
||
else text.textContent = 'Результат готов — можно сохранять';
|
||
}
|
||
const applyBtn = document.getElementById('cpuEnhanceApplyBtn');
|
||
if (applyBtn) {
|
||
applyBtn.disabled = cpuEnhanceBusy || !ready || dirty;
|
||
applyBtn.title = !ready
|
||
? 'Сначала получите результат — «Активировать»'
|
||
: dirty ? 'Параметры изменены: обновите результат через «Активировать»' : 'Сохранить результат к записи';
|
||
}
|
||
const activateBtn = document.getElementById('cpuEnhanceActivateBtn');
|
||
if (activateBtn) {
|
||
activateBtn.disabled = cpuEnhanceBusy;
|
||
activateBtn.classList.toggle('attention', dirty && ready && !cpuEnhanceBusy);
|
||
}
|
||
const previewBtn = document.getElementById('cpuEnhancePreviewBtn');
|
||
if (previewBtn) {
|
||
const cpuOnly = mode === 'cpu';
|
||
previewBtn.disabled = cpuEnhanceBusy || !cpuOnly;
|
||
previewBtn.title = cpuOnly
|
||
? 'Серверный предпросмотр текущих параметров'
|
||
: 'Превью доступно только в режиме CPU — в режиме GPU жмите «Активировать»';
|
||
}
|
||
const autoBtn = document.getElementById('cpuEnhanceAutoBtn');
|
||
if (autoBtn) autoBtn.disabled = cpuEnhanceBusy;
|
||
const resetBtn = document.getElementById('cpuEnhanceResetBtn');
|
||
if (resetBtn) resetBtn.disabled = cpuEnhanceBusy;
|
||
const applyCpuBtn = document.getElementById('cpuEnhanceApplyCpuBtn');
|
||
if (applyCpuBtn) applyCpuBtn.disabled = cpuEnhanceBusy;
|
||
}
|
||
|
||
function cpuEnhanceMarkApplied() {
|
||
cpuEnhanceActiveKey = cpuEnhanceParamsKey();
|
||
cpuEnhanceSyncPending();
|
||
}
|
||
|
||
function cpuEnhanceMarkCleared() {
|
||
cpuEnhanceActiveKey = '';
|
||
cpuEnhanceSyncPending();
|
||
}
|
||
|
||
function cpuEnhanceApplySuggested(s) {
|
||
const set = (id, v) => {
|
||
const el = document.getElementById('cpuEnhance' + id);
|
||
if (!el) return;
|
||
el.value = Math.max(parseInt(el.min, 10), Math.min(parseInt(el.max, 10), Math.round(v)));
|
||
cpuEnhanceSyncSlider(id);
|
||
};
|
||
if (!s) return;
|
||
if (s.clarity !== undefined) set('Clarity', s.clarity);
|
||
if (s.denoise !== undefined) set('Denoise', s.denoise);
|
||
if (s.sharp !== undefined) set('Sharp', s.sharp);
|
||
if (s.brightness !== undefined) set('Brightness', s.brightness);
|
||
if (s.contrast !== undefined) set('Contrast', s.contrast);
|
||
if (s.saturate !== undefined) set('Saturate', s.saturate);
|
||
}
|
||
|
||
function cpuEnhanceResetSliders(resetMode) {
|
||
CPU_ENHANCE_SLIDERS.forEach(k => {
|
||
const el = document.getElementById('cpuEnhance' + k);
|
||
if (!el) return;
|
||
el.value = CPU_ENHANCE_DEFAULTS[k];
|
||
cpuEnhanceSyncSlider(k);
|
||
});
|
||
const scale = document.getElementById('cpuEnhanceScale');
|
||
if (scale) scale.value = '1';
|
||
if (resetMode) cpuEnhanceSetMode('auto');
|
||
}
|
||
|
||
const CPU_ENHANCE_INFO_FMT = {
|
||
'Среднее': v => Math.round(v) + ' / 255',
|
||
'Контраст': v => Math.round(v),
|
||
'Резкость': v => Number(v).toFixed(1),
|
||
};
|
||
|
||
function cpuEnhanceInfoValue(key, value) {
|
||
const fmt = CPU_ENHANCE_INFO_FMT[key];
|
||
const n = Number(value);
|
||
if (fmt && Number.isFinite(n)) return fmt(n);
|
||
return String(value);
|
||
}
|
||
|
||
function cpuEnhanceSetInfo(analyze, extra) {
|
||
const box = document.getElementById('cpuEnhanceInfo');
|
||
if (!box) return;
|
||
const items = [];
|
||
if (analyze) {
|
||
items.push(['Размер', `${analyze.width}×${analyze.height}`]);
|
||
items.push(['Среднее', analyze.mean]);
|
||
items.push(['Контраст', analyze.stdev]);
|
||
items.push(['Резкость', analyze.sharpness]);
|
||
}
|
||
if (extra) items.push(...extra);
|
||
box.innerHTML = items.map(([k, v]) => {
|
||
const wide = String(v).length > 22 ? ' is-wide' : '';
|
||
return `<span class="cpu-enhance-chip${wide}">${esc(k)}: <b>${esc(cpuEnhanceInfoValue(k, v))}</b></span>`;
|
||
}).join('');
|
||
}
|
||
|
||
function cpuEnhanceSetLoading(on, text, progress) {
|
||
const el = document.getElementById('cpuEnhanceLoading');
|
||
const t = document.getElementById('cpuEnhanceLoadingText');
|
||
const track = document.getElementById('cpuEnhanceProgress');
|
||
const bar = document.getElementById('cpuEnhanceProgressBar');
|
||
const modal = document.getElementById('cpuEnhanceModal');
|
||
if (!el) return;
|
||
el.style.display = on ? '' : 'none';
|
||
if (modal) modal.setAttribute('aria-busy', on ? 'true' : 'false');
|
||
if (t && text) t.textContent = text;
|
||
if (track) track.hidden = !on;
|
||
if (bar) {
|
||
if (!on) {
|
||
bar.classList.remove('indeterminate');
|
||
bar.style.width = '0%';
|
||
} else if (typeof progress === 'number') {
|
||
bar.classList.remove('indeterminate');
|
||
bar.style.width = Math.max(2, Math.min(100, progress)) + '%';
|
||
} else {
|
||
bar.classList.add('indeterminate');
|
||
}
|
||
}
|
||
cpuEnhanceSetBusy(!!on);
|
||
}
|
||
|
||
function cpuEnhanceSetBusy(on) {
|
||
cpuEnhanceBusy = !!on;
|
||
CPU_ENHANCE_SLIDERS.forEach(k => {
|
||
const el = document.getElementById('cpuEnhance' + k);
|
||
if (el) el.disabled = cpuEnhanceBusy;
|
||
});
|
||
const mode = document.getElementById('cpuEnhanceMode');
|
||
const scale = document.getElementById('cpuEnhanceScale');
|
||
if (scale) scale.disabled = cpuEnhanceBusy;
|
||
if (mode) mode.disabled = cpuEnhanceBusy;
|
||
document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => { b.disabled = cpuEnhanceBusy; });
|
||
cpuEnhanceSyncPending();
|
||
}
|
||
|
||
function cpuEnhanceSetClip(pct) {
|
||
const top = document.getElementById('cpuEnhanceTop');
|
||
const divider = document.getElementById('cpuEnhanceDivider');
|
||
if (!top || !divider) return;
|
||
const v = Math.max(0, Math.min(100, pct));
|
||
top.style.clipPath = `inset(0 0 0 ${v}%)`;
|
||
divider.style.left = `${v}%`;
|
||
}
|
||
|
||
function cpuEnhanceSetMode(mode) {
|
||
const m = mode === 'ai' || mode === 'cpu' ? mode : 'auto';
|
||
const sel = document.getElementById('cpuEnhanceMode');
|
||
if (sel) sel.value = m;
|
||
const gpuMode = m === 'ai' || m === 'auto';
|
||
const gpuActive = gpuMode && !!cpuEnhanceDevice.gpu;
|
||
document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => {
|
||
const on = b.dataset.cpuMode === m;
|
||
b.classList.toggle('active', on);
|
||
b.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||
});
|
||
const note = document.getElementById('cpuEnhanceGpuNote');
|
||
if (note) note.hidden = !gpuActive;
|
||
const badge = document.getElementById('cpuEnhanceEngineBadge');
|
||
if (badge) {
|
||
badge.classList.toggle('is-gpu', gpuActive);
|
||
badge.classList.toggle('is-cpu', m === 'cpu');
|
||
badge.classList.toggle('is-warn', !gpuActive && m !== 'cpu');
|
||
if (m === 'cpu') badge.textContent = 'CPU · ' + (cpuEnhanceDevice.name || 'пайплайн');
|
||
else if (gpuActive) badge.textContent = 'GPU · ' + (cpuEnhanceDevice.name || 'photo-ai');
|
||
else if (m === 'ai') badge.textContent = 'GPU недоступен';
|
||
else badge.textContent = 'GPU недоступен → CPU';
|
||
}
|
||
if (gpuActive && cpuEnhanceBaseKind === 'orig' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal();
|
||
cpuEnhanceSyncPending();
|
||
}
|
||
|
||
async function openCpuEnhance(id) {
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (!e) return;
|
||
const mp = mainPhotoPath(e);
|
||
if (!mp) { showToast('У записи нет фото'); return; }
|
||
cpuEnhanceReturnFocus = document.activeElement;
|
||
cpuEnhanceEntryId = id;
|
||
cpuEnhanceSaving = false;
|
||
cpuEnhanceAiJobId = null;
|
||
cpuEnhanceAiResultPath = null;
|
||
cpuEnhanceParamsTouched = false;
|
||
cpuEnhanceActiveKey = '';
|
||
cpuEnhanceSetBusy(false);
|
||
cpuEnhanceResetSliders(true);
|
||
cpuEnhanceSetClip(50);
|
||
cpuEnhanceResetZoom();
|
||
cpuEnhanceSetView('split');
|
||
const orig = document.getElementById('cpuEnhanceOrig');
|
||
if (orig) orig.src = `${API}${mp}`;
|
||
cpuEnhanceClearResult();
|
||
cpuEnhanceSetBaseImg(mp);
|
||
cpuEnhanceSetInfo(null, [['Движок', 'анализ…']]);
|
||
cpuEnhanceClearError();
|
||
const applyLabel = document.getElementById('cpuEnhanceApplyLabel');
|
||
if (applyLabel) applyLabel.textContent = 'Сохранить';
|
||
const applyCpuLabel = document.getElementById('cpuEnhanceApplyCpuLabel');
|
||
if (applyCpuLabel) applyCpuLabel.textContent = 'Только эффекты';
|
||
const restoreBtn = document.getElementById('cpuEnhanceRestoreBtn');
|
||
if (restoreBtn) restoreBtn.style.display = e.photo_original_path ? '' : 'none';
|
||
const context = document.getElementById('cpuEnhanceContext');
|
||
if (context) {
|
||
const parts = [e.student_name, e.group_name].filter(Boolean);
|
||
if (e.module_name) parts.push(e.module_name);
|
||
if (e.created_at) parts.push(fmtFull(e.created_at));
|
||
context.textContent = parts.join(' · ');
|
||
}
|
||
document.getElementById('cpuEnhanceModal').classList.add('open');
|
||
cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto');
|
||
cpuEnhanceSyncPending();
|
||
renderIcons();
|
||
const compare = document.getElementById('cpuEnhanceCompare');
|
||
if (compare) compare.focus({ preventScroll: true });
|
||
cpuEnhanceProbeDevice();
|
||
}
|
||
|
||
function cpuEnhanceClearResult() {
|
||
if (cpuEnhancePreviewUrl) {
|
||
if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl);
|
||
cpuEnhancePreviewUrl = '';
|
||
}
|
||
cpuEnhanceSetResultSrc('');
|
||
cpuEnhanceMarkCleared();
|
||
}
|
||
|
||
async function cpuEnhanceAuto(showToastMsg) {
|
||
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
|
||
cpuEnhanceClearError();
|
||
cpuEnhanceSetLoading(true, 'Анализ фото…');
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-analyze`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({}),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка анализа');
|
||
const kept = cpuEnhanceParamsTouched;
|
||
if (!kept) cpuEnhanceApplySuggested(data.suggested);
|
||
cpuEnhanceSetInfo(data.analyze, [
|
||
['Движок', 'CPU'],
|
||
['ИИ доступен', data.ai_available ? 'да' : 'нет'],
|
||
kept ? ['Авто', 'не применён — есть ручные правки'] : null,
|
||
].filter(Boolean));
|
||
if (showToastMsg) showToast(kept ? 'Авто-параметры рассчитаны, но ручные правки оставлены' : 'Параметры подобраны автоматически');
|
||
cpuEnhanceSyncPending();
|
||
} catch (e) {
|
||
cpuEnhanceSetError(e.message);
|
||
if (showToastMsg) showToast(e.message, true);
|
||
} finally {
|
||
cpuEnhanceSetLoading(false);
|
||
}
|
||
}
|
||
|
||
async function cpuEnhancePreview() {
|
||
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
|
||
const m = document.getElementById('cpuEnhanceMode').value;
|
||
if (m === 'ai' || m === 'auto') {
|
||
showToast('Превью доступно только в режиме CPU');
|
||
return;
|
||
}
|
||
cpuEnhanceClearError();
|
||
cpuEnhanceSetLoading(true, 'Предпросмотр…');
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-preview`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ params: cpuEnhanceReadParams(), width: 720 }),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка предпросмотра');
|
||
const bytes = Uint8Array.from(atob(data.image_base64), c => c.charCodeAt(0));
|
||
if (cpuEnhancePreviewUrl && cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl);
|
||
cpuEnhancePreviewUrl = URL.createObjectURL(new Blob([bytes], { type: 'image/jpeg' }));
|
||
cpuEnhanceSetResultSrc(cpuEnhancePreviewUrl);
|
||
cpuEnhanceAdoptPreviewAsBase();
|
||
if (data.params) cpuEnhanceApplySuggested(data.params);
|
||
cpuEnhanceMarkApplied();
|
||
cpuEnhanceSetInfo(data.analyze, [['Превью', `${Math.round((data.bytes || 0) / 1024)} КБ`]]);
|
||
} catch (e) {
|
||
cpuEnhanceMarkCleared();
|
||
cpuEnhanceSetError(e.message);
|
||
showToast(e.message, true);
|
||
} finally {
|
||
cpuEnhanceSetLoading(false);
|
||
}
|
||
}
|
||
|
||
async function cpuEnhanceRunAi(entryId, mode) {
|
||
cpuEnhanceSetLoading(true, 'Постановка ИИ-задачи…', 12);
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ mode: mode === 'auto' ? 'auto' : 'ai', params: cpuEnhanceReadParams(), face: 'face', face_model: 'gfpgan' }),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось запустить ИИ');
|
||
if (!data.jobId) throw new Error('ИИ-задача не создана');
|
||
cpuEnhanceAiJobId = data.jobId;
|
||
cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]);
|
||
const done = await cpuEnhancePollAi(entryId, data.jobId);
|
||
cpuEnhanceAiResultPath = done.photo_path || '';
|
||
if (cpuEnhanceAiResultPath) {
|
||
cpuEnhanceSetResultSrc(`${API}${cpuEnhanceAiResultPath}`);
|
||
cpuEnhanceLoadAiBase();
|
||
cpuEnhanceSetView('result');
|
||
}
|
||
cpuEnhanceMarkApplied();
|
||
cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]);
|
||
}
|
||
|
||
async function cpuEnhanceRun() {
|
||
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
|
||
const mode = document.getElementById('cpuEnhanceMode').value;
|
||
const entryId = cpuEnhanceEntryId;
|
||
if (mode === 'ai' || mode === 'auto') {
|
||
cpuEnhanceSaving = true;
|
||
cpuEnhanceClearError();
|
||
let fellBack = false;
|
||
try {
|
||
await cpuEnhanceRunAi(entryId, mode);
|
||
} catch (e) {
|
||
if (mode === 'auto') {
|
||
fellBack = true;
|
||
cpuEnhanceFallbackCpu(e.message);
|
||
} else {
|
||
cpuEnhanceMarkCleared();
|
||
cpuEnhanceSetError(e.message);
|
||
showToast(e.message, true);
|
||
}
|
||
} finally {
|
||
cpuEnhanceSaving = false;
|
||
if (!fellBack) cpuEnhanceSetLoading(false);
|
||
}
|
||
return;
|
||
}
|
||
await cpuEnhancePreview();
|
||
}
|
||
|
||
function cpuEnhanceFallbackCpu(reason) {
|
||
cpuEnhanceDevice = { device: 'cpu', name: 'CPU (GPU недоступен)', ready: false, gpu: false };
|
||
cpuEnhanceSetMode('cpu');
|
||
showToast('GPU недоступен, переключаюсь на CPU');
|
||
cpuEnhanceSetInfo(null, [['Причина', reason || 'GPU недоступен'], ['Движок', 'CPU']]);
|
||
cpuEnhanceSaving = false;
|
||
cpuEnhancePreview();
|
||
}
|
||
|
||
async function cpuEnhanceApply() {
|
||
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
|
||
const mode = document.getElementById('cpuEnhanceMode').value;
|
||
if (cpuEnhanceIsDirty()) {
|
||
showToast('Параметры изменены — сначала обновите результат через «Активировать»', true);
|
||
return;
|
||
}
|
||
if (!cpuEnhanceActiveKey) {
|
||
showToast('Сначала нажмите «Активировать», чтобы получить результат', true);
|
||
return;
|
||
}
|
||
cpuEnhanceSaving = true;
|
||
cpuEnhanceClearError();
|
||
let fellBack = false;
|
||
const applyLabel = document.getElementById('cpuEnhanceApplyLabel');
|
||
if (applyLabel) applyLabel.textContent = 'Сохраняю…';
|
||
cpuEnhanceSetBusy(true);
|
||
cpuEnhanceSetLoading(true, 'Сохранение результата…');
|
||
const entryId = cpuEnhanceEntryId;
|
||
try {
|
||
if (cpuEnhanceAiJobId) {
|
||
await cpuEnhanceApplyAi(entryId, cpuEnhanceAiJobId);
|
||
showToast(cpuEnhanceDevice.gpu ? 'ИИ-результат сохранён' : 'Результат сохранён');
|
||
closeCpuEnhance(true);
|
||
refreshEntryCard(entryId);
|
||
return;
|
||
}
|
||
const payload = {
|
||
mode,
|
||
params: cpuEnhanceReadParams(),
|
||
face: mode === 'cpu' ? 'off' : 'face',
|
||
face_model: 'gfpgan',
|
||
};
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify(payload),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка обработки');
|
||
if (data.jobId) {
|
||
cpuEnhanceAiJobId = data.jobId;
|
||
await cpuEnhancePollAi(entryId, data.jobId);
|
||
await cpuEnhanceApplyAi(entryId, data.jobId);
|
||
} else {
|
||
showToast('Фото обработано');
|
||
}
|
||
closeCpuEnhance(true);
|
||
refreshEntryCard(entryId);
|
||
} catch (e) {
|
||
if (mode === 'auto' && /ИИ-обработка фото не настроена|503/i.test(e.message)) {
|
||
cpuEnhanceFallbackCpu(e.message);
|
||
fellBack = true;
|
||
return;
|
||
}
|
||
cpuEnhanceSetError(e.message);
|
||
showToast(e.message, true);
|
||
} finally {
|
||
cpuEnhanceSaving = false;
|
||
if (applyLabel) applyLabel.textContent = 'Сохранить';
|
||
if (!fellBack) {
|
||
cpuEnhanceSetLoading(false);
|
||
cpuEnhanceSetBusy(false);
|
||
}
|
||
}
|
||
}
|
||
|
||
async function cpuEnhanceApplyCpuOnly() {
|
||
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
|
||
const entryId = cpuEnhanceEntryId;
|
||
const label = document.getElementById('cpuEnhanceApplyCpuLabel');
|
||
cpuEnhanceSaving = true;
|
||
cpuEnhanceClearError();
|
||
if (label) label.textContent = 'Сохраняю…';
|
||
cpuEnhanceSetBusy(true);
|
||
cpuEnhanceSetLoading(true, 'Применение эффектов…');
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({
|
||
mode: 'cpu',
|
||
params: { ...cpuEnhanceReadParams(), preset: 'quality' },
|
||
face: 'off',
|
||
face_model: 'gfpgan',
|
||
}),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка обработки');
|
||
showToast('Эффекты применены, ИИ не использовался');
|
||
closeCpuEnhance(true);
|
||
refreshEntryCard(entryId);
|
||
} catch (e) {
|
||
cpuEnhanceSetError(e.message);
|
||
showToast(e.message, true);
|
||
} finally {
|
||
cpuEnhanceSaving = false;
|
||
if (label) label.textContent = 'Только эффекты';
|
||
cpuEnhanceSetLoading(false);
|
||
}
|
||
}
|
||
|
||
function cpuEnhancePollAi(entryId, jobId) {
|
||
return new Promise((resolve, reject) => {
|
||
let done = false;
|
||
const tick = async () => {
|
||
if (done) 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 (done) return;
|
||
if (s.status === 'done') { done = true; clearInterval(t); resolve(s); return; }
|
||
if (s.status === 'error') { done = true; clearInterval(t); reject(new Error(s.error || 'Ошибка ИИ')); return; }
|
||
if (s.status === 'pending') cpuEnhanceSetLoading(true, 'В очереди — ждём свободный воркер', 18);
|
||
else cpuEnhanceSetLoading(true, 'ИИ обрабатывает фото…', 62);
|
||
} catch (e) {
|
||
done = true;
|
||
clearInterval(t);
|
||
reject(e);
|
||
}
|
||
};
|
||
const t = setInterval(tick, 1200);
|
||
tick();
|
||
});
|
||
}
|
||
|
||
async function cpuEnhanceApplyAi(entryId, jobId) {
|
||
cpuEnhanceSetLoading(true, 'Сохранение результата…', 88);
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата');
|
||
cpuEnhanceAiJobId = null;
|
||
cpuEnhanceAiResultPath = null;
|
||
}
|
||
|
||
function closeCpuEnhance(force) {
|
||
if (!force && cpuEnhanceActiveKey && cpuEnhanceIsDirty()) {
|
||
if (!confirm('Параметры изменены, результат не сохранён. Закрыть без сохранения?')) return;
|
||
}
|
||
if (cpuEnhancePreviewUrl) {
|
||
if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl);
|
||
cpuEnhancePreviewUrl = '';
|
||
}
|
||
if (cpuEnhanceAiJobId && cpuEnhanceEntryId) {
|
||
const entryId = cpuEnhanceEntryId;
|
||
const jobId = cpuEnhanceAiJobId;
|
||
cpuEnhanceAiJobId = null;
|
||
fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/reject`, { method: 'POST', headers: hdr() }).catch(() => {});
|
||
}
|
||
cpuEnhanceAiResultPath = null;
|
||
const modal = document.getElementById('cpuEnhanceModal');
|
||
if (modal) modal.classList.remove('open');
|
||
cpuEnhanceEntryId = null;
|
||
cpuEnhanceSaving = false;
|
||
cpuEnhanceSetBusy(false);
|
||
cpuEnhanceClearResult();
|
||
cpuEnhanceResetZoom();
|
||
cpuEnhanceSetView('split');
|
||
cpuEnhanceClearError();
|
||
const restore = cpuEnhanceReturnFocus;
|
||
cpuEnhanceReturnFocus = null;
|
||
if (restore && typeof restore.focus === 'function' && document.contains(restore)) restore.focus({ preventScroll: true });
|
||
}
|
||
|
||
function photoJobThumb(p) {
|
||
if (!p) return '';
|
||
if (p.startsWith('/uploads/.originals/')) return `${API}${p}`;
|
||
return `${API}/uploads/thumb/${p.split('/').pop()}`;
|
||
}
|
||
|
||
const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' };
|
||
const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' };
|
||
|
||
async function loadPhotoHistory() {
|
||
if (!enhanceEntryId) return;
|
||
const list = document.getElementById('photoHistoryList');
|
||
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Загрузка...</div>';
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs`, { headers: hdr() });
|
||
if (!res.ok) throw new Error('Ошибка загрузки истории');
|
||
const rows = await res.json();
|
||
if (!rows.length) {
|
||
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Изменений фотографии пока не было.</div>';
|
||
return;
|
||
}
|
||
list.innerHTML = rows.map(r => {
|
||
const before = r.before_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.before_path))}" alt="было">` : '<span style="color:var(--muted)">—</span>';
|
||
const after = r.after_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.after_path))}" alt="стало">` : '<span style="color:var(--muted)">—</span>';
|
||
const canApply = r.status === 'done' && r.applied === false && r.action === 'ai' && !!r.after_path;
|
||
const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback' && !canApply;
|
||
const err = r.error ? `<div style="color:#ef4444;font-size:.75rem;margin-top:4px">${esc(r.error)}</div>` : '';
|
||
const time = r.finished_at || r.created_at;
|
||
return `<div style="display:flex;gap:10px;align-items:center;border:1px solid var(--border);border-radius:10px;padding:10px">
|
||
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
|
||
${before}
|
||
<span style="font-size:.65rem;color:var(--muted)">было</span>
|
||
</div>
|
||
<div style="color:var(--muted)">→</div>
|
||
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
|
||
${after}
|
||
<span style="font-size:.65rem;color:var(--muted)">стало</span>
|
||
</div>
|
||
<div style="flex:1;min-width:0">
|
||
<div style="font-size:.85rem">${esc(PHOTO_JOB_ACTION_LABELS[r.action] || r.action)}
|
||
<span style="color:var(--muted);font-size:.75rem;margin-left:6px">${esc(PHOTO_JOB_STATUS_LABELS[r.status] || r.status)} · ${esc(fmtFull(time))}</span>
|
||
</div>
|
||
${err}
|
||
</div>
|
||
${canRollback ? `<button type="button" class="btn-primary ghost" style="white-space:nowrap" data-job-rollback="${r.id}">↩ Откатить</button>` : ''}
|
||
${canApply ? `<button type="button" class="btn-primary" style="white-space:nowrap" data-job-apply="${r.id}">✓ Применить</button>` : ''}
|
||
</div>`;
|
||
}).join('');
|
||
} catch (e) {
|
||
list.innerHTML = `<div style="color:#ef4444;font-size:.85rem">${esc(e.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
function openPhotoHistory() {
|
||
document.getElementById('photoHistoryTitle').textContent = `История изменений фотографии — запись #${enhanceEntryId}`;
|
||
document.getElementById('photoHistoryModal').classList.add('open');
|
||
loadPhotoHistory();
|
||
}
|
||
|
||
async function rollbackPhotoJob(jobId) {
|
||
if (!enhanceEntryId || enhanceSaving) return;
|
||
if (!confirm('Откатить фотографию к сохранённой версии? Текущая версия сохранится в истории.')) return;
|
||
enhanceSaving = true;
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${jobId}/rollback`, { method: 'POST', headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка отката');
|
||
showToast('Фотография отката');
|
||
document.getElementById('photoHistoryModal').classList.remove('open');
|
||
const mp = data.photo_path;
|
||
document.getElementById('enhanceOrig').src = `${API}${mp}`;
|
||
showEnhanceResult(false);
|
||
setEnhanceLoadingProgress(0, 'Загрузка...');
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
enhanceSourceImg = img;
|
||
renderEnhancePreview();
|
||
};
|
||
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) {
|
||
alert(e.message);
|
||
} finally {
|
||
enhanceSaving = false;
|
||
}
|
||
}
|
||
|
||
function medianFilterPass(ctx, w, h) {
|
||
const data = ctx.getImageData(0, 0, w, h);
|
||
const src = data.data;
|
||
const out = new Uint8ClampedArray(src);
|
||
const row = w * 4;
|
||
const win = new Array(9);
|
||
for (let y = 1; y < h - 1; y++) {
|
||
for (let x = 1; x < w - 1; x++) {
|
||
const i = y * row + x * 4;
|
||
for (let ch = 0; ch < 3; ch++) {
|
||
win[0] = src[i - row - 4 + ch]; win[1] = src[i - row + ch]; win[2] = src[i - row + 4 + ch];
|
||
win[3] = src[i - 4 + ch]; win[4] = src[i + ch]; win[5] = src[i + 4 + ch];
|
||
win[6] = src[i + row - 4 + ch]; win[7] = src[i + row + ch]; win[8] = src[i + row + 4 + ch];
|
||
win.sort((a, b) => a - b);
|
||
out[i + ch] = win[4];
|
||
}
|
||
}
|
||
}
|
||
data.data.set(out);
|
||
ctx.putImageData(data, 0, 0);
|
||
}
|
||
|
||
function sharpenPass(ctx, w, h, sharp) {
|
||
const data = ctx.getImageData(0, 0, w, h);
|
||
const src = data.data;
|
||
const out = new Uint8ClampedArray(src);
|
||
const row = w * 4;
|
||
const a = (sharp / 100) * 1.5;
|
||
for (let y = 1; y < h - 1; y++) {
|
||
for (let x = 1; x < w - 1; x++) {
|
||
const i = y * row + x * 4;
|
||
for (let ch = 0; ch < 3; ch++) {
|
||
const v = (1 + 4 * a) * src[i + ch]
|
||
- a * src[i - 4 + ch] - a * src[i + 4 + ch]
|
||
- a * src[i - row + ch] - a * src[i + row + ch];
|
||
out[i + ch] = v;
|
||
}
|
||
}
|
||
}
|
||
data.data.set(out);
|
||
ctx.putImageData(data, 0, 0);
|
||
}
|
||
|
||
function drawEnhanced(ctx, img, w, h) {
|
||
const b = document.getElementById('enhanceBrightness').value;
|
||
const c = document.getElementById('enhanceContrast').value;
|
||
const s = document.getElementById('enhanceSaturate').value;
|
||
const dn = parseInt(document.getElementById('enhanceDenoise').value, 10);
|
||
const sp = parseInt(document.getElementById('enhanceSharp').value, 10);
|
||
ctx.filter = `brightness(${b}%) contrast(${c}%) saturate(${s}%)`;
|
||
ctx.drawImage(img, 0, 0, w, h);
|
||
ctx.filter = 'none';
|
||
if (dn > 0) {
|
||
medianFilterPass(ctx, w, h);
|
||
if (dn > 70) medianFilterPass(ctx, w, h);
|
||
}
|
||
if (sp > 0) sharpenPass(ctx, w, h, sp);
|
||
}
|
||
|
||
function renderEnhancePreview() {
|
||
if (!enhanceSourceImg) return;
|
||
const img = enhanceSourceImg;
|
||
const scale = Math.min(1, 1600 / img.naturalWidth);
|
||
const w = Math.max(1, Math.round(img.naturalWidth * scale));
|
||
const h = Math.max(1, Math.round(img.naturalHeight * scale));
|
||
const canvas = document.getElementById('enhanceCanvas');
|
||
canvas.width = w;
|
||
canvas.height = h;
|
||
const ctx = canvas.getContext('2d');
|
||
drawEnhanced(ctx, img, w, h);
|
||
showEnhanceResult(true);
|
||
}
|
||
|
||
function scheduleEnhancePreview() {
|
||
document.getElementById('enhanceBrightnessVal').textContent = document.getElementById('enhanceBrightness').value + '%';
|
||
document.getElementById('enhanceContrastVal').textContent = document.getElementById('enhanceContrast').value + '%';
|
||
document.getElementById('enhanceSaturateVal').textContent = document.getElementById('enhanceSaturate').value + '%';
|
||
document.getElementById('enhanceDenoiseVal').textContent = document.getElementById('enhanceDenoise').value + '%';
|
||
document.getElementById('enhanceSharpVal').textContent = document.getElementById('enhanceSharp').value + '%';
|
||
if (enhanceTimer) clearTimeout(enhanceTimer);
|
||
enhanceTimer = setTimeout(renderEnhancePreview, 120);
|
||
}
|
||
|
||
function enhanceParams() {
|
||
return {
|
||
brightness: parseInt(document.getElementById('enhanceBrightness').value, 10),
|
||
contrast: parseInt(document.getElementById('enhanceContrast').value, 10),
|
||
saturate: parseInt(document.getElementById('enhanceSaturate').value, 10),
|
||
denoise: parseInt(document.getElementById('enhanceDenoise').value, 10),
|
||
sharp: parseInt(document.getElementById('enhanceSharp').value, 10),
|
||
};
|
||
}
|
||
|
||
function estimateNoise(img) {
|
||
const aw = 160;
|
||
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
|
||
const ac = document.createElement('canvas');
|
||
ac.width = aw;
|
||
ac.height = ah;
|
||
const actx = ac.getContext('2d');
|
||
actx.drawImage(img, 0, 0, aw, ah);
|
||
const d = actx.getImageData(0, 0, aw, ah).data;
|
||
let sum = 0;
|
||
let n = 0;
|
||
for (let y = 0; y < ah - 1; y++) {
|
||
for (let x = 0; x < aw - 1; x++) {
|
||
const i = (y * aw + x) * 4;
|
||
const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
|
||
const lr = 0.299 * d[i + 4] + 0.587 * d[i + 5] + 0.114 * d[i + 6];
|
||
const lb = 0.299 * d[i + aw * 4] + 0.587 * d[i + aw * 4 + 1] + 0.114 * d[i + aw * 4 + 2];
|
||
sum += Math.abs(l - lr) + Math.abs(l - lb);
|
||
n += 2;
|
||
}
|
||
}
|
||
return n ? sum / n : 0;
|
||
}
|
||
|
||
function autoEnhance() {
|
||
if (!enhanceSourceImg) return;
|
||
const img = enhanceSourceImg;
|
||
const aw = 160;
|
||
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
|
||
const ac = document.createElement('canvas');
|
||
ac.width = aw;
|
||
ac.height = ah;
|
||
const actx = ac.getContext('2d');
|
||
actx.drawImage(img, 0, 0, aw, ah);
|
||
const d = actx.getImageData(0, 0, aw, ah).data;
|
||
const hist = new Array(256).fill(0);
|
||
let total = 0;
|
||
for (let i = 0; i < d.length; i += 4) {
|
||
if (d[i + 3] < 16) continue;
|
||
hist[Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2])]++;
|
||
total++;
|
||
}
|
||
const pct = p => {
|
||
let acc = 0;
|
||
const target = total * p;
|
||
for (let v = 0; v < 256; v++) {
|
||
acc += hist[v];
|
||
if (acc >= target) return v;
|
||
}
|
||
return 255;
|
||
};
|
||
let lo = pct(0.005);
|
||
let hi = pct(0.995);
|
||
if (hi - lo < 30) {
|
||
lo = Math.max(0, lo - 15);
|
||
hi = Math.min(255, hi + 15);
|
||
}
|
||
const contrast = Math.round(Math.min(150, Math.max(100, 25500 / (hi - lo))));
|
||
const brightness = Math.round(Math.min(120, Math.max(85, 12800 / Math.max(1, (lo + hi) / 2))));
|
||
const noise = estimateNoise(img);
|
||
let denoise = 0;
|
||
let sharp = 30;
|
||
if (noise > 6) {
|
||
denoise = Math.min(50, Math.round(noise * 6));
|
||
sharp = 15;
|
||
}
|
||
const saturate = 106;
|
||
document.getElementById('enhanceBrightness').value = brightness;
|
||
document.getElementById('enhanceContrast').value = contrast;
|
||
document.getElementById('enhanceSaturate').value = saturate;
|
||
document.getElementById('enhanceDenoise').value = denoise;
|
||
document.getElementById('enhanceSharp').value = sharp;
|
||
scheduleEnhancePreview();
|
||
}
|
||
|
||
async function saveEnhance() {
|
||
if (enhanceSaving) return;
|
||
if (!enhanceEntryId) { alert('Запись не выбрана'); return; }
|
||
if (!enhanceSourceImg) { alert('Фото ещё не загружено — подождите'); return; }
|
||
await loadEnhanceEngine();
|
||
const btn = document.getElementById('enhanceSaveBtn');
|
||
enhanceSaving = true;
|
||
if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; }
|
||
const entryId = enhanceEntryId;
|
||
try {
|
||
let done = false;
|
||
let engineLabel = 'клиент';
|
||
if (enhanceAiResultPath && isDefaultEnhanceParams()) {
|
||
const ctrl = new AbortController();
|
||
const timer = setTimeout(() => ctrl.abort(), 15000);
|
||
try {
|
||
await applyAiResult(ctrl.signal);
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
engineLabel = 'ИИ';
|
||
done = true;
|
||
} else if (enhanceEngine !== 'client' && !enhanceAiResultPath) {
|
||
try {
|
||
const ctrl = new AbortController();
|
||
const timer = setTimeout(() => ctrl.abort(), 8000);
|
||
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance`, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ params: enhanceParams() }),
|
||
signal: ctrl.signal,
|
||
});
|
||
clearTimeout(timer);
|
||
if (!res.ok) {
|
||
const err = await res.json().catch(() => ({}));
|
||
throw new Error(err.error || 'Ошибка сервера');
|
||
}
|
||
engineLabel = 'сервер';
|
||
done = true;
|
||
} catch (e) {
|
||
if (enhanceEngine === 'server') throw e;
|
||
}
|
||
}
|
||
if (!done) {
|
||
const img = enhanceSourceImg;
|
||
const canvas = document.createElement('canvas');
|
||
canvas.width = img.naturalWidth;
|
||
canvas.height = img.naturalHeight;
|
||
const ctx = canvas.getContext('2d');
|
||
drawEnhanced(ctx, img, canvas.width, canvas.height);
|
||
const blob = await new Promise((resolve, reject) => canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/jpeg', 0.92));
|
||
const fd = new FormData();
|
||
fd.append('photo', blob, 'enhanced.jpg');
|
||
const ctrl = new AbortController();
|
||
const timer = setTimeout(() => ctrl.abort(), 30000);
|
||
let res;
|
||
try {
|
||
res = await fetch(`${API}/api/entries/${entryId}/photo/enhance`, { method: 'PUT', headers: hdr(), body: fd, signal: ctrl.signal });
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
if (!res.ok) {
|
||
const err = await res.json().catch(() => ({}));
|
||
throw new Error(err.error || 'Ошибка сохранения');
|
||
}
|
||
}
|
||
showToast(`Фото улучшено (${engineLabel}) и сохранено`);
|
||
try { closeEnhance(); } catch (e) { console.error('closeEnhance failed:', e); }
|
||
try { await refreshEntryCard(entryId); } catch (e) { console.error('refreshEntryCard failed:', e); }
|
||
} catch (e) {
|
||
console.error('saveEnhance failed:', e);
|
||
alert(e && e.message ? e.message : String(e));
|
||
} finally {
|
||
enhanceSaving = false;
|
||
if (btn && document.contains(btn)) {
|
||
btn.disabled = false;
|
||
btn.textContent = 'Применить';
|
||
}
|
||
}
|
||
}
|
||
|
||
async function aiCorrect() {
|
||
if (aiCorrecting) return;
|
||
const textarea = document.getElementById('editDesc');
|
||
const text = textarea.value.trim();
|
||
if (!text) { showToast('Нет текста для исправления'); return; }
|
||
const btn = document.getElementById('aiCorrectBtn');
|
||
const modal = document.getElementById('aiCorrectModal');
|
||
const suggestionEl = document.getElementById('aiSuggestion');
|
||
aiCorrecting = true;
|
||
btn.disabled = true;
|
||
btn.textContent = '⏳';
|
||
suggestionEl.textContent = 'Обработка...';
|
||
modal.classList.add('open');
|
||
try {
|
||
const res = await fetch(`${API}/api/ai/correct`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ text })
|
||
});
|
||
if (!res.ok) {
|
||
const err = await res.json();
|
||
throw new Error(err.error || 'Ошибка ИИ');
|
||
}
|
||
const data = await res.json();
|
||
suggestionEl.textContent = data.suggestion || text;
|
||
} catch (e) {
|
||
suggestionEl.textContent = 'Ошибка: ' + e.message;
|
||
showToast('ИИ недоступен: ' + e.message);
|
||
} finally {
|
||
aiCorrecting = false;
|
||
btn.disabled = false;
|
||
btn.textContent = '✨';
|
||
}
|
||
}
|
||
|
||
function closeAiCorrect() {
|
||
document.getElementById('aiCorrectModal').classList.remove('open');
|
||
}
|
||
|
||
function acceptAiCorrect() {
|
||
const suggestion = document.getElementById('aiSuggestion').textContent;
|
||
if (suggestion && suggestion !== 'Обработка...' && !suggestion.startsWith('Ошибка:')) {
|
||
document.getElementById('editDesc').value = suggestion;
|
||
editAiSuggestion = suggestion.trim();
|
||
}
|
||
closeAiCorrect();
|
||
}
|
||
|
||
function renderEditAiStatus(e) {
|
||
const el = document.getElementById('editAiStatus');
|
||
if (!e || !e.ai_status) { el.style.display = 'none'; el.innerHTML = ''; return; }
|
||
el.style.display = 'block';
|
||
const changed = e.description_ai && e.description_original && e.description_ai !== e.description_original;
|
||
const parts = [AI_STATUS_LABELS[e.ai_status] || `ИИ: ${e.ai_status}`];
|
||
if (e.ai_checked_at) parts.push(fmtFull(e.ai_checked_at));
|
||
let html = `<span>${esc(parts.join(' · '))}</span>`;
|
||
if (changed) html += ` <button type="button" id="aiRevertBtn" class="ai-btn" style="font-size:.75rem" title="Вернуть исходный текст (до ИИ)">↩ Оригинал</button>`;
|
||
html += ` <button type="button" id="aiRecheckBtn" class="ai-btn" style="font-size:.75rem" title="Проверить заново">⟳ Проверить</button>`;
|
||
el.innerHTML = html;
|
||
const rb = document.getElementById('aiRevertBtn');
|
||
if (rb) rb.addEventListener('click', () => revertAi(e.id));
|
||
const cb = document.getElementById('aiRecheckBtn');
|
||
if (cb) cb.addEventListener('click', () => recheckAi(e.id));
|
||
}
|
||
|
||
async function revertAi(id) {
|
||
if (!confirm('Вернуть исходный текст записи (до ИИ-проверки)?')) return;
|
||
const res = await fetch(`${API}/api/entries/${id}/ai/revert`, { method: 'POST', headers: hdr() });
|
||
if (!res.ok) { const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); return; }
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (e) {
|
||
if (e.description_original) e.description = e.description_original;
|
||
e.description_ai = null;
|
||
e.ai_status = 'reverted';
|
||
e.ai_error = null;
|
||
}
|
||
showToast('Оригинал восстановлен');
|
||
closeEdit();
|
||
refreshEntryCard(id);
|
||
}
|
||
|
||
async function recheckAi(id) {
|
||
const res = await fetch(`${API}/api/entries/${id}/ai/recheck`, { method: 'POST', headers: hdr() });
|
||
if (!res.ok) { const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); return; }
|
||
const e = currentEntries.find(x => x.id === id);
|
||
if (e) {
|
||
e.ai_status = 'pending';
|
||
e.ai_error = null;
|
||
}
|
||
showToast('Отправлено на ИИ-проверку');
|
||
closeEdit();
|
||
refreshEntryCard(id);
|
||
}
|
||
|
||
function editSourceFor(description) {
|
||
if (!editAiSuggestion) return 'manual';
|
||
return description === editAiSuggestion ? 'ai' : 'ai_manual';
|
||
}
|
||
|
||
async function saveEdit() {
|
||
if (!editId) return;
|
||
const name = document.getElementById('editName').value.trim();
|
||
const group_id = document.getElementById('editGroup').value;
|
||
const description = document.getElementById('editDesc').value.trim();
|
||
if (!name || !group_id || !description) { alert('Заполните все поля'); return; }
|
||
|
||
const moduleId = await resolveModuleId(document.getElementById('editModule').value);
|
||
if (moduleId === null) { alert('Тема модуля не найдена. Выберите из списка подсказок.'); return; }
|
||
|
||
const formData = new FormData();
|
||
formData.append('student_name', name);
|
||
formData.append('group_id', group_id);
|
||
formData.append('description', description);
|
||
formData.append('module_id', moduleId);
|
||
formData.append('edit_source', editSourceFor(description));
|
||
|
||
const photoFiles = document.getElementById('editPhoto').files;
|
||
for (const f of photoFiles) formData.append('photo', f);
|
||
|
||
const res = await fetch(`${API}/api/entries/${editId}`, {
|
||
method: 'PUT',
|
||
headers: hdr(),
|
||
body: formData
|
||
});
|
||
if (!res.ok) { const err = await res.json(); alert(err.error); return; }
|
||
|
||
const files = document.getElementById('editFiles').files;
|
||
if (files.length) {
|
||
const filesFormData = new FormData();
|
||
for (const f of files) filesFormData.append('files', f);
|
||
const uploadRes = await fetch(`${API}/api/entries/${editId}/files`, {
|
||
method: 'POST',
|
||
headers: hdr(),
|
||
body: filesFormData
|
||
});
|
||
if (!uploadRes.ok) {
|
||
const err = await uploadRes.json().catch(() => ({}));
|
||
alert(err.error || 'Ошибка загрузки файлов');
|
||
return;
|
||
}
|
||
}
|
||
|
||
const id = editId;
|
||
closeEdit();
|
||
const refreshed = await refreshEntryCard(id);
|
||
if (!refreshed) loadEntries();
|
||
showToast('Запись обновлена');
|
||
}
|
||
|
||
async function delEntry(id) {
|
||
if (!confirm('Переместить запись в корзину? Файлы и фото сохранятся.')) return;
|
||
await fetch(`${API}/api/entries/${id}`, { method: 'DELETE', headers: hdr() });
|
||
showToast('Запись перемещена в корзину');
|
||
loadEntries();
|
||
}
|
||
|
||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadEntries(); });
|
||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadEntries(); });
|
||
document.getElementById('moduleFilter').addEventListener('change', applyModuleFilter);
|
||
document.getElementById('moduleFilter').addEventListener('keydown', e => {
|
||
if (e.key === 'Enter') { e.preventDefault(); applyModuleFilter(); }
|
||
});
|
||
document.getElementById('moduleFilter').addEventListener('input', () => {
|
||
clearTimeout(moduleSearchTimer);
|
||
const q = document.getElementById('moduleFilter').value.trim();
|
||
moduleSearchTimer = setTimeout(async () => {
|
||
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 () => {
|
||
const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT);
|
||
if (list) renderModuleOptions('editModuleList', list);
|
||
}, 250);
|
||
});
|
||
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadEntries(); });
|
||
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadEntries(); });
|
||
document.getElementById('searchInput').addEventListener('input', () => {
|
||
clearTimeout(searchTimer);
|
||
searchTimer = setTimeout(() => { page = 1; loadEntries(); }, 300);
|
||
});
|
||
document.getElementById('editForm').addEventListener('submit', (e) => {
|
||
e.preventDefault();
|
||
saveEdit();
|
||
});
|
||
document.getElementById('editFiles').addEventListener('change', (e) => {
|
||
const preview = document.getElementById('editFilesPreview');
|
||
preview.innerHTML = '';
|
||
Array.from(e.target.files).forEach((f, i) => {
|
||
const div = document.createElement('div');
|
||
div.className = 'file-preview-item';
|
||
div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem';
|
||
div.innerHTML = `<span>${esc(f.name)}</span> <span style="color:var(--muted)">${(f.size/1024).toFixed(1)} KB</span> <button type="button" data-remove-file="${i}" style="background:none;border:none;color:var(--muted);cursor:pointer;font-size:1.1rem;line-height:1">✕</button>`;
|
||
preview.appendChild(div);
|
||
});
|
||
});
|
||
|
||
document.getElementById('editPhoto').addEventListener('change', (e) => {
|
||
const preview = document.getElementById('editPhotoPreview');
|
||
Array.from(e.target.files).forEach(f => {
|
||
const div = document.createElement('div');
|
||
div.className = 'file-preview-item';
|
||
div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem';
|
||
const url = URL.createObjectURL(f);
|
||
div.innerHTML = `<img src="${url}" style="width:48px;height:48px;object-fit:cover;border-radius:4px"> <span>${esc(f.name)}</span> <span style="color:var(--muted)">${(f.size/1024).toFixed(1)} KB</span> <button type="button" data-remove-new-photo="${f.name}" style="background:none;border:none;color:var(--muted);cursor:pointer;font-size:1.1rem;line-height:1">✕</button>`;
|
||
preview.appendChild(div);
|
||
});
|
||
});
|
||
|
||
function removeEditFile(index) {
|
||
const input = document.getElementById('editFiles');
|
||
const dt = new DataTransfer();
|
||
Array.from(input.files).forEach((f, i) => { if (i !== index) dt.items.add(f); });
|
||
input.files = dt.files;
|
||
input.dispatchEvent(new Event('change'));
|
||
}
|
||
|
||
async function exportCSV() {
|
||
const p = new URLSearchParams();
|
||
const q = document.getElementById('searchInput').value;
|
||
const sn = document.getElementById('studentFilter').value;
|
||
const gid = document.getElementById('groupFilter').value;
|
||
const df = document.getElementById('dateFrom').value;
|
||
const dt = document.getElementById('dateTo').value;
|
||
if (q) p.set('search', q);
|
||
if (sn) p.set('student_name', sn);
|
||
if (gid) p.set('group_id', gid);
|
||
if (df) p.set('date_from', df);
|
||
if (dt) p.set('date_to', dt);
|
||
if (moduleFilterId) p.set('module_id', moduleFilterId);
|
||
const res = await fetch(`${API}/api/entries?${p}`, { headers: hdr() });
|
||
const entries = (await res.json()).entries;
|
||
if (!entries.length) { alert('Нет данных для экспорта'); return; }
|
||
const rows = [['Фамилия и имя', 'Группа', 'Тема модуля', 'Описание', 'Дата', 'Фото']];
|
||
entries.forEach(e => {
|
||
rows.push([
|
||
e.student_name,
|
||
e.group_name,
|
||
e.module_name || '',
|
||
e.description.replace(/\n/g, ' '),
|
||
fmtFull(e.created_at),
|
||
e.photo_path ? `${API}${e.photo_path}` : ''
|
||
]);
|
||
});
|
||
const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(';')).join('\n');
|
||
const bom = '\uFEFF';
|
||
const blob = new Blob([bom + csv], { type: 'text/csv;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
const dateLabel = df && dt ? `${df}_${dt}` : 'all';
|
||
a.download = `journal_${dateLabel}.csv`;
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
let linkGroups = [];
|
||
let linkStudentsLoaded = false;
|
||
let createdLinkUrl = '';
|
||
|
||
function fmtD(d) { return d ? d.split('-').reverse().join('.') : 'весь период'; }
|
||
|
||
async function openLinkCreate() {
|
||
const gid = document.getElementById('groupFilter').value;
|
||
if (!gid) { alert('Сначала выберите группу в фильтре'); return; }
|
||
const df = document.getElementById('dateFrom').value;
|
||
const dt = document.getElementById('dateTo').value;
|
||
if (!linkGroups.length) {
|
||
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
|
||
linkGroups = await res.json();
|
||
}
|
||
if (!linkStudentsLoaded) {
|
||
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
|
||
const names = await res.json();
|
||
const dl = document.getElementById('linkStudentList');
|
||
dl.innerHTML = names.map(n => `<option value="${esc(n)}">`).join('');
|
||
linkStudentsLoaded = true;
|
||
}
|
||
const currentStudent = document.getElementById('studentFilter').value;
|
||
const g = linkGroups.find(x => String(x.id) === String(gid));
|
||
document.getElementById('linkPreview').innerHTML =
|
||
`Будут показаны записи: <b>${esc(g ? g.name : '')}</b><br>Период: <b>${fmtD(df)}</b> — <b>${fmtD(dt)}</b>`;
|
||
document.getElementById('linkGroupPreview').value = g ? g.name : '';
|
||
const dfl = df.split('-').reverse().join('.');
|
||
document.getElementById('linkNameInput').value = `${g ? g.name : ''} ${dfl}`;
|
||
document.getElementById('linkStudent').value = currentStudent;
|
||
document.getElementById('linkExpiresDays').value = '7';
|
||
document.getElementById('linkShowNames').checked = false;
|
||
document.getElementById('linkPassword').value = '';
|
||
document.getElementById('linkMessage').value = '';
|
||
document.getElementById('linkUrl').value = '';
|
||
const s = await loadLinkSettings();
|
||
document.getElementById('linkShowNames').checked = s.share_show_student_names !== 'false';
|
||
document.getElementById('linkShowMessage').checked = s.share_show_student_message === 'true';
|
||
document.getElementById('linkShowDate').checked = s.share_show_entry_date === 'true';
|
||
document.getElementById('linkShowPhotos').checked = s.share_show_group_photos !== 'false';
|
||
document.getElementById('linkCreateView').style.display = '';
|
||
document.getElementById('linkResultView').style.display = 'none';
|
||
document.getElementById('linkModal').classList.add('open');
|
||
}
|
||
|
||
function closeLinkCreate() {
|
||
document.getElementById('linkModal').classList.remove('open');
|
||
}
|
||
|
||
async function createLink() {
|
||
const name = document.getElementById('linkNameInput').value.trim();
|
||
const group_id = document.getElementById('groupFilter').value;
|
||
const student_name = document.getElementById('linkStudent').value;
|
||
const date_from = document.getElementById('dateFrom').value;
|
||
const date_to = document.getElementById('dateTo').value;
|
||
const expires_days = parseInt(document.getElementById('linkExpiresDays').value, 10);
|
||
const show_student_names = document.getElementById('linkShowNames').checked;
|
||
const access_password = document.getElementById('linkPassword').value;
|
||
const message = document.getElementById('linkMessage').value.trim();
|
||
const link_url = document.getElementById('linkUrl').value.trim();
|
||
if (!name) { alert('Введите название'); return; }
|
||
if (expires_days < 1 || expires_days > 365) { alert('Дней истечения: 1-365'); return; }
|
||
const expires_at = new Date(Date.now() + expires_days * 24 * 60 * 60 * 1000).toISOString();
|
||
const res = await fetch(`${API}/api/links`, {
|
||
method: 'POST',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ name, group_id, student_name: student_name || null, date_from: date_from || null, date_to: date_to || null, show_student_names, expires_at, access_password: access_password || null, message: message || null, link_url: link_url || null, show_student_message: document.getElementById('linkShowMessage').checked, show_entry_date: document.getElementById('linkShowDate').checked, show_group_photos: document.getElementById('linkShowPhotos').checked })
|
||
});
|
||
if (!res.ok) { const err = await res.json(); alert(err.error || 'Ошибка'); return; }
|
||
const link = await res.json();
|
||
createdLinkUrl = `${location.origin}/s/${link.token}`;
|
||
document.getElementById('linkUrlResult').value = createdLinkUrl;
|
||
document.getElementById('linkCreateView').style.display = 'none';
|
||
document.getElementById('linkResultView').style.display = '';
|
||
showToast('Ссылка создана');
|
||
}
|
||
|
||
function copyLink() { copyText(createdLinkUrl); }
|
||
|
||
function closeImgModal() {
|
||
const m = document.getElementById('imgModal');
|
||
if (!m) return;
|
||
m.classList.remove('open');
|
||
document.getElementById('imgModalSrc').removeAttribute('src');
|
||
galleryIndex = -1;
|
||
}
|
||
|
||
function syncImgModalNav() {
|
||
const nav = document.getElementById('imgModalNav');
|
||
const count = document.getElementById('imgModalCount');
|
||
if (!nav || !count) return;
|
||
const multi = galleryList.length > 1 && galleryIndex >= 0;
|
||
nav.hidden = !multi;
|
||
if (multi) count.textContent = `${galleryIndex + 1} / ${galleryList.length}`;
|
||
}
|
||
|
||
function showGalleryImage(i) {
|
||
if (!galleryList.length) return;
|
||
const n = galleryList.length;
|
||
galleryIndex = ((i % n) + n) % n;
|
||
showImg(galleryList[galleryIndex]);
|
||
syncImgModalNav();
|
||
}
|
||
|
||
function bindReportGalleryLightbox() {
|
||
const modal = document.getElementById('imgModal');
|
||
const prev = document.getElementById('imgModalPrev');
|
||
const next = document.getElementById('imgModalNext');
|
||
const card = document.getElementById('reportCardModal');
|
||
if (prev) prev.addEventListener('click', e => { e.stopPropagation(); showGalleryImage(galleryIndex - 1); });
|
||
if (next) next.addEventListener('click', e => { e.stopPropagation(); showGalleryImage(galleryIndex + 1); });
|
||
if (modal) {
|
||
modal.addEventListener('click', e => {
|
||
if (e.target.closest('.img-modal-nav')) return;
|
||
closeImgModal();
|
||
});
|
||
}
|
||
if (!card) return;
|
||
card.addEventListener('click', e => {
|
||
const shot = e.target.closest('[data-gal-index]');
|
||
if (!shot) return;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
showGalleryImage(parseInt(shot.dataset.galIndex, 10));
|
||
});
|
||
card.addEventListener('wheel', e => {
|
||
if (Math.abs(e.deltaX) <= Math.abs(e.deltaY) || galleryList.length < 2) return;
|
||
e.preventDefault();
|
||
showGalleryImage(galleryIndex + (e.deltaX > 0 ? 1 : -1));
|
||
}, { passive: false });
|
||
}
|
||
|
||
bindReportGalleryLightbox();
|
||
|
||
document.getElementById('editModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeEdit(); });
|
||
document.getElementById('linkModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeLinkCreate(); });
|
||
document.getElementById('reportCardModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeReportCard(); });
|
||
document.addEventListener('keydown', e => {
|
||
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
|
||
if (!document.getElementById('imgModal').classList.contains('open')) return;
|
||
if (galleryList.length < 2 || galleryIndex < 0) return;
|
||
e.preventDefault();
|
||
showGalleryImage(galleryIndex + (e.key === 'ArrowRight' ? 1 : -1));
|
||
return;
|
||
}
|
||
if (e.key !== 'Escape') return;
|
||
if (document.getElementById('imgModal').classList.contains('open')) { closeImgModal(); return; }
|
||
if (document.getElementById('reportFields').classList.contains('open')) { setReportFieldsOpen(false); return; }
|
||
if (document.getElementById('reportCardModal').classList.contains('open')) closeReportCard();
|
||
});
|
||
|
||
function setReportCardFields(keys) {
|
||
reportCardFields.length = 0;
|
||
REPORT_CARD_FIELDS.map(f => f.key).filter(k => keys.includes(k)).forEach(k => reportCardFields.push(k));
|
||
saveReportCardFields();
|
||
renderReportFieldsList();
|
||
renderReportEmbedToggle();
|
||
refreshReportCard();
|
||
}
|
||
|
||
function renderReportFieldsList() {
|
||
const list = document.getElementById('reportFieldsList');
|
||
if (!list) return;
|
||
list.innerHTML = REPORT_CARD_FIELDS.map(f => `
|
||
<label class="report-fields__item">
|
||
<input type="checkbox" data-report-field="${f.key}"${reportCardFieldOn(f.key) ? ' checked' : ''}>
|
||
<span>${esc(f.label)}</span>
|
||
</label>`).join('');
|
||
}
|
||
|
||
const reportFieldsRoot = document.getElementById('reportFields');
|
||
const reportFieldsBtn = document.getElementById('reportFieldsBtn');
|
||
const reportFieldsPanel = document.getElementById('reportFieldsPanel');
|
||
const reportEmbedToggle = document.getElementById('reportEmbedToggle');
|
||
const reportEmbedHint = document.getElementById('reportEmbedHint');
|
||
const REPORT_EMBED_HINT = 'Показывать превью последних картинок-вложений ученика за всё время';
|
||
|
||
function renderReportEmbedToggle() {
|
||
if (!reportEmbedToggle) return;
|
||
reportEmbedToggle.checked = reportCardEmbed;
|
||
if (reportEmbedHint) reportEmbedHint.textContent = REPORT_EMBED_HINT;
|
||
}
|
||
|
||
function setReportCardEmbed(on) {
|
||
reportCardEmbed = !!on;
|
||
saveReportCardEmbed();
|
||
renderReportEmbedToggle();
|
||
refreshReportCard();
|
||
}
|
||
|
||
if (reportEmbedToggle) {
|
||
reportEmbedToggle.addEventListener('change', e => setReportCardEmbed(e.target.checked));
|
||
}
|
||
|
||
const reportStudentWorksToggle = document.getElementById('reportStudentWorksToggle');
|
||
const reportStudentWorksHint = document.getElementById('reportStudentWorksHint');
|
||
const REPORT_STUDENT_WORKS_HINT = 'Показывать последние фото с занятий ученика — до 3 в строку';
|
||
|
||
function renderReportStudentWorksToggle() {
|
||
if (!reportStudentWorksToggle) return;
|
||
reportStudentWorksToggle.checked = reportCardStudentWorks;
|
||
if (reportStudentWorksHint) reportStudentWorksHint.textContent = REPORT_STUDENT_WORKS_HINT;
|
||
}
|
||
|
||
function setReportCardStudentWorks(on) {
|
||
reportCardStudentWorks = !!on;
|
||
saveReportCardStudentWorks();
|
||
renderReportStudentWorksToggle();
|
||
refreshReportCard();
|
||
}
|
||
|
||
if (reportStudentWorksToggle) {
|
||
reportStudentWorksToggle.addEventListener('change', e => setReportCardStudentWorks(e.target.checked));
|
||
}
|
||
|
||
const reportLogoToggle = document.getElementById('reportLogoToggle');
|
||
const reportLogoHint = document.getElementById('reportLogoHint');
|
||
const REPORT_LOGO_HINT = 'Логотип сайта в левом верхнем углу карточки поверх фото';
|
||
|
||
function renderReportLogoToggle() {
|
||
if (!reportLogoToggle) return;
|
||
reportLogoToggle.checked = reportCardLogoOn;
|
||
if (reportLogoHint) reportLogoHint.textContent = REPORT_LOGO_HINT;
|
||
}
|
||
|
||
function setReportCardLogo(on) {
|
||
reportCardLogoOn = !!on;
|
||
saveReportCardLogo();
|
||
renderReportLogoToggle();
|
||
refreshReportCard();
|
||
}
|
||
|
||
if (reportLogoToggle) {
|
||
reportLogoToggle.addEventListener('change', e => setReportCardLogo(e.target.checked));
|
||
}
|
||
|
||
async function loadReportCardLogoImage() {
|
||
try {
|
||
const r = await fetch(`${API}/api/public-settings`);
|
||
const s = await r.json();
|
||
reportCardLogoSrc = (s && s.system_logo) || '';
|
||
const logo = document.getElementById('reportCardLogo');
|
||
if (logo && reportCardLogoSrc) logo.src = reportCardLogoSrc;
|
||
refreshReportCard();
|
||
} catch (err) {}
|
||
}
|
||
|
||
function setReportFieldsOpen(open) {
|
||
reportFieldsRoot.classList.toggle('open', open);
|
||
reportFieldsBtn.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||
}
|
||
|
||
renderReportFieldsList();
|
||
renderReportEmbedToggle();
|
||
renderReportStudentWorksToggle();
|
||
renderReportLogoToggle();
|
||
loadReportCardLogoImage();
|
||
reportFieldsBtn.addEventListener('click', () => setReportFieldsOpen(!reportFieldsRoot.classList.contains('open')));
|
||
reportFieldsPanel.addEventListener('change', e => {
|
||
const cb = e.target.closest('[data-report-field]');
|
||
if (!cb) return;
|
||
const key = cb.dataset.reportField;
|
||
const keys = cb.checked
|
||
? REPORT_CARD_FIELDS.map(f => f.key).filter(k => reportCardFieldOn(k) || k === key)
|
||
: reportCardFields.filter(k => k !== key);
|
||
setReportCardFields(keys);
|
||
});
|
||
document.getElementById('reportFieldsAll').addEventListener('click', () => setReportCardFields(REPORT_CARD_FIELDS.map(f => f.key)));
|
||
document.getElementById('reportFieldsNone').addEventListener('click', () => setReportCardFields([]));
|
||
document.addEventListener('click', e => {
|
||
if (!reportFieldsRoot.contains(e.target)) setReportFieldsOpen(false);
|
||
});
|
||
|
||
document.getElementById('grid').addEventListener('click', e => {
|
||
const det = e.target.closest('[data-detach]');
|
||
if (det) { detachFile(parseInt(det.dataset.detach, 10)); return; }
|
||
const rp = e.target.closest('[data-report]');
|
||
if (rp) { openReportCard(parseInt(rp.dataset.report, 10)); return; }
|
||
const ed = e.target.closest('[data-edit]');
|
||
if (ed) { openEdit(parseInt(ed.dataset.edit, 10)); return; }
|
||
const en = e.target.closest('[data-enhance]');
|
||
if (en) { openEnhance(parseInt(en.dataset.enhance, 10)); return; }
|
||
const ce = e.target.closest('[data-cpuenhance]');
|
||
if (ce) { openCpuEnhance(parseInt(ce.dataset.cpuenhance, 10)); return; }
|
||
const dl = e.target.closest('[data-del]');
|
||
if (dl) { delEntry(parseInt(dl.dataset.del, 10)); }
|
||
});
|
||
|
||
document.getElementById('editFilesPreview').addEventListener('click', e => {
|
||
const btn = e.target.closest('[data-remove-file]');
|
||
if (btn) removeEditFile(parseInt(btn.dataset.removeFile, 10));
|
||
});
|
||
|
||
document.getElementById('editPhotoPreview').addEventListener('click', e => {
|
||
const removeBtn = e.target.closest('[data-remove-photo]');
|
||
if (removeBtn) {
|
||
document.getElementById('editPhoto').value = '';
|
||
document.getElementById('editPhotoPreview').innerHTML = '';
|
||
return;
|
||
}
|
||
const applyBtn = e.target.closest('.apply-photo-btn');
|
||
if (applyBtn) { applyMainPhoto(applyBtn); return; }
|
||
const removeNewBtn = e.target.closest('[data-remove-new-photo]');
|
||
if (removeNewBtn) {
|
||
const fileName = removeNewBtn.dataset.removeNewPhoto;
|
||
const input = document.getElementById('editPhoto');
|
||
const dt = new DataTransfer();
|
||
Array.from(input.files).forEach(f => { if (f.name !== fileName) dt.items.add(f); });
|
||
input.files = dt.files;
|
||
removeNewBtn.closest('.file-preview-item').remove();
|
||
}
|
||
});
|
||
|
||
document.getElementById('aiCorrectBtn').addEventListener('click', aiCorrect);
|
||
document.getElementById('enhanceCancelBtn').addEventListener('click', closeEnhance);
|
||
document.getElementById('enhanceAutoBtn').addEventListener('click', autoEnhance);
|
||
document.getElementById('enhanceAiBtn').addEventListener('click', runPhotoAi);
|
||
document.getElementById('enhanceRestoreBtn').addEventListener('click', restoreOriginal);
|
||
document.getElementById('enhanceSaveBtn').addEventListener('click', saveEnhance);
|
||
document.getElementById('enhanceHistoryBtn').addEventListener('click', openPhotoHistory);
|
||
document.getElementById('photoHistoryCloseBtn').addEventListener('click', () => document.getElementById('photoHistoryModal').classList.remove('open'));
|
||
document.getElementById('photoHistoryModal').addEventListener('click', e => {
|
||
if (e.target === e.currentTarget) e.currentTarget.classList.remove('open');
|
||
});
|
||
document.getElementById('photoHistoryList').addEventListener('click', e => {
|
||
const btn = e.target.closest('[data-job-rollback]');
|
||
if (btn) {
|
||
rollbackPhotoJob(parseInt(btn.dataset.jobRollback, 10));
|
||
return;
|
||
}
|
||
const applyBtn = e.target.closest('[data-job-apply]');
|
||
if (applyBtn) applyPhotoJob(parseInt(applyBtn.dataset.jobApply, 10));
|
||
});
|
||
|
||
async function applyPhotoJob(jobId) {
|
||
if (!enhanceEntryId || enhanceSaving) return;
|
||
if (!confirm('Применить обработанную фотографию к записи? Текущая версия сохранится в истории.')) return;
|
||
enhanceSaving = true;
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Ошибка применения');
|
||
showToast('Фотография применена');
|
||
const mp = data.photo_path;
|
||
const origImg = document.getElementById('enhanceOrig');
|
||
if (origImg && mp) origImg.src = `${API}${mp}`;
|
||
loadPhotoHistory();
|
||
refreshEntryCard(enhanceEntryId);
|
||
} catch (e) {
|
||
alert(e.message);
|
||
} finally {
|
||
enhanceSaving = false;
|
||
}
|
||
}
|
||
document.getElementById('enhanceModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeEnhance(); });
|
||
document.getElementById('enhanceBrightness').addEventListener('input', scheduleEnhancePreview);
|
||
document.getElementById('enhanceContrast').addEventListener('input', scheduleEnhancePreview);
|
||
document.getElementById('enhanceSaturate').addEventListener('input', scheduleEnhancePreview);
|
||
document.getElementById('enhanceDenoise').addEventListener('input', scheduleEnhancePreview);
|
||
document.getElementById('enhanceSharp').addEventListener('input', scheduleEnhancePreview);
|
||
document.getElementById('cpuEnhanceModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeCpuEnhance(); });
|
||
document.getElementById('cpuEnhanceCancelBtn').addEventListener('click', () => closeCpuEnhance());
|
||
document.getElementById('cpuEnhanceCloseX').addEventListener('click', () => closeCpuEnhance());
|
||
document.getElementById('cpuEnhanceApplyBtn').addEventListener('click', cpuEnhanceApply);
|
||
document.getElementById('cpuEnhanceApplyCpuBtn').addEventListener('click', cpuEnhanceApplyCpuOnly);
|
||
document.getElementById('cpuEnhancePreviewBtn').addEventListener('click', cpuEnhancePreview);
|
||
document.getElementById('cpuEnhanceActivateBtn').addEventListener('click', cpuEnhanceActivate);
|
||
document.getElementById('cpuZoomIn').addEventListener('click', () => cpuEnhanceZoomBy(1.25));
|
||
document.getElementById('cpuZoomOut').addEventListener('click', () => cpuEnhanceZoomBy(1 / 1.25));
|
||
document.getElementById('cpuZoomReset').addEventListener('click', cpuEnhanceResetZoom);
|
||
document.getElementById('cpuEnhanceView').addEventListener('click', e => {
|
||
const btn = e.target.closest('button[data-cpu-view]');
|
||
if (btn) cpuEnhanceSetView(btn.dataset.cpuView);
|
||
});
|
||
document.querySelector('.cpu-enhance-tools').addEventListener('pointerdown', e => e.stopPropagation());
|
||
document.getElementById('cpuEnhanceAutoBtn').addEventListener('click', () => cpuEnhanceAuto(true));
|
||
document.getElementById('cpuEnhanceResetBtn').addEventListener('click', () => {
|
||
if (cpuEnhanceBusy) return;
|
||
cpuEnhanceResetSliders(false);
|
||
cpuEnhanceClearError();
|
||
cpuEnhanceSetInfo(null, [['Параметры', 'сброшены к значениям по умолчанию']]);
|
||
if (cpuEnhanceBaseImg) cpuEnhanceDrawLocal();
|
||
cpuEnhanceSyncPending();
|
||
showToast('Параметры сброшены к значениям по умолчанию');
|
||
});
|
||
document.getElementById('cpuEnhanceModeGroup').addEventListener('click', e => {
|
||
const btn = e.target.closest('button[data-cpu-mode]');
|
||
if (!btn || btn.disabled) return;
|
||
cpuEnhanceClearError();
|
||
cpuEnhanceSetMode(btn.dataset.cpuMode);
|
||
});
|
||
document.getElementById('cpuEnhanceModeGroup').addEventListener('keydown', e => {
|
||
if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return;
|
||
const group = document.getElementById('cpuEnhanceModeGroup');
|
||
const buttons = [...group.querySelectorAll('button[data-cpu-mode]')].filter(b => !b.disabled);
|
||
const at = buttons.indexOf(document.activeElement);
|
||
if (at < 0) return;
|
||
e.preventDefault();
|
||
const step = e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 1;
|
||
const next = buttons[(at + step + buttons.length) % buttons.length];
|
||
next.focus();
|
||
cpuEnhanceSetMode(next.dataset.cpuMode);
|
||
});
|
||
document.getElementById('cpuEnhanceScale').addEventListener('change', () => {
|
||
if (cpuEnhanceBaseImg) cpuEnhanceDrawLocal();
|
||
cpuEnhanceSyncPending();
|
||
});
|
||
document.getElementById('cpuEnhanceRestoreBtn').addEventListener('click', async () => {
|
||
if (!cpuEnhanceEntryId) return;
|
||
if (!confirm('Вернуть исходную фотографию?')) return;
|
||
try {
|
||
const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/restore-original`, { method: 'POST', headers: hdr() });
|
||
if (!res.ok) throw new Error('Ошибка восстановления');
|
||
showToast('Оригинал возвращён');
|
||
const saved = cpuEnhanceEntryId;
|
||
closeCpuEnhance(true);
|
||
refreshEntryCard(saved);
|
||
} catch (e) { showToast(e.message, true); }
|
||
});
|
||
CPU_ENHANCE_SLIDERS.forEach(k => {
|
||
const el = document.getElementById('cpuEnhance' + k);
|
||
if (!el) return;
|
||
el.addEventListener('input', () => {
|
||
cpuEnhanceSyncSlider(k);
|
||
cpuEnhanceClearError();
|
||
if (k !== 'Quality') cpuEnhanceParamsTouched = true;
|
||
if (k !== 'Quality' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal();
|
||
cpuEnhanceSyncPending();
|
||
});
|
||
el.addEventListener('dblclick', () => {
|
||
if (cpuEnhanceBusy) return;
|
||
el.value = CPU_ENHANCE_DEFAULTS[k];
|
||
cpuEnhanceSyncSlider(k);
|
||
cpuEnhanceParamsTouched = true;
|
||
if (k !== 'Quality' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal();
|
||
cpuEnhanceSyncPending();
|
||
});
|
||
});
|
||
|
||
function cpuEnhanceApplyTransform() {
|
||
const t = `translate(${cpuEnhancePanX}px, ${cpuEnhancePanY}px) scale(${cpuEnhanceZoom})`;
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (area) area.querySelectorAll('.cpu-enhance-layer').forEach(el => { el.style.transform = t; });
|
||
if (area) area.classList.toggle('zoomed', cpuEnhanceZoom > 1.001);
|
||
}
|
||
|
||
function cpuEnhanceClampPan() {
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (!area) return;
|
||
const rect = area.getBoundingClientRect();
|
||
const minX = rect.width * (1 - cpuEnhanceZoom);
|
||
const minY = rect.height * (1 - cpuEnhanceZoom);
|
||
cpuEnhancePanX = Math.min(0, Math.max(minX, cpuEnhancePanX));
|
||
cpuEnhancePanY = Math.min(0, Math.max(minY, cpuEnhancePanY));
|
||
}
|
||
|
||
function cpuEnhanceSyncZoomLabel() {
|
||
const el = document.getElementById('cpuZoomLevel');
|
||
if (el) el.textContent = Math.round(cpuEnhanceZoom * 100) + '%';
|
||
}
|
||
|
||
function cpuEnhanceSetZoom(next, cx, cy) {
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (!area) return;
|
||
const prev = cpuEnhanceZoom;
|
||
const clamped = Math.min(8, Math.max(1, next));
|
||
if (Math.abs(clamped - prev) < 0.001) { cpuEnhanceSyncZoomLabel(); return; }
|
||
const rect = area.getBoundingClientRect();
|
||
const px = typeof cx === 'number' ? cx : rect.width / 2;
|
||
const py = typeof cy === 'number' ? cy : rect.height / 2;
|
||
cpuEnhanceZoom = clamped;
|
||
cpuEnhancePanX = px - (px - cpuEnhancePanX) * (clamped / prev);
|
||
cpuEnhancePanY = py - (py - cpuEnhancePanY) * (clamped / prev);
|
||
cpuEnhanceClampPan();
|
||
cpuEnhanceApplyTransform();
|
||
cpuEnhanceSyncZoomLabel();
|
||
}
|
||
|
||
function cpuEnhanceZoomBy(factor) {
|
||
cpuEnhanceSetZoom(cpuEnhanceZoom * factor);
|
||
}
|
||
|
||
function cpuEnhanceResetZoom() {
|
||
cpuEnhanceZoom = 1;
|
||
cpuEnhancePanX = 0;
|
||
cpuEnhancePanY = 0;
|
||
cpuEnhanceApplyTransform();
|
||
cpuEnhanceSyncZoomLabel();
|
||
}
|
||
|
||
function cpuEnhanceSetView(view) {
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (!area) return;
|
||
let next = ['orig', 'split', 'result'].includes(view) ? view : 'split';
|
||
if (next !== 'orig' && !cpuEnhanceHasResult()) next = 'split';
|
||
cpuEnhanceView = next;
|
||
area.classList.remove('view-orig', 'view-result');
|
||
if (cpuEnhanceView === 'orig') area.classList.add('view-orig');
|
||
if (cpuEnhanceView === 'result') area.classList.add('view-result');
|
||
cpuEnhanceSetClip(50);
|
||
const top = document.getElementById('cpuEnhanceTop');
|
||
if (top) top.style.clipPath = 'inset(0 0 0 50%)';
|
||
const divider = document.getElementById('cpuEnhanceDivider');
|
||
if (divider) divider.style.left = '50%';
|
||
const seg = document.getElementById('cpuEnhanceView');
|
||
if (seg) {
|
||
seg.querySelectorAll('button[data-cpu-view]').forEach(b => {
|
||
const on = b.dataset.cpuView === cpuEnhanceView;
|
||
b.classList.toggle('active', on);
|
||
b.setAttribute('aria-pressed', on ? 'true' : 'false');
|
||
});
|
||
}
|
||
if (cpuEnhanceView === 'result' && cpuEnhanceZoom > 1.001) cpuEnhanceResetZoom();
|
||
}
|
||
|
||
(function initCpuEnhanceView() {
|
||
const area = document.getElementById('cpuEnhanceCompare');
|
||
if (!area) return;
|
||
let dragging = false;
|
||
let dividerDrag = false;
|
||
let lastX = 0;
|
||
let lastY = 0;
|
||
const moveClip = ev => {
|
||
const rect = area.getBoundingClientRect();
|
||
cpuEnhanceSetClip(((ev.clientX - rect.left) / rect.width) * 100);
|
||
};
|
||
const inTools = ev => !!(ev.target && ev.target.closest && ev.target.closest('.cpu-enhance-tools'));
|
||
area.addEventListener('pointerdown', ev => {
|
||
if (ev.button !== 0 && ev.pointerType === 'mouse') return;
|
||
if (inTools(ev)) return;
|
||
dividerDrag = !!ev.target.closest('#cpuEnhanceDivider') && cpuEnhanceView === 'split' && cpuEnhanceHasResult();
|
||
dragging = true;
|
||
lastX = ev.clientX;
|
||
lastY = ev.clientY;
|
||
area.setPointerCapture(ev.pointerId);
|
||
if (dividerDrag || (cpuEnhanceZoom <= 1.001 && cpuEnhanceView === 'split' && cpuEnhanceHasResult())) moveClip(ev);
|
||
});
|
||
area.addEventListener('wheel', ev => {
|
||
if (inTools(ev)) return;
|
||
if (!ev.ctrlKey && cpuEnhanceZoom <= 1.001) return;
|
||
ev.preventDefault();
|
||
const rect = area.getBoundingClientRect();
|
||
cpuEnhanceSetZoom(cpuEnhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15), ev.clientX - rect.left, ev.clientY - rect.top);
|
||
}, { passive: false });
|
||
area.addEventListener('pointermove', ev => {
|
||
if (!dragging) return;
|
||
if (dividerDrag) {
|
||
moveClip(ev);
|
||
return;
|
||
}
|
||
if (cpuEnhanceZoom > 1.001) {
|
||
area.classList.add('panning');
|
||
cpuEnhancePanX += ev.clientX - lastX;
|
||
cpuEnhancePanY += ev.clientY - lastY;
|
||
lastX = ev.clientX;
|
||
lastY = ev.clientY;
|
||
cpuEnhanceClampPan();
|
||
cpuEnhanceApplyTransform();
|
||
} else if (cpuEnhanceView === 'split' && cpuEnhanceHasResult()) {
|
||
moveClip(ev);
|
||
}
|
||
});
|
||
const endDrag = () => {
|
||
dragging = false;
|
||
dividerDrag = false;
|
||
area.classList.remove('panning');
|
||
};
|
||
area.addEventListener('pointerup', endDrag);
|
||
area.addEventListener('pointercancel', endDrag);
|
||
area.addEventListener('dblclick', ev => {
|
||
if (inTools(ev)) return;
|
||
cpuEnhanceResetZoom();
|
||
});
|
||
})();
|
||
|
||
function cpuEnhanceActivate() {
|
||
cpuEnhanceRun();
|
||
}
|
||
document.getElementById('aiAcceptBtn').addEventListener('click', acceptAiCorrect);
|
||
document.getElementById('aiRejectBtn').addEventListener('click', closeAiCorrect);
|
||
document.getElementById('aiCorrectModal').addEventListener('click', e => {
|
||
if (e.target === e.currentTarget) closeAiCorrect();
|
||
});
|
||
|
||
function openVideo(url, name, token) {
|
||
const modal = document.getElementById('videoModal');
|
||
const player = document.getElementById('videoPlayer');
|
||
const title = document.getElementById('videoTitle');
|
||
const dl = document.getElementById('videoDownload');
|
||
if (!modal || !player) return;
|
||
player.src = url;
|
||
player.currentTime = 0;
|
||
title.textContent = name || 'Видео';
|
||
dl.href = `${API}/api/files/${token}`;
|
||
dl.setAttribute('download', '');
|
||
modal.classList.add('open');
|
||
const play = player.play();
|
||
if (play && typeof play.catch === 'function') play.catch(() => {});
|
||
}
|
||
|
||
function closeVideo() {
|
||
const modal = document.getElementById('videoModal');
|
||
const player = document.getElementById('videoPlayer');
|
||
if (!modal || !player) return;
|
||
try { player.pause(); } catch {}
|
||
player.removeAttribute('src');
|
||
player.load();
|
||
modal.classList.remove('open');
|
||
}
|
||
|
||
document.getElementById('videoModal').addEventListener('click', e => {
|
||
if (e.target === e.currentTarget) closeVideo();
|
||
});
|
||
document.getElementById('videoClose').addEventListener('click', closeVideo);
|
||
document.addEventListener('keydown', e => {
|
||
if (e.key !== 'Escape') return;
|
||
if (document.getElementById('videoModal').classList.contains('open')) closeVideo();
|
||
if (document.getElementById('cpuEnhanceModal').classList.contains('open')) closeCpuEnhance();
|
||
});
|
||
document.addEventListener('keydown', e => {
|
||
if (!document.getElementById('cpuEnhanceModal').classList.contains('open')) return;
|
||
if (e.key === 'Tab') {
|
||
const items = cpuEnhanceFocusables();
|
||
if (!items.length) return;
|
||
const first = items[0];
|
||
const last = items[items.length - 1];
|
||
if (e.shiftKey && (document.activeElement === first || !items.includes(document.activeElement))) {
|
||
e.preventDefault();
|
||
last.focus();
|
||
} else if (!e.shiftKey && (document.activeElement === last || !items.includes(document.activeElement))) {
|
||
e.preventDefault();
|
||
first.focus();
|
||
}
|
||
return;
|
||
}
|
||
if (e.ctrlKey || e.metaKey || e.altKey) return;
|
||
const tag = (e.target && e.target.tagName) || '';
|
||
if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return;
|
||
if (cpuEnhanceBusy) return;
|
||
if (e.key === '+' || e.key === '=') { e.preventDefault(); cpuEnhanceZoomBy(1.25); return; }
|
||
if (e.key === '-' || e.key === '_') { e.preventDefault(); cpuEnhanceZoomBy(1 / 1.25); return; }
|
||
if (e.key === '0') { e.preventDefault(); cpuEnhanceResetZoom(); return; }
|
||
if (e.key === '1') { e.preventDefault(); cpuEnhanceSetView('orig'); return; }
|
||
if (e.key === '2') { e.preventDefault(); cpuEnhanceSetView('split'); return; }
|
||
if (e.key === '3') { e.preventDefault(); cpuEnhanceSetView('result'); }
|
||
});
|
||
document.addEventListener('click', e => {
|
||
const v = e.target.closest('[data-video]');
|
||
if (!v) return;
|
||
e.preventDefault();
|
||
openVideo(v.dataset.video, v.dataset.videoName, v.dataset.videoToken);
|
||
});
|
||
|
||
document.getElementById('exportCsvBtn').addEventListener('click', exportCSV);
|
||
document.getElementById('createLinkBtn').addEventListener('click', openLinkCreate);
|
||
document.getElementById('lessonReportBtn').addEventListener('click', () => {
|
||
openLessonModal({ groupId: document.getElementById('groupFilter').value });
|
||
});
|
||
document.querySelectorAll('#viewToggle button').forEach(b => b.addEventListener('click', () => setView(b.dataset.view)));
|
||
document.getElementById('editCancelBtn').addEventListener('click', closeEdit);
|
||
document.getElementById('linkCreateCloseBtn').addEventListener('click', closeLinkCreate);
|
||
document.getElementById('linkCreateSaveBtn').addEventListener('click', createLink);
|
||
document.getElementById('linkCopyBtn').addEventListener('click', copyLink);
|
||
|
||
(async () => {
|
||
if (await checkAuth()) {
|
||
buildSidebar(document.body.dataset.page);
|
||
bindJournalThumbLoading();
|
||
document.querySelectorAll('#viewToggle button').forEach(b => {
|
||
b.classList.toggle('active', b.dataset.view === view);
|
||
});
|
||
const qs = new URLSearchParams(location.search);
|
||
const qsStudent = (qs.get('student') || '').trim();
|
||
const qsDate = /^\d{4}-\d{2}-\d{2}$/.test(qs.get('date') || '') ? qs.get('date') : '';
|
||
if (qsDate) {
|
||
document.getElementById('dateFrom').value = qsDate;
|
||
document.getElementById('dateTo').value = qsDate;
|
||
} else {
|
||
setDefaultDates();
|
||
}
|
||
if (qsStudent) document.getElementById('studentFilter').value = qsStudent;
|
||
loadGroupOptions();
|
||
loadModuleOptions();
|
||
loadStudentOptions();
|
||
loadEntries();
|
||
connectLiveUpdates();
|
||
}
|
||
})();
|