feat(feedback): notify on feedback AI ready/error
This commit is contained in:
+167
-68
@@ -3,6 +3,8 @@
|
||||
let digests = [];
|
||||
let editingId = null;
|
||||
let saving = false;
|
||||
let query = '';
|
||||
let digestLoaded = false;
|
||||
let previewPath = null;
|
||||
let previewRemoved = false;
|
||||
let previewFile = null;
|
||||
@@ -40,6 +42,7 @@
|
||||
const pinnedEl = document.getElementById('digestPinned');
|
||||
const postAtEl = document.getElementById('digestPostAt');
|
||||
const hideAtEl = document.getElementById('digestHideAt');
|
||||
let restored = false;
|
||||
if (titleEl && d.title != null) titleEl.value = d.title;
|
||||
if (bodyEl && d.body != null) bodyEl.value = d.body;
|
||||
if (pinnedEl && d.isPinned != null) pinnedEl.checked = !!d.isPinned;
|
||||
@@ -47,7 +50,9 @@
|
||||
if (hideAtEl && d.hideAt != null) hideAtEl.value = d.hideAt;
|
||||
previewPath = d.previewPath || null;
|
||||
showPreview(previewPath);
|
||||
} catch (e) {}
|
||||
restored = !!(d.title || d.body || d.postAt || d.hideAt || previewPath || d.isPinned);
|
||||
return restored;
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
function clearDraft() {
|
||||
@@ -67,12 +72,6 @@
|
||||
return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function escAttr(s) {
|
||||
const d = document.createElement('textarea');
|
||||
d.textContent = s || '';
|
||||
return d.value;
|
||||
}
|
||||
|
||||
function tzOffsetMinutes(instant) {
|
||||
try {
|
||||
const d = new Date(instant);
|
||||
@@ -111,34 +110,20 @@
|
||||
} catch { return null; }
|
||||
}
|
||||
|
||||
function thumbSrc(p) {
|
||||
if (!p) return '';
|
||||
if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`;
|
||||
return p;
|
||||
}
|
||||
|
||||
function fmtDigestDate(iso) {
|
||||
if (!iso) return '—';
|
||||
try {
|
||||
return new Intl.DateTimeFormat('ru-RU', {
|
||||
timeZone: DateTime.tz, day: '2-digit', month: '2-digit', year: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit'
|
||||
}).format(new Date(iso));
|
||||
} catch { return String(iso).slice(0, 16); }
|
||||
}
|
||||
|
||||
function digestCardHtml(d) {
|
||||
const admin = isAdmin();
|
||||
const mine = currentUser && d.author_id === currentUser.id;
|
||||
const canEdit = admin || mine;
|
||||
const pinned = !!d.is_pinned;
|
||||
const nowTs = new Date();
|
||||
const nowTs = Date.now();
|
||||
const postFuture = d.post_at && new Date(d.post_at).getTime() > nowTs;
|
||||
const hidden = d.hide_at && new Date(d.hide_at) <= nowTs;
|
||||
|
||||
const badge = [];
|
||||
if (pinned) badge.push('<span class="digest-badge">Закреплено</span>');
|
||||
if (d.post_at) badge.push('<span class="digest-badge">Публикация ' + fmtDigestDate(d.post_at) + '</span>');
|
||||
if (d.hide_at) badge.push('<span class="digest-badge">Скрыть ' + fmtDigestDate(d.hide_at) + '</span>');
|
||||
if (postFuture) badge.push('<span class="digest-badge scheduled">Запланировано на ' + esc(fmtDateTimeY(d.post_at)) + '</span>');
|
||||
if (hidden) badge.push('<span class="digest-badge dim">Скрыто</span>');
|
||||
else if (d.hide_at) badge.push('<span class="digest-badge dim">Скроется ' + esc(fmtDateTimeY(d.hide_at)) + '</span>');
|
||||
|
||||
const preview = d.preview_path
|
||||
? '<div class="digest-head-img"><button type="button" class="digest-shot" data-img="' + esc(d.preview_path) + '" title="Открыть превью"><img class="digest-preview-img" src="' + esc(thumbSrc(d.preview_path)) + '" alt="превью"></button></div>'
|
||||
@@ -164,6 +149,11 @@
|
||||
actions.push('<button type="button" class="btn-link" data-action="pin" data-id="' + d.id + '" data-pin="' + (pinned ? '0' : '1') + '">' + (pinned ? 'Открепить' : 'Закрепить') + '</button>');
|
||||
}
|
||||
|
||||
const bodyText = d.body || '';
|
||||
const longBody = bodyText.length > 600;
|
||||
const bodyHtml = '<div class="digest-body' + (longBody ? ' clamp' : '') + '">' + esc(bodyText) + '</div>' +
|
||||
(longBody ? '<button type="button" class="digest-body-toggle" data-action="toggle-body" data-id="' + d.id + '">Показать полностью</button>' : '');
|
||||
|
||||
return '<div class="digest-card' + (pinned ? ' pinned' : '') + (hidden ? ' digest-hidden' : '') + '" data-id="' + d.id + '">' +
|
||||
'<div class="digest-head">' +
|
||||
'<h3 class="digest-title">' + esc(d.title) + '</h3>' +
|
||||
@@ -171,10 +161,10 @@
|
||||
'</div>' +
|
||||
preview +
|
||||
'<div class="digest-meta">' +
|
||||
'<span>' + esc(d.author_name || '—') + '</span>' +
|
||||
'<span>' + fmtShortIso(d.created_at) + '</span>' +
|
||||
'<span class="digest-meta-item"><i data-lucide="user"></i>' + esc(d.author_name || '—') + '</span>' +
|
||||
'<span class="digest-meta-item"><i data-lucide="calendar"></i>' + esc(fmtDateTimeY(d.published_at || d.created_at)) + '</span>' +
|
||||
'</div>' +
|
||||
'<div class="digest-body">' + esc(d.body) + '</div>' +
|
||||
bodyHtml +
|
||||
imagesHtml +
|
||||
'<div class="digest-foot">' +
|
||||
'<div class="digest-actions">' + actions.join('') + '</div>' +
|
||||
@@ -182,14 +172,55 @@
|
||||
'</div>';
|
||||
}
|
||||
|
||||
function filterDigests() {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return digests;
|
||||
return digests.filter(function(d) {
|
||||
return (d.title || '').toLowerCase().includes(q) ||
|
||||
(d.body || '').toLowerCase().includes(q) ||
|
||||
(d.author_name || '').toLowerCase().includes(q);
|
||||
});
|
||||
}
|
||||
|
||||
function updateCountInfo(list) {
|
||||
const el = document.getElementById('digestCount');
|
||||
if (!el) return;
|
||||
el.textContent = query.trim()
|
||||
? 'Найдено: ' + list.length + ' из ' + digests.length
|
||||
: (digests.length ? 'Сообщений: ' + digests.length : '');
|
||||
}
|
||||
|
||||
function renderDigests() {
|
||||
const el = document.getElementById('digestList');
|
||||
if (!el) return;
|
||||
if (!digestLoaded) return;
|
||||
const list = filterDigests();
|
||||
updateCountInfo(list);
|
||||
if (!digests.length) {
|
||||
el.innerHTML = '<div class="digest-empty">Сообщений пока нет</div>';
|
||||
el.innerHTML = '<div class="digest-empty"><i data-lucide="megaphone"></i>' +
|
||||
'<p>Сообщений пока нет</p>' +
|
||||
'<p class="sub">Опубликуйте важное объявление — его увидят все тьюторы и админы.</p>' +
|
||||
'</div>';
|
||||
renderIcons();
|
||||
return;
|
||||
}
|
||||
el.innerHTML = digests.map(digestCardHtml).join('');
|
||||
if (!list.length) {
|
||||
el.innerHTML = '<div class="digest-empty"><i data-lucide="search-x"></i>' +
|
||||
'<p>Ничего не найдено</p>' +
|
||||
'<p class="sub">По запросу «' + esc(query.trim()) + '» сообщений нет</p></div>';
|
||||
renderIcons();
|
||||
return;
|
||||
}
|
||||
el.innerHTML = list.map(digestCardHtml).join('');
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function renderLoadError() {
|
||||
const el = document.getElementById('digestList');
|
||||
if (!el) return;
|
||||
el.innerHTML = '<div class="digest-empty error"><i data-lucide="wifi-off"></i>' +
|
||||
'<p>Не удалось загрузить сообщения</p>' +
|
||||
'<button type="button" class="btn-primary ghost" data-action="reload">Повторить</button></div>';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
@@ -198,12 +229,18 @@
|
||||
try {
|
||||
res = await fetch(API + '/api/digests', { headers: hdr() });
|
||||
} catch (e) {
|
||||
if (!digestLoaded) renderLoadError();
|
||||
showToast('Ошибка сети при загрузке дайджеста', true);
|
||||
return;
|
||||
}
|
||||
if (!res.ok) return;
|
||||
if (!res.ok) {
|
||||
if (!digestLoaded) renderLoadError();
|
||||
showToast('Не удалось загрузить дайджест', true);
|
||||
return;
|
||||
}
|
||||
const data = await res.json().catch(function() { return {}; });
|
||||
digests = Array.isArray(data.items) ? data.items : (Array.isArray(data) ? data : []);
|
||||
digestLoaded = true;
|
||||
renderDigests();
|
||||
}
|
||||
|
||||
@@ -253,6 +290,15 @@
|
||||
btn.style.display = path || previewRemoved || previewFile ? '' : 'none';
|
||||
}
|
||||
|
||||
function updateCounts() {
|
||||
const t = document.getElementById('digestTitle');
|
||||
const b = document.getElementById('digestBody');
|
||||
const tc = document.getElementById('digestTitleCount');
|
||||
const bc = document.getElementById('digestBodyCount');
|
||||
if (t && tc) tc.textContent = t.value.length + ' / 200';
|
||||
if (b && bc) bc.textContent = b.value.length + ' / 5000';
|
||||
}
|
||||
|
||||
function openDigestModal(d) {
|
||||
editingId = d ? d.id : null;
|
||||
previewPath = d ? d.preview_path : null;
|
||||
@@ -260,8 +306,8 @@
|
||||
previewFile = null;
|
||||
digestImages = [];
|
||||
document.getElementById('digestModalTitle').textContent = d ? 'Редактирование сообщения' : 'Новое сообщение';
|
||||
document.getElementById('digestTitle').value = d ? escAttr(d.title) : '';
|
||||
document.getElementById('digestBody').value = d ? escAttr(d.body) : '';
|
||||
document.getElementById('digestTitle').value = d ? d.title : '';
|
||||
document.getElementById('digestBody').value = d ? d.body : '';
|
||||
document.getElementById('digestPostAt').value = d ? toLocalInput(d.post_at) : '';
|
||||
document.getElementById('digestHideAt').value = d ? toLocalInput(d.hide_at) : '';
|
||||
const pinRow = document.getElementById('digestPinned').closest('.settings-field');
|
||||
@@ -272,22 +318,26 @@
|
||||
document.getElementById('digestImageFile').value = '';
|
||||
const canManageImages = !!editingId;
|
||||
document.getElementById('digestImageAdd').style.display = canManageImages ? '' : 'none';
|
||||
document.getElementById('digestImagesWrap').style.display = canManageImages ? '' : 'none';
|
||||
document.getElementById('digestImagesWrap').style.display = '';
|
||||
if (canManageImages) {
|
||||
loadImages(editingId);
|
||||
} else {
|
||||
document.getElementById('digestImagesWrap').innerHTML = '<span class="digest-none">Сохраните сообщение, чтобы добавить картинки</span>';
|
||||
document.getElementById('digestImagesWrap').innerHTML = '<span class="digest-none">Добавятся после сохранения. Или вставьте картинку из буфера — Ctrl+V в поле текста, сообщение сохранится автоматически.</span>';
|
||||
}
|
||||
let draftRestored = false;
|
||||
if (editingId) {
|
||||
clearDraft();
|
||||
} else {
|
||||
restoreDraft();
|
||||
draftRestored = restoreDraft();
|
||||
}
|
||||
updateCounts();
|
||||
document.getElementById('digestModal').classList.add('open');
|
||||
document.getElementById('digestTitle').focus();
|
||||
if (draftRestored) showToast('Несохранённый черновик восстановлен');
|
||||
}
|
||||
|
||||
function closeDigestModal() {
|
||||
if (saving) return;
|
||||
if (hasDraft() && !confirm('Есть несохранённые изменения. Закрыть без сохранения?')) return;
|
||||
document.getElementById('digestModal').classList.remove('open');
|
||||
editingId = null;
|
||||
@@ -299,7 +349,6 @@
|
||||
}
|
||||
|
||||
async function uploadPreview(digestId) {
|
||||
if (!previewFile) return;
|
||||
if (previewRemoved) {
|
||||
try {
|
||||
await fetch(API + '/api/digests/' + digestId + '/preview', { method: 'DELETE', headers: hdr() });
|
||||
@@ -307,6 +356,7 @@
|
||||
previewRemoved = false;
|
||||
return;
|
||||
}
|
||||
if (!previewFile) return;
|
||||
const fd = new FormData();
|
||||
fd.append('image', previewFile);
|
||||
try {
|
||||
@@ -322,43 +372,66 @@
|
||||
}
|
||||
}
|
||||
|
||||
function setInvalid(el, on) {
|
||||
if (el) el.classList.toggle('invalid', !!on);
|
||||
}
|
||||
|
||||
async function doSaveDigest() {
|
||||
const title = document.getElementById('digestTitle').value.trim();
|
||||
const body = document.getElementById('digestBody').value.trim();
|
||||
const titleEl = document.getElementById('digestTitle');
|
||||
const bodyEl = document.getElementById('digestBody');
|
||||
const title = titleEl.value.trim();
|
||||
const body = bodyEl.value.trim();
|
||||
const isPinned = document.getElementById('digestPinned').checked;
|
||||
const postAt = inputToIso(document.getElementById('digestPostAt').value);
|
||||
const hideAt = inputToIso(document.getElementById('digestHideAt').value);
|
||||
if (!title) { showToast('Введите заголовок', true); return null; }
|
||||
if (!body) { showToast('Введите текст сообщения', true); return null; }
|
||||
if (!title || !body) {
|
||||
setInvalid(titleEl, !title);
|
||||
setInvalid(bodyEl, !body);
|
||||
if (!title) titleEl.focus(); else bodyEl.focus();
|
||||
showToast(!title ? 'Введите заголовок' : 'Введите текст сообщения', true);
|
||||
return null;
|
||||
}
|
||||
if (hideAt && postAt && new Date(hideAt).getTime() <= new Date(postAt).getTime()) {
|
||||
showToast('Дата скрытия должна быть позже даты публикации', true);
|
||||
document.getElementById('digestHideAt').focus();
|
||||
return null;
|
||||
}
|
||||
if (saving) return null;
|
||||
const payload = { title: title, body: body, is_pinned: isPinned, preview_path: previewPath || null, post_at: postAt, hide_at: hideAt };
|
||||
const saveBtn = document.getElementById('digestSave');
|
||||
saving = true;
|
||||
let res;
|
||||
saveBtn.disabled = true;
|
||||
saveBtn.textContent = 'Сохранение…';
|
||||
try {
|
||||
if (editingId) {
|
||||
res = await fetch(API + '/api/digests/' + editingId, {
|
||||
method: 'PUT', headers: hdrJson(), body: JSON.stringify(payload)
|
||||
});
|
||||
} else {
|
||||
res = await fetch(API + '/api/digests', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) });
|
||||
let res;
|
||||
try {
|
||||
if (editingId) {
|
||||
res = await fetch(API + '/api/digests/' + editingId, {
|
||||
method: 'PUT', headers: hdrJson(), body: JSON.stringify(payload)
|
||||
});
|
||||
} else {
|
||||
res = await fetch(API + '/api/digests', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) });
|
||||
}
|
||||
} catch (e) {
|
||||
showToast('Ошибка сети', true);
|
||||
return null;
|
||||
}
|
||||
} catch (e) {
|
||||
const data = await res.json().catch(function() { return {}; });
|
||||
if (!res.ok) {
|
||||
showToast(data.error || 'Ошибка при сохранении', true);
|
||||
return null;
|
||||
}
|
||||
const savedId = editingId || (data.item && data.item.id);
|
||||
if (savedId) {
|
||||
await uploadPreview(savedId);
|
||||
previewFile = null;
|
||||
}
|
||||
return savedId;
|
||||
} finally {
|
||||
saving = false;
|
||||
showToast('Ошибка сети', true);
|
||||
return null;
|
||||
saveBtn.disabled = false;
|
||||
saveBtn.textContent = 'Сохранить';
|
||||
}
|
||||
const data = await res.json().catch(function() { return {}; });
|
||||
saving = false;
|
||||
if (!res.ok) {
|
||||
showToast(data.error || 'Ошибка при сохранении', true);
|
||||
return null;
|
||||
}
|
||||
const savedId = editingId || (data.item && data.item.id);
|
||||
if (savedId) {
|
||||
await uploadPreview(savedId);
|
||||
previewFile = null;
|
||||
}
|
||||
return savedId;
|
||||
}
|
||||
|
||||
async function saveDigest() {
|
||||
@@ -404,6 +477,9 @@
|
||||
if (!saved) return;
|
||||
targetId = saved;
|
||||
editingId = targetId;
|
||||
clearDraft();
|
||||
document.getElementById('digestModalTitle').textContent = 'Редактирование сообщения';
|
||||
showToast('Сообщение сохранено — картинка добавляется к нему');
|
||||
document.getElementById('digestImageAdd').style.display = '';
|
||||
document.getElementById('digestImagesWrap').style.display = '';
|
||||
}
|
||||
@@ -548,7 +624,6 @@
|
||||
document.getElementById('digestSave').addEventListener('click', saveDigest);
|
||||
document.getElementById('digestPreviewFile').addEventListener('change', addPreviewFile);
|
||||
document.getElementById('digestPreviewRemove').addEventListener('click', removePreview);
|
||||
document.getElementById('digestImageAdd').addEventListener('click', addImages);
|
||||
document.getElementById('digestImageFile').addEventListener('change', addImages);
|
||||
document.getElementById('digestModal').addEventListener('paste', digestPaste);
|
||||
const draftTitle = document.getElementById('digestTitle');
|
||||
@@ -556,7 +631,11 @@
|
||||
const draftPinned = document.getElementById('digestPinned');
|
||||
const draftPostAt = document.getElementById('digestPostAt');
|
||||
const draftHideAt = document.getElementById('digestHideAt');
|
||||
[draftTitle, draftBody].forEach(el => el && el.addEventListener('input', persistDraft));
|
||||
[draftTitle, draftBody].forEach(el => el && el.addEventListener('input', function() {
|
||||
persistDraft();
|
||||
updateCounts();
|
||||
setInvalid(el, false);
|
||||
}));
|
||||
[draftPinned, draftPostAt, draftHideAt].forEach(el => el && el.addEventListener('change', persistDraft));
|
||||
document.getElementById('digestImagesWrap').addEventListener('click', function(e) {
|
||||
const btn = e.target.closest('[data-action="del-image"]');
|
||||
@@ -568,12 +647,20 @@
|
||||
document.addEventListener('keydown', function(e) {
|
||||
const m = document.getElementById('digestModal');
|
||||
const open = m && m.classList.contains('open');
|
||||
if (e.key === 'Escape' && open) closeDigestModal();
|
||||
if (!open) return;
|
||||
if (e.key === 'Escape') { closeDigestModal(); return; }
|
||||
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) {
|
||||
e.preventDefault();
|
||||
const tag = document.activeElement && document.activeElement.tagName;
|
||||
if (tag !== 'INPUT' || document.activeElement.type !== 'file') saveDigest();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function bindPage() {
|
||||
document.getElementById('digestNewBtn').addEventListener('click', function() { openDigestModal(null); });
|
||||
const search = document.getElementById('digestSearch');
|
||||
if (search) search.addEventListener('input', function() { query = search.value; renderDigests(); });
|
||||
document.addEventListener('click', async function(e) {
|
||||
const actEl = e.target.closest('[data-action]');
|
||||
if (actEl) {
|
||||
@@ -586,6 +673,18 @@
|
||||
}
|
||||
if (action === 'delete') { await removeDigest(id); return; }
|
||||
if (action === 'pin') { await togglePin(id, actEl.dataset.pin === '1'); return; }
|
||||
if (action === 'toggle-body') {
|
||||
const card = actEl.closest('.digest-card');
|
||||
if (card) {
|
||||
const body = card.querySelector('.digest-body');
|
||||
if (body) {
|
||||
const clamped = body.classList.toggle('clamp');
|
||||
actEl.textContent = clamped ? 'Показать полностью' : 'Свернуть';
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (action === 'reload') { await loadDigests(); return; }
|
||||
return;
|
||||
}
|
||||
});
|
||||
@@ -611,7 +710,7 @@
|
||||
const mine = currentUser && d.author_id === currentUser.id;
|
||||
if (admin || mine) openDigestModal(d);
|
||||
else {
|
||||
const card = document.querySelector('[data-id="' + id + '"]');
|
||||
const card = document.querySelector('[data-page="digest"] .digest-card[data-id="' + id + '"]');
|
||||
if (card) { card.scrollIntoView({ behavior: 'smooth', block: 'center' }); card.classList.add('digest-highlight'); setTimeout(function() { card.classList.remove('digest-highlight'); }, 1500); }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user