723 lines
29 KiB
JavaScript
723 lines
29 KiB
JavaScript
(async function() {
|
||
'use strict';
|
||
let digests = [];
|
||
let editingId = null;
|
||
let saving = false;
|
||
let query = '';
|
||
let digestLoaded = false;
|
||
let previewPath = null;
|
||
let previewRemoved = false;
|
||
let previewFile = null;
|
||
let digestImages = [];
|
||
const DRAFT_KEY = 'whatido:digest:draft';
|
||
|
||
function draftPayload() {
|
||
const titleEl = document.getElementById('digestTitle');
|
||
const bodyEl = document.getElementById('digestBody');
|
||
const pinnedEl = document.getElementById('digestPinned');
|
||
const postAtEl = document.getElementById('digestPostAt');
|
||
const hideAtEl = document.getElementById('digestHideAt');
|
||
return {
|
||
title: titleEl ? titleEl.value : '',
|
||
body: bodyEl ? bodyEl.value : '',
|
||
isPinned: pinnedEl ? pinnedEl.checked : false,
|
||
postAt: postAtEl ? postAtEl.value : '',
|
||
hideAt: hideAtEl ? hideAtEl.value : '',
|
||
previewPath: previewPath || null
|
||
};
|
||
}
|
||
|
||
function persistDraft() {
|
||
try { localStorage.setItem(DRAFT_KEY, JSON.stringify(draftPayload())); } catch (e) {}
|
||
}
|
||
|
||
function restoreDraft() {
|
||
try {
|
||
const raw = localStorage.getItem(DRAFT_KEY);
|
||
if (!raw) return;
|
||
const d = JSON.parse(raw);
|
||
if (!d || typeof d !== 'object') return;
|
||
const titleEl = document.getElementById('digestTitle');
|
||
const bodyEl = document.getElementById('digestBody');
|
||
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;
|
||
if (postAtEl && d.postAt != null) postAtEl.value = d.postAt;
|
||
if (hideAtEl && d.hideAt != null) hideAtEl.value = d.hideAt;
|
||
previewPath = d.previewPath || null;
|
||
showPreview(previewPath);
|
||
restored = !!(d.title || d.body || d.postAt || d.hideAt || previewPath || d.isPinned);
|
||
return restored;
|
||
} catch { return false; }
|
||
}
|
||
|
||
function clearDraft() {
|
||
try { localStorage.removeItem(DRAFT_KEY); } catch (e) {}
|
||
}
|
||
|
||
function hasDraft() {
|
||
try {
|
||
const raw = localStorage.getItem(DRAFT_KEY);
|
||
if (!raw) return false;
|
||
const d = JSON.parse(raw);
|
||
return Boolean(d && (d.title || d.body || d.postAt || d.hideAt || d.previewPath || d.isPinned));
|
||
} catch { return false; }
|
||
}
|
||
|
||
function esc(s) {
|
||
return String(s || '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
|
||
}
|
||
|
||
function tzOffsetMinutes(instant) {
|
||
try {
|
||
const d = new Date(instant);
|
||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: DateTime.tz, year: 'numeric', month: '2-digit', day: '2-digit',
|
||
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
|
||
}).formatToParts(d);
|
||
const get = name => Number(parts.find(p => p.type === name)?.value || 0);
|
||
const asUtc = new Date(Date.UTC(get('year'), get('month') - 1, get('day'), get('hour'), get('minute'), get('second')));
|
||
return -Math.round((d.getTime() - asUtc.getTime()) / 60000);
|
||
} catch { return 0; }
|
||
}
|
||
|
||
function toLocalInput(iso) {
|
||
if (!iso) return '';
|
||
try {
|
||
const d = new Date(iso);
|
||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: DateTime.tz, year: 'numeric', month: '2-digit', day: '2-digit',
|
||
hour: '2-digit', minute: '2-digit', hour12: false
|
||
}).formatToParts(d);
|
||
const get = name => parts.find(p => p.type === name)?.value || '';
|
||
return `${get('year')}-${get('month')}-${get('day')}T${get('hour')}:${get('minute')}`;
|
||
} catch { return ''; }
|
||
}
|
||
|
||
function inputToIso(localDt) {
|
||
if (!localDt) return null;
|
||
try {
|
||
const [datePart, timePart] = String(localDt).split('T');
|
||
const [y, mo, d] = datePart.split('-').map(Number);
|
||
const [h, mi] = timePart.split(':').map(Number);
|
||
const ref = new Date(Date.UTC(y, mo - 1, d, h, mi, 0, 0));
|
||
const off = tzOffsetMinutes(ref);
|
||
return new Date(ref.getTime() - off * 60000).toISOString();
|
||
} catch { return null; }
|
||
}
|
||
|
||
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 = 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 (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>'
|
||
: '';
|
||
|
||
const images = Array.isArray(d.images) ? d.images : [];
|
||
let imagesHtml = '';
|
||
if (images.length) {
|
||
imagesHtml = '<div class="digest-images-row">' + images.slice(0, 4).map(function(img, i) {
|
||
return '<button type="button" class="digest-shot" data-img="' + esc(img.path) + '" data-gal-index="' + i + '" title="' + esc(img.name || '') + '" aria-label="' + esc(img.name || '') + '">' +
|
||
'<img class="digest-card-thumb" src="' + esc(thumbSrc(img.path)) + '" alt="' + esc(img.name || '') + '" loading="lazy" decoding="async">' +
|
||
'<span class="digest-shot-zoom" aria-hidden="true"><i data-lucide="maximize-2"></i></span>' +
|
||
'</button>';
|
||
}).join('') + (images.length > 4 ? '<span class="digest-none">+ ' + (images.length - 4) + '</span>' : '') + '</div>';
|
||
}
|
||
|
||
const actions = [];
|
||
if (canEdit) {
|
||
actions.push('<button type="button" class="btn-link" data-action="edit" data-id="' + d.id + '">Изменить</button>');
|
||
actions.push('<button type="button" class="btn-link danger" data-action="delete" data-id="' + d.id + '">Удалить</button>');
|
||
}
|
||
if (admin) {
|
||
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>' +
|
||
badge.join('') +
|
||
'</div>' +
|
||
preview +
|
||
'<div class="digest-meta">' +
|
||
'<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>' +
|
||
bodyHtml +
|
||
imagesHtml +
|
||
'<div class="digest-foot">' +
|
||
'<div class="digest-actions">' + actions.join('') + '</div>' +
|
||
'</div>' +
|
||
'</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"><i data-lucide="megaphone"></i>' +
|
||
'<p>Сообщений пока нет</p>' +
|
||
'<p class="sub">Опубликуйте важное объявление — его увидят все тьюторы и админы.</p>' +
|
||
'</div>';
|
||
renderIcons();
|
||
return;
|
||
}
|
||
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();
|
||
}
|
||
|
||
async function loadDigests() {
|
||
let res;
|
||
try {
|
||
res = await fetch(API + '/api/digests', { headers: hdr() });
|
||
} catch (e) {
|
||
if (!digestLoaded) renderLoadError();
|
||
showToast('Ошибка сети при загрузке дайджеста', true);
|
||
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();
|
||
}
|
||
|
||
async function loadImages(digestId) {
|
||
let res;
|
||
try {
|
||
res = await fetch(API + '/api/digests/' + digestId + '/images', { headers: hdr() });
|
||
} catch (e) {
|
||
showToast('Ошибка сети при загрузке вложений', true);
|
||
return [];
|
||
}
|
||
if (!res.ok) return [];
|
||
const data = await res.json().catch(function() { return {}; });
|
||
digestImages = Array.isArray(data.items) ? data.items : [];
|
||
renderImageGallery();
|
||
return digestImages;
|
||
}
|
||
|
||
function renderImageGallery() {
|
||
const wrap = document.getElementById('digestImagesWrap');
|
||
if (!wrap) return;
|
||
if (!digestImages.length) {
|
||
wrap.innerHTML = '<span class="digest-none">Ещё нет картинок</span>';
|
||
return;
|
||
}
|
||
wrap.innerHTML = digestImages.map(function(img) {
|
||
return '<div class="digest-image" data-id="' + img.id + '">' +
|
||
'<img src="' + esc(thumbSrc(img.path)) + '" data-img="' + esc(img.path) + '" alt="">' +
|
||
'<button type="button" class="digest-image-remove" data-action="del-image" data-id="' + img.id + '">×</button>' +
|
||
'</div>';
|
||
}).join('');
|
||
}
|
||
|
||
function showPreview(path) {
|
||
const img = document.getElementById('digestPreviewImg');
|
||
const wrap = document.getElementById('digestPreviewWrap');
|
||
const btn = document.getElementById('digestPreviewRemove');
|
||
if (path) {
|
||
img.src = thumbSrc(path);
|
||
img.style.display = 'block';
|
||
previewPath = path;
|
||
} else {
|
||
img.src = '';
|
||
img.style.display = 'none';
|
||
previewPath = null;
|
||
}
|
||
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;
|
||
previewRemoved = false;
|
||
previewFile = null;
|
||
digestImages = [];
|
||
document.getElementById('digestModalTitle').textContent = d ? 'Редактирование сообщения' : 'Новое сообщение';
|
||
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');
|
||
const pinInput = document.getElementById('digestPinned');
|
||
pinInput.checked = d ? !!d.is_pinned : false;
|
||
pinRow.style.display = isAdmin() ? '' : 'none';
|
||
showPreview(d ? d.preview_path : null);
|
||
document.getElementById('digestImageFile').value = '';
|
||
const canManageImages = !!editingId;
|
||
document.getElementById('digestImageAdd').style.display = canManageImages ? '' : 'none';
|
||
document.getElementById('digestImagesWrap').style.display = '';
|
||
if (canManageImages) {
|
||
loadImages(editingId);
|
||
} else {
|
||
document.getElementById('digestImagesWrap').innerHTML = '<span class="digest-none">Добавятся после сохранения. Или вставьте картинку из буфера — Ctrl+V в поле текста, сообщение сохранится автоматически.</span>';
|
||
}
|
||
let draftRestored = false;
|
||
if (editingId) {
|
||
clearDraft();
|
||
} else {
|
||
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;
|
||
previewPath = null;
|
||
previewRemoved = false;
|
||
previewFile = null;
|
||
digestImages = [];
|
||
clearDraft();
|
||
}
|
||
|
||
async function uploadPreview(digestId) {
|
||
if (previewRemoved) {
|
||
try {
|
||
await fetch(API + '/api/digests/' + digestId + '/preview', { method: 'DELETE', headers: hdr() });
|
||
} catch (e) { console.error('preview clear:', e); }
|
||
previewRemoved = false;
|
||
return;
|
||
}
|
||
if (!previewFile) return;
|
||
const fd = new FormData();
|
||
fd.append('image', previewFile);
|
||
try {
|
||
const res = await fetch(API + '/api/digests/' + digestId + '/preview', {
|
||
method: 'POST', headers: hdr(), body: fd
|
||
});
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(function() { return {}; });
|
||
showToast(data.error || 'Не удалось загрузить превью', true);
|
||
}
|
||
} catch (e) {
|
||
showToast('Ошибка сети при загрузке превью', true);
|
||
}
|
||
}
|
||
|
||
function setInvalid(el, on) {
|
||
if (el) el.classList.toggle('invalid', !!on);
|
||
}
|
||
|
||
async function doSaveDigest() {
|
||
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 || !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;
|
||
saveBtn.disabled = true;
|
||
saveBtn.textContent = 'Сохранение…';
|
||
try {
|
||
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;
|
||
}
|
||
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;
|
||
saveBtn.disabled = false;
|
||
saveBtn.textContent = 'Сохранить';
|
||
}
|
||
}
|
||
|
||
async function saveDigest() {
|
||
const savedId = await doSaveDigest();
|
||
if (savedId === null) return;
|
||
if (!editingId) {
|
||
showToast('Сообщение создано');
|
||
clearDraft();
|
||
closeDigestModal();
|
||
await loadDigests();
|
||
return;
|
||
}
|
||
showToast('Сообщение обновлено');
|
||
clearDraft();
|
||
closeDigestModal();
|
||
await loadDigests();
|
||
}
|
||
|
||
async function digestPaste(e) {
|
||
const m = document.getElementById('digestModal');
|
||
if (!m || !m.classList.contains('open')) return;
|
||
const active = document.activeElement;
|
||
if (!active || !m.contains(active)) return;
|
||
const clip = e.clipboardData;
|
||
if (!clip) return;
|
||
const pasted = [];
|
||
for (const item of Array.from(clip.items || [])) {
|
||
if (item.kind !== 'file') continue;
|
||
const file = item.getAsFile();
|
||
if (file && /^image\//i.test(file.type || '')) pasted.push(file);
|
||
}
|
||
if (!pasted.length && clip.files && clip.files.length) {
|
||
for (const f of Array.from(clip.files)) {
|
||
if (/^image\//i.test(f.type || '')) pasted.push(f);
|
||
}
|
||
}
|
||
if (!pasted.length) return;
|
||
e.preventDefault();
|
||
|
||
let targetId = editingId;
|
||
if (!targetId) {
|
||
const saved = await doSaveDigest();
|
||
if (!saved) return;
|
||
targetId = saved;
|
||
editingId = targetId;
|
||
clearDraft();
|
||
document.getElementById('digestModalTitle').textContent = 'Редактирование сообщения';
|
||
showToast('Сообщение сохранено — картинка добавляется к нему');
|
||
document.getElementById('digestImageAdd').style.display = '';
|
||
document.getElementById('digestImagesWrap').style.display = '';
|
||
}
|
||
|
||
let pending = pasted.length, failed = 0;
|
||
for (const file of pasted) {
|
||
const fd = new FormData();
|
||
fd.append('image', file);
|
||
try {
|
||
const res = await fetch(API + '/api/digests/' + targetId + '/images', {
|
||
method: 'POST', headers: hdr(), body: fd
|
||
});
|
||
if (!res.ok) { failed++; continue; }
|
||
const data = await res.json().catch(function() { return {}; });
|
||
if (data.item) digestImages.push(data.item);
|
||
} catch (err) { failed++; }
|
||
}
|
||
renderImageGallery();
|
||
await loadDigests();
|
||
if (pending) {
|
||
const ok = pending - failed;
|
||
if (failed) showToast('Вставлено ' + ok + ' из ' + pending + ' картинок', true);
|
||
else showToast('Картинок вставлено: ' + ok);
|
||
}
|
||
}
|
||
|
||
async function addPreviewFile() {
|
||
const input = document.getElementById('digestPreviewFile');
|
||
if (!input.files || !input.files.length) return;
|
||
previewFile = input.files[0];
|
||
previewRemoved = false;
|
||
const url = URL.createObjectURL(previewFile);
|
||
const img = document.getElementById('digestPreviewImg');
|
||
img.src = url;
|
||
img.style.display = 'block';
|
||
document.getElementById('digestPreviewRemove').style.display = '';
|
||
input.value = '';
|
||
showToast('Превью выбрано, загрузится при сохранении');
|
||
}
|
||
|
||
async function removePreview() {
|
||
previewRemoved = true;
|
||
previewFile = null;
|
||
document.getElementById('digestPreviewImg').src = '';
|
||
document.getElementById('digestPreviewImg').style.display = 'none';
|
||
document.getElementById('digestPreviewRemove').style.display = 'none';
|
||
previewPath = null;
|
||
}
|
||
|
||
async function addImages() {
|
||
if (!editingId) { showToast('Сначала сохраните сообщение', true); return; }
|
||
const input = document.getElementById('digestImageFile');
|
||
if (!input.files || !input.files.length) return;
|
||
const files = Array.from(input.files);
|
||
let pending = files.length;
|
||
let failed = 0;
|
||
input.value = '';
|
||
for (const file of files) {
|
||
const fd = new FormData();
|
||
fd.append('image', file);
|
||
try {
|
||
const res = await fetch(API + '/api/digests/' + editingId + '/images', {
|
||
method: 'POST', headers: hdr(), body: fd
|
||
});
|
||
if (!res.ok) {
|
||
failed++;
|
||
continue;
|
||
}
|
||
const data = await res.json().catch(function() { return {}; });
|
||
if (data.item) digestImages.push(data.item);
|
||
} catch (e) {
|
||
failed++;
|
||
}
|
||
}
|
||
if (pending) {
|
||
renderImageGallery();
|
||
await loadDigests();
|
||
if (failed) showToast('Загружено ' + (pending - failed) + ' из ' + pending + ' картинок', true);
|
||
else showToast('Картинки добавлены');
|
||
}
|
||
}
|
||
|
||
async function removeImage(imageId) {
|
||
if (!confirm('Удалить картинку из сообщения и с диска?')) return;
|
||
let res;
|
||
try {
|
||
res = await fetch(API + '/api/digests/images/' + imageId, { method: 'DELETE', headers: hdr() });
|
||
} catch (e) {
|
||
showToast('Ошибка сети', true);
|
||
return;
|
||
}
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(function() { return {}; });
|
||
showToast(data.error || 'Не удалось удалить картинку', true);
|
||
return;
|
||
}
|
||
digestImages = digestImages.filter(function(img) { return img.id !== imageId; });
|
||
renderImageGallery();
|
||
await loadDigests();
|
||
showToast('Картинка удалена');
|
||
}
|
||
|
||
async function togglePin(id, toPin) {
|
||
let res;
|
||
try {
|
||
res = await fetch(API + '/api/digests/' + id + '/pin', { method: 'PUT', headers: hdr() });
|
||
} catch (e) {
|
||
showToast('Ошибка сети', true);
|
||
return;
|
||
}
|
||
const data = await res.json().catch(function() { return {}; });
|
||
if (!res.ok) {
|
||
showToast(data.error || 'Ошибка', true);
|
||
return;
|
||
}
|
||
await loadDigests();
|
||
showToast(toPin ? 'Закреплено' : 'Откреплено');
|
||
}
|
||
|
||
async function removeDigest(id) {
|
||
if (!confirm('Удалить это сообщение из дайджеста?')) return;
|
||
let res;
|
||
try {
|
||
res = await fetch(API + '/api/digests/' + id, { method: 'DELETE', headers: hdr() });
|
||
} catch (e) {
|
||
showToast('Ошибка сети', true);
|
||
return;
|
||
}
|
||
if (!res.ok) {
|
||
const data = await res.json().catch(function() { return {}; });
|
||
showToast(data.error || 'Ошибка при удалении', true);
|
||
return;
|
||
}
|
||
digests = digests.filter(function(d) { return d.id !== id; });
|
||
renderDigests();
|
||
showToast('Сообщение удалено');
|
||
}
|
||
|
||
function bindModal() {
|
||
document.getElementById('digestModalClose').addEventListener('click', closeDigestModal);
|
||
document.getElementById('digestCancel').addEventListener('click', closeDigestModal);
|
||
document.getElementById('digestSave').addEventListener('click', saveDigest);
|
||
document.getElementById('digestPreviewFile').addEventListener('change', addPreviewFile);
|
||
document.getElementById('digestPreviewRemove').addEventListener('click', removePreview);
|
||
document.getElementById('digestImageFile').addEventListener('change', addImages);
|
||
document.getElementById('digestModal').addEventListener('paste', digestPaste);
|
||
const draftTitle = document.getElementById('digestTitle');
|
||
const draftBody = document.getElementById('digestBody');
|
||
const draftPinned = document.getElementById('digestPinned');
|
||
const draftPostAt = document.getElementById('digestPostAt');
|
||
const draftHideAt = document.getElementById('digestHideAt');
|
||
[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"]');
|
||
if (btn) removeImage(parseInt(btn.dataset.id, 10));
|
||
});
|
||
document.getElementById('digestModal').addEventListener('click', function(e) {
|
||
if (e.target === e.currentTarget) closeDigestModal();
|
||
});
|
||
document.addEventListener('keydown', function(e) {
|
||
const m = document.getElementById('digestModal');
|
||
const open = m && m.classList.contains('open');
|
||
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) {
|
||
const action = actEl.dataset.action;
|
||
const id = parseInt(actEl.dataset.id, 10);
|
||
if (action === 'edit') {
|
||
const d = digests.find(function(x) { return x.id === id; });
|
||
if (d) openDigestModal(d);
|
||
return;
|
||
}
|
||
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;
|
||
}
|
||
});
|
||
}
|
||
|
||
async function init() {
|
||
if (!(await checkAuth())) return;
|
||
buildSidebar(document.body.dataset.page);
|
||
const nb = document.getElementById('digestNewBtn');
|
||
if (nb) nb.style.display = isAdmin() ? '' : 'none';
|
||
bindModal();
|
||
bindPage();
|
||
renderIcons();
|
||
await loadDigests();
|
||
const params = new URLSearchParams(location.search);
|
||
const idParam = params.get('id');
|
||
if (idParam) {
|
||
const id = parseInt(idParam, 10);
|
||
if (Number.isInteger(id)) {
|
||
const d = digests.find(function(x) { return x.id === id; });
|
||
if (d) {
|
||
const admin = isAdmin();
|
||
const mine = currentUser && d.author_id === currentUser.id;
|
||
if (admin || mine) openDigestModal(d);
|
||
else {
|
||
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); }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
init();
|
||
})();
|